2 * Copyright (c) 2004-2008 Apple Computer, 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@
34 - PMRootDomain calls IOHibernateSystemSleep() before system sleep
35 (devices awake, normal execution context)
36 - IOHibernateSystemSleep opens the hibernation file (or partition) at the bsd level,
37 grabs its extents and searches for a polling driver willing to work with that IOMedia.
38 The BSD code makes an ioctl to the storage driver to get the partition base offset to
39 the disk, and other ioctls to get the transfer constraints
40 If successful, the file is written to make sure its initially not bootable (in case of
41 later failure) and nvram set to point to the first block of the file. (Has to be done
42 here so blocking is possible in nvram support).
43 hibernate_setup() in osfmk is called to allocate page bitmaps for all dram, and
44 page out any pages it wants to (currently zero, but probably some percentage of memory).
45 Its assumed just allocating pages will cause the VM system to naturally select the best
46 pages for eviction. It also copies processor flags needed for the restore path and sets
47 a flag in the boot processor proc info.
48 gIOHibernateState = kIOHibernateStateHibernating.
49 - Regular sleep progresses - some drivers may inspect the root domain property
50 kIOHibernateStateKey to modify behavior. The platform driver saves state to memory
51 as usual but leaves motherboard I/O on.
52 - Eventually the platform calls ml_ppc_sleep() in the shutdown context on the last cpu,
53 at which point memory is ready to be saved. mapping_hibernate_flush() is called to get
54 all ppc RC bits out of the hash table and caches into the mapping structures.
55 - hibernate_write_image() is called (still in shutdown context, no blocking or preemption).
56 hibernate_page_list_setall() is called to get a bitmap of dram pages that need to be saved.
57 All pages are assumed to be saved (as part of the wired image) unless explicitly subtracted
58 by hibernate_page_list_setall(), avoiding having to find arch dependent low level bits.
59 The image header and block list are written. The header includes the second file extent so
60 only the header block is needed to read the file, regardless of filesystem.
61 The kernel section "__HIB" is written uncompressed to the image. This section of code and data
62 (only) is used to decompress the image during wake/boot.
63 Some additional pages are removed from the bitmaps - the buffers used for hibernation.
64 The bitmaps are written to the image.
65 More areas are removed from the bitmaps (after they have been written to the image) - the
66 section "__HIB" pages and interrupt stack.
67 Each wired page is compressed and written and then each non-wired page. Compression and
68 disk writes are in parallel.
69 The image header is written to the start of the file and the polling driver closed.
70 The machine powers down (or sleeps).
74 - BootX sees the boot-image nvram variable containing the device and block number of the image,
75 reads the header and if the signature is correct proceeds. The boot-image variable is cleared.
76 - BootX reads the portion of the image used for wired pages, to memory. Its assumed this will fit
77 in the OF memory environment, and the image is decrypted. There is no decompression in BootX,
78 that is in the kernel's __HIB section.
79 - BootX copies the "__HIB" section to its correct position in memory, quiesces and calls its entry
80 hibernate_kernel_entrypoint(), passing the location of the image in memory. Translation is off,
81 only code & data in that section is safe to call since all the other wired pages are still
82 compressed in the image.
83 - hibernate_kernel_entrypoint() removes pages occupied by the raw image from the page bitmaps.
84 It uses the bitmaps to work out which pages can be uncompressed from the image to their final
85 location directly, and copies those that can't to interim free pages. When the image has been
86 completed, the copies are uncompressed, overwriting the wired image pages.
87 hibernate_restore_phys_page() (in osfmk since its arch dependent, but part of the "__HIB" section)
88 is used to get pages into place for 64bit.
89 - the reset vector is called (at least on ppc), the kernel proceeds on a normal wake, with some
90 changes conditional on the per proc flag - before VM is turned on the boot cpu, all mappings
91 are removed from the software strutures, and the hash table is reinitialized.
92 - After the platform CPU init code is called, hibernate_machine_init() is called to restore the rest
93 of memory, using the polled mode driver, before other threads can run or any devices are turned on.
94 This reduces the memory usage for BootX and allows decompression in parallel with disk reads,
95 for the remaining non wired pages.
96 - The polling driver is closed down and regular wake proceeds. When the kernel calls iokit to wake
97 (normal execution context) hibernate_teardown() in osmfk is called to release any memory, the file
102 IOHibernateSystemSleep() finds a polled mode interface to the ATA controller via a property in the
103 registry, specifying an object of calls IOPolledInterface.
105 Before the system goes to sleep it searches from the IOMedia object (could be a filesystem or
106 partition) that the image is going to live, looking for polled interface properties. If it finds
107 one the IOMedia object is passed to a "probe" call for the interface to accept or reject. All the
108 interfaces found are kept in an ordered list.
110 There is an Open/Close pair of calls made to each of the interfaces at various stages since there are
111 few different contexts things happen in:
113 - there is an Open/Close (Preflight) made before any part of the system has slept (I/O is all
114 up and running) and after wake - this is safe to allocate memory and do anything. The device
115 ignores sleep requests from that point since its a waste of time if it goes to sleep and
116 immediately wakes back up for the image write.
118 - there is an Open/Close (BeforeSleep) pair made around the image write operations that happen
119 immediately before sleep. These can't block or allocate memory - the I/O system is asleep apart
120 from the low level bits (motherboard I/O etc). There is only one thread running. The close can be
121 used to flush and set the disk to sleep.
123 - there is an Open/Close (AfterSleep) pair made around the image read operations that happen
124 immediately after sleep. These can't block or allocate memory. This is happening after the platform
125 expert has woken the low level bits of the system, but most of the I/O system has not. There is only
128 For the actual I/O, all the ops are with respect to a single IOMemoryDescriptor that was passed
129 (prepared) to the Preflight Open() call. There is a read/write op, buffer offset to the IOMD for
130 the data, an offset to the disk and length (block aligned 64 bit numbers), and completion callback.
131 Each I/O is async but only one is ever outstanding. The polled interface has a checkForWork call
132 that is called for the hardware to check for events, and complete the I/O via the callback.
133 The hibernate path uses the same transfer constraints the regular cluster I/O path in BSD uses
137 #include <sys/systm.h>
139 #include <IOKit/IOWorkLoop.h>
140 #include <IOKit/IOCommandGate.h>
141 #include <IOKit/IOTimerEventSource.h>
142 #include <IOKit/IOPlatformExpert.h>
143 #include <IOKit/IOKitDebug.h>
144 #include <IOKit/IOTimeStamp.h>
145 #include <IOKit/pwr_mgt/RootDomain.h>
146 #include <IOKit/pwr_mgt/IOPMPrivate.h>
147 #include <IOKit/IOMessage.h>
148 #include <IOKit/IODeviceTreeSupport.h>
149 #include <IOKit/IOBSD.h>
150 #include "RootDomainUserClient.h"
151 #include <IOKit/pwr_mgt/IOPowerConnection.h>
152 #include "IOPMPowerStateQueue.h"
153 #include <IOKit/IOBufferMemoryDescriptor.h>
154 #include <crypto/aes.h>
157 #include <sys/conf.h>
158 #include <sys/stat.h>
159 #include <sys/fcntl.h> // (FWRITE, ...)
160 #include <sys/sysctl.h>
162 #include <IOKit/IOHibernatePrivate.h>
163 #include <IOKit/IOPolledInterface.h>
164 #include <IOKit/IONVRAM.h>
165 #include "IOHibernateInternal.h"
167 #include "IOKitKernelInternal.h"
169 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
171 extern unsigned int save_kdebug_enable
;
172 extern uint32_t gIOHibernateState
;
173 uint32_t gIOHibernateMode
;
174 static char gIOHibernateBootSignature
[256+1];
175 static char gIOHibernateFilename
[MAXPATHLEN
+1];
176 static uint32_t gIOHibernateFreeRatio
= 0; // free page target (percent)
177 uint32_t gIOHibernateFreeTime
= 0*1000; // max time to spend freeing pages (ms)
179 static IODTNVRAM
* gIOOptionsEntry
;
180 static IORegistryEntry
* gIOChosenEntry
;
181 #if defined(__i386__) || defined(__x86_64__)
182 static const OSSymbol
* gIOCreateEFIDevicePathSymbol
;
185 static IOPolledFileIOVars gFileVars
;
186 static IOHibernateVars gIOHibernateVars
;
187 static struct kern_direct_file_io_ref_t
* gIOHibernateFileRef
;
188 static hibernate_cryptvars_t gIOHibernateCryptWakeContext
;
190 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
192 enum { kXPRamAudioVolume
= 8 };
193 enum { kDefaultIOSize
= 128 * 1024 };
194 enum { kVideoMapSize
= 32 * 1024 * 1024 };
196 #ifndef kIOMediaPreferredBlockSizeKey
197 #define kIOMediaPreferredBlockSizeKey "Preferred Block Size"
200 #ifndef kIOBootPathKey
201 #define kIOBootPathKey "bootpath"
203 #ifndef kIOSelectedBootDeviceKey
204 #define kIOSelectedBootDeviceKey "boot-device"
208 enum { kIOHibernateMinPollersNeeded
= 2 };
210 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
212 // copy from phys addr to MD
215 IOMemoryDescriptorWriteFromPhysical(IOMemoryDescriptor
* md
,
216 IOByteCount offset
, addr64_t bytes
, IOByteCount length
)
218 addr64_t srcAddr
= bytes
;
219 IOByteCount remaining
;
221 remaining
= length
= min(length
, md
->getLength() - offset
);
222 while (remaining
) { // (process another target segment?)
226 dstAddr64
= md
->getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
230 // Clip segment length to remaining
231 if (dstLen
> remaining
)
235 bcopy_phys(srcAddr
, dstAddr64
, dstLen
);
237 copypv(srcAddr
, dstAddr64
, dstLen
,
238 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
247 return remaining
? kIOReturnUnderrun
: kIOReturnSuccess
;
250 // copy from MD to phys addr
253 IOMemoryDescriptorReadToPhysical(IOMemoryDescriptor
* md
,
254 IOByteCount offset
, addr64_t bytes
, IOByteCount length
)
256 addr64_t dstAddr
= bytes
;
257 IOByteCount remaining
;
259 remaining
= length
= min(length
, md
->getLength() - offset
);
260 while (remaining
) { // (process another target segment?)
264 srcAddr64
= md
->getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
268 // Clip segment length to remaining
269 if (dstLen
> remaining
)
273 bcopy_phys(srcAddr64
, dstAddr
, dstLen
);
275 copypv(srcAddr
, dstAddr64
, dstLen
,
276 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
285 return remaining
? kIOReturnUnderrun
: kIOReturnSuccess
;
288 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
291 hibernate_set_page_state(hibernate_page_list_t
* page_list
, hibernate_page_list_t
* page_list_wired
,
292 vm_offset_t ppnum
, vm_offset_t count
, uint32_t kind
)
297 case kIOHibernatePageStateUnwiredSave
:
299 for (; ppnum
< count
; ppnum
++)
301 hibernate_page_bitset(page_list
, FALSE
, ppnum
);
302 hibernate_page_bitset(page_list_wired
, TRUE
, ppnum
);
305 case kIOHibernatePageStateWiredSave
:
307 for (; ppnum
< count
; ppnum
++)
309 hibernate_page_bitset(page_list
, FALSE
, ppnum
);
310 hibernate_page_bitset(page_list_wired
, FALSE
, ppnum
);
313 case kIOHibernatePageStateFree
:
315 for (; ppnum
< count
; ppnum
++)
317 hibernate_page_bitset(page_list
, TRUE
, ppnum
);
318 hibernate_page_bitset(page_list_wired
, TRUE
, ppnum
);
322 panic("hibernate_set_page_state");
327 hibernate_page_list_iterate(hibernate_page_list_t
* list
, vm_offset_t
* pPage
)
329 uint32_t page
= *pPage
;
331 hibernate_bitmap_t
* bitmap
;
333 while ((bitmap
= hibernate_page_bitmap_pin(list
, &page
)))
335 count
= hibernate_page_bitmap_count(bitmap
, TRUE
, page
);
339 if (page
<= bitmap
->last_page
)
345 count
= hibernate_page_bitmap_count(bitmap
, FALSE
, page
);
352 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
355 IOHibernatePollerProbe(IOPolledFileIOVars
* vars
, IOService
* target
)
357 IOReturn err
= kIOReturnError
;
359 IOPolledInterface
* poller
;
361 for (idx
= vars
->pollers
->getCount() - 1; idx
>= 0; idx
--)
363 poller
= (IOPolledInterface
*) vars
->pollers
->getObject(idx
);
364 err
= poller
->probe(target
);
367 HIBLOG("IOPolledInterface::probe[%d] 0x%x\n", idx
, err
);
376 IOHibernatePollerOpen(IOPolledFileIOVars
* vars
, uint32_t state
, IOMemoryDescriptor
* md
)
378 IOReturn err
= kIOReturnError
;
380 IOPolledInterface
* poller
;
382 for (idx
= vars
->pollers
->getCount() - 1; idx
>= 0; idx
--)
384 poller
= (IOPolledInterface
*) vars
->pollers
->getObject(idx
);
385 err
= poller
->open(state
, md
);
388 HIBLOG("IOPolledInterface::open[%d] 0x%x\n", idx
, err
);
397 IOHibernatePollerClose(IOPolledFileIOVars
* vars
, uint32_t state
)
399 IOReturn err
= kIOReturnError
;
401 IOPolledInterface
* poller
;
404 (poller
= (IOPolledInterface
*) vars
->pollers
->getObject(idx
));
407 err
= poller
->close(state
);
409 HIBLOG("IOPolledInterface::close[%d] 0x%x\n", idx
, err
);
416 IOHibernatePollerIOComplete(void * target
,
419 UInt64 actualByteCount
)
421 IOPolledFileIOVars
* vars
= (IOPolledFileIOVars
*) parameter
;
423 vars
->ioStatus
= status
;
427 IOHibernatePollerIO(IOPolledFileIOVars
* vars
,
428 uint32_t operation
, uint32_t bufferOffset
,
429 uint64_t deviceOffset
, uint64_t length
)
432 IOReturn err
= kIOReturnError
;
433 IOPolledInterface
* poller
;
434 IOPolledCompletion completion
;
436 completion
.target
= 0;
437 completion
.action
= &IOHibernatePollerIOComplete
;
438 completion
.parameter
= vars
;
442 poller
= (IOPolledInterface
*) vars
->pollers
->getObject(0);
443 err
= poller
->startIO(operation
, bufferOffset
, deviceOffset
+ vars
->block0
, length
, completion
);
445 HIBLOG("IOPolledInterface::startIO[%d] 0x%x\n", 0, err
);
451 IOHibernatePollerIODone(IOPolledFileIOVars
* vars
, bool abortable
)
453 IOReturn err
= kIOReturnSuccess
;
455 IOPolledInterface
* poller
;
457 while (-1 == vars
->ioStatus
)
460 (poller
= (IOPolledInterface
*) vars
->pollers
->getObject(idx
));
464 newErr
= poller
->checkForWork();
465 if ((newErr
== kIOReturnAborted
) && !abortable
)
466 newErr
= kIOReturnSuccess
;
467 if (kIOReturnSuccess
== err
)
472 if ((kIOReturnSuccess
== err
) && abortable
&& hibernate_should_abort())
474 err
= kIOReturnAborted
;
475 HIBLOG("IOPolledInterface::checkForWork sw abort\n");
480 HIBLOG("IOPolledInterface::checkForWork[%d] 0x%x\n", idx
, err
);
484 err
= vars
->ioStatus
;
485 if (kIOReturnSuccess
!= err
)
486 HIBLOG("IOPolledInterface::ioStatus 0x%x\n", err
);
493 IOPolledInterface::checkAllForWork(void)
495 IOReturn err
= kIOReturnNotReady
;
497 IOPolledInterface
* poller
;
499 IOHibernateVars
* vars
= &gIOHibernateVars
;
501 if (!vars
->fileVars
|| !vars
->fileVars
->pollers
)
505 (poller
= (IOPolledInterface
*) vars
->fileVars
->pollers
->getObject(idx
));
508 err
= poller
->checkForWork();
510 HIBLOG("IOPolledInterface::checkAllForWork[%d] 0x%x\n", idx
, err
);
516 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
518 struct _OpenFileContext
525 file_extent_callback(void * ref
, uint64_t start
, uint64_t length
)
527 _OpenFileContext
* ctx
= (_OpenFileContext
*) ref
;
528 IOPolledFileExtent extent
;
530 extent
.start
= start
;
531 extent
.length
= length
;
533 ctx
->extents
->appendBytes(&extent
, sizeof(extent
));
538 IOPolledFileOpen( const char * filename
, IOBufferMemoryDescriptor
* ioBuffer
,
539 IOPolledFileIOVars
** fileVars
, OSData
** fileExtents
,
542 IOReturn err
= kIOReturnError
;
543 IOPolledFileIOVars
* vars
;
544 _OpenFileContext ctx
;
545 OSData
* extentsData
;
547 IORegistryEntry
* part
= 0;
548 OSDictionary
* matching
;
550 dev_t hibernate_image_dev
;
556 HIBLOG("sizeof(IOHibernateImageHeader) == %ld\n", sizeof(IOHibernateImageHeader
));
557 if (sizeof(IOHibernateImageHeader
) != 512)
561 vars
->buffer
= (uint8_t *) ioBuffer
->getBytesNoCopy();
562 vars
->bufferHalf
= 0;
563 vars
->bufferOffset
= 0;
564 vars
->bufferSize
= ioBuffer
->getLength() >> 1;
566 extentsData
= OSData::withCapacity(32);
568 ctx
.extents
= extentsData
;
570 vars
->fileRef
= kern_open_file_for_direct_io(filename
,
571 &file_extent_callback
, &ctx
,
572 &hibernate_image_dev
,
578 err
= kIOReturnNoSpace
;
581 gIOHibernateFileRef
= vars
->fileRef
;
583 if (kIOHibernateModeSSDInvert
& gIOHibernateMode
)
584 vars
->solid_state
= vars
->solid_state
? false : true;
586 HIBLOG("Opened file %s, size %qd, partition base 0x%qx, maxio %qx ssd %d\n", filename
, ctx
.size
,
587 vars
->block0
, maxiobytes
, vars
->solid_state
);
588 if (ctx
.size
< 1*1024*1024) // check against image size estimate!
590 err
= kIOReturnNoSpace
;
594 if (maxiobytes
< vars
->bufferSize
)
595 vars
->bufferSize
= maxiobytes
;
597 vars
->extentMap
= (IOPolledFileExtent
*) extentsData
->getBytesNoCopy();
599 matching
= IOService::serviceMatching("IOMedia");
600 num
= OSNumber::withNumber(major(hibernate_image_dev
), 32);
601 matching
->setObject(kIOBSDMajorKey
, num
);
603 num
= OSNumber::withNumber(minor(hibernate_image_dev
), 32);
604 matching
->setObject(kIOBSDMinorKey
, num
);
606 iter
= IOService::getMatchingServices(matching
);
610 part
= (IORegistryEntry
*) iter
->getNextObject();
618 IORegistryEntry
* next
;
619 IORegistryEntry
* child
;
622 num
= (OSNumber
*) part
->getProperty(kIOBSDMajorKey
);
625 major
= num
->unsigned32BitValue();
626 num
= (OSNumber
*) part
->getProperty(kIOBSDMinorKey
);
629 minor
= num
->unsigned32BitValue();
631 hibernate_image_dev
= makedev(major
, minor
);
633 vars
->pollers
= OSArray::withCapacity(4);
637 vars
->blockSize
= 512;
641 IOPolledInterface
* poller
;
644 obj
= next
->getProperty(kIOPolledInterfaceSupportKey
);
645 if (kOSBooleanFalse
== obj
)
647 vars
->pollers
->flushCollection();
650 else if ((poller
= OSDynamicCast(IOPolledInterface
, obj
)))
651 vars
->pollers
->setObject(poller
);
652 if ((num
= OSDynamicCast(OSNumber
, next
->getProperty(kIOMediaPreferredBlockSizeKey
))))
653 vars
->blockSize
= num
->unsigned32BitValue();
656 while ((next
= child
->getParentEntry(gIOServicePlane
))
657 && child
->isParent(next
, gIOServicePlane
, true));
659 HIBLOG("hibernate image major %d, minor %d, blocksize %ld, pollers %d\n",
660 major
, minor
, (long)vars
->blockSize
, vars
->pollers
->getCount());
661 if (vars
->pollers
->getCount() < kIOHibernateMinPollersNeeded
)
664 err
= IOHibernatePollerProbe(vars
, (IOService
*) part
);
665 if (kIOReturnSuccess
!= err
)
668 err
= IOHibernatePollerOpen(vars
, kIOPolledPreflightState
, ioBuffer
);
669 if (kIOReturnSuccess
!= err
)
673 *fileExtents
= extentsData
;
677 if ((extentsData
->getLength() >= sizeof(IOPolledFileExtent
)))
681 #if defined(__i386__) || defined(__x86_64__)
682 if (!gIOCreateEFIDevicePathSymbol
)
683 gIOCreateEFIDevicePathSymbol
= OSSymbol::withCString("CreateEFIDevicePath");
685 snprintf(str2
, sizeof(str2
), "%qx", vars
->extentMap
[0].start
);
687 err
= IOService::getPlatform()->callPlatformFunction(
688 gIOCreateEFIDevicePathSymbol
, false,
689 (void *) part
, (void *) str2
, (void *) true,
693 int len
= sizeof(str1
);
695 if (!part
->getPath(str1
, &len
, gIODTPlane
))
696 err
= kIOReturnNotFound
;
699 snprintf(str2
, sizeof(str2
), ",%qx", vars
->extentMap
[0].start
);
700 // (strip the plane name)
701 char * tail
= strchr(str1
, ':');
704 data
= OSData::withBytes(tail
+ 1, strlen(tail
+ 1));
705 data
->appendBytes(str2
, strlen(str2
));
708 if (kIOReturnSuccess
== err
)
711 HIBLOG("error 0x%x getting path\n", err
);
716 if (kIOReturnSuccess
!= err
)
718 HIBLOG("error 0x%x opening hibernation file\n", err
);
721 kern_close_file_for_direct_io(vars
->fileRef
);
722 gIOHibernateFileRef
= vars
->fileRef
= NULL
;
733 IOPolledFileClose( IOPolledFileIOVars
* vars
)
737 IOHibernatePollerClose(vars
, kIOPolledPostflightState
);
738 vars
->pollers
->release();
741 bzero(vars
, sizeof(IOPolledFileIOVars
));
743 return (kIOReturnSuccess
);
747 IOPolledFileSeek(IOPolledFileIOVars
* vars
, uint64_t position
)
749 IOPolledFileExtent
* extentMap
;
751 extentMap
= vars
->extentMap
;
753 vars
->position
= position
;
755 while (position
>= extentMap
->length
)
757 position
-= extentMap
->length
;
761 vars
->currentExtent
= extentMap
;
762 vars
->extentRemaining
= extentMap
->length
- position
;
763 vars
->extentPosition
= vars
->position
- position
;
765 if (vars
->bufferSize
<= vars
->extentRemaining
)
766 vars
->bufferLimit
= vars
->bufferSize
;
768 vars
->bufferLimit
= vars
->extentRemaining
;
770 return (kIOReturnSuccess
);
774 IOPolledFileWrite(IOPolledFileIOVars
* vars
,
775 const uint8_t * bytes
, IOByteCount size
,
776 hibernate_cryptvars_t
* cryptvars
)
778 IOReturn err
= kIOReturnSuccess
;
786 // seek to end of block & flush
787 size
= vars
->position
& (vars
->blockSize
- 1);
789 size
= vars
->blockSize
- size
;
791 // use some garbage for the fill
792 bytes
= vars
->buffer
+ vars
->bufferOffset
;
795 copy
= vars
->bufferLimit
- vars
->bufferOffset
;
803 bcopy(bytes
, vars
->buffer
+ vars
->bufferHalf
+ vars
->bufferOffset
, copy
);
807 bzero(vars
->buffer
+ vars
->bufferHalf
+ vars
->bufferOffset
, copy
);
810 vars
->bufferOffset
+= copy
;
811 vars
->position
+= copy
;
813 if (flush
&& vars
->bufferOffset
)
815 uint64_t offset
= (vars
->position
- vars
->bufferOffset
816 - vars
->extentPosition
+ vars
->currentExtent
->start
);
817 uint32_t length
= (vars
->bufferOffset
);
820 if (cryptvars
&& vars
->encryptStart
821 && (vars
->position
> vars
->encryptStart
)
822 && ((vars
->position
- length
) < vars
->encryptEnd
))
824 uint32_t encryptLen
, encryptStart
;
825 encryptLen
= vars
->position
- vars
->encryptStart
;
826 if (encryptLen
> length
)
828 encryptStart
= length
- encryptLen
;
829 if (vars
->position
> vars
->encryptEnd
)
830 encryptLen
-= (vars
->position
- vars
->encryptEnd
);
832 // encrypt the buffer
833 aes_encrypt_cbc(vars
->buffer
+ vars
->bufferHalf
+ encryptStart
,
834 &cryptvars
->aes_iv
[0],
835 encryptLen
/ AES_BLOCK_SIZE
,
836 vars
->buffer
+ vars
->bufferHalf
+ encryptStart
,
837 &cryptvars
->ctx
.encrypt
);
838 // save initial vector for following encrypts
839 bcopy(vars
->buffer
+ vars
->bufferHalf
+ encryptStart
+ encryptLen
- AES_BLOCK_SIZE
,
840 &cryptvars
->aes_iv
[0],
847 err
= IOHibernatePollerIODone(vars
, true);
848 if (kIOReturnSuccess
!= err
)
852 if (vars
->position
& (vars
->blockSize
- 1)) HIBLOG("misaligned file pos %qx\n", vars
->position
);
853 //if (length != vars->bufferSize) HIBLOG("short write of %qx ends@ %qx\n", length, offset + length);
855 err
= IOHibernatePollerIO(vars
, kIOPolledWrite
, vars
->bufferHalf
, offset
, length
);
856 if (kIOReturnSuccess
!= err
)
860 vars
->extentRemaining
-= vars
->bufferOffset
;
861 if (!vars
->extentRemaining
)
863 vars
->currentExtent
++;
864 vars
->extentRemaining
= vars
->currentExtent
->length
;
865 vars
->extentPosition
= vars
->position
;
866 if (!vars
->extentRemaining
)
868 err
= kIOReturnOverrun
;
873 vars
->bufferHalf
= vars
->bufferHalf
? 0 : vars
->bufferSize
;
874 vars
->bufferOffset
= 0;
875 if (vars
->bufferSize
<= vars
->extentRemaining
)
876 vars
->bufferLimit
= vars
->bufferSize
;
878 vars
->bufferLimit
= vars
->extentRemaining
;
889 IOPolledFileRead(IOPolledFileIOVars
* vars
,
890 uint8_t * bytes
, IOByteCount size
,
891 hibernate_cryptvars_t
* cryptvars
)
893 IOReturn err
= kIOReturnSuccess
;
896 // bytesWritten += size;
900 copy
= vars
->bufferLimit
- vars
->bufferOffset
;
906 bcopy(vars
->buffer
+ vars
->bufferHalf
+ vars
->bufferOffset
, bytes
, copy
);
910 vars
->bufferOffset
+= copy
;
911 // vars->position += copy;
913 if (vars
->bufferOffset
== vars
->bufferLimit
)
917 err
= IOHibernatePollerIODone(vars
, false);
918 if (kIOReturnSuccess
!= err
)
924 if (vars
->position
& (vars
->blockSize
- 1)) HIBLOG("misaligned file pos %qx\n", vars
->position
);
926 vars
->position
+= vars
->lastRead
;
927 vars
->extentRemaining
-= vars
->lastRead
;
928 vars
->bufferLimit
= vars
->lastRead
;
930 if (!vars
->extentRemaining
)
932 vars
->currentExtent
++;
933 vars
->extentRemaining
= vars
->currentExtent
->length
;
934 vars
->extentPosition
= vars
->position
;
935 if (!vars
->extentRemaining
)
937 err
= kIOReturnOverrun
;
943 uint64_t lastReadLength
= vars
->lastRead
;
944 uint64_t offset
= (vars
->position
945 - vars
->extentPosition
+ vars
->currentExtent
->start
);
946 if (vars
->extentRemaining
<= vars
->bufferSize
)
947 length
= vars
->extentRemaining
;
949 length
= vars
->bufferSize
;
950 vars
->lastRead
= length
;
952 //if (length != vars->bufferSize) HIBLOG("short read of %qx ends@ %qx\n", length, offset + length);
954 err
= IOHibernatePollerIO(vars
, kIOPolledRead
, vars
->bufferHalf
, offset
, length
);
955 if (kIOReturnSuccess
!= err
)
959 vars
->bufferHalf
= vars
->bufferHalf
? 0 : vars
->bufferSize
;
960 vars
->bufferOffset
= 0;
965 uint8_t thisVector
[AES_BLOCK_SIZE
];
966 // save initial vector for following decrypts
967 bcopy(&cryptvars
->aes_iv
[0], &thisVector
[0], AES_BLOCK_SIZE
);
968 bcopy(vars
->buffer
+ vars
->bufferHalf
+ lastReadLength
- AES_BLOCK_SIZE
,
969 &cryptvars
->aes_iv
[0], AES_BLOCK_SIZE
);
970 // decrypt the buffer
971 aes_decrypt_cbc(vars
->buffer
+ vars
->bufferHalf
,
973 lastReadLength
/ AES_BLOCK_SIZE
,
974 vars
->buffer
+ vars
->bufferHalf
,
975 &cryptvars
->ctx
.decrypt
);
985 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
988 IOHibernateSystemSleep(void)
996 IOHibernateVars
* vars
= &gIOHibernateVars
;
998 if (vars
->fileVars
&& vars
->fileVars
->fileRef
)
999 // already on the way down
1000 return (kIOReturnSuccess
);
1002 gIOHibernateState
= kIOHibernateStateInactive
;
1004 gIOHibernateDebugFlags
= 0;
1005 if (kIOLogHibernate
& gIOKitDebug
)
1006 gIOHibernateDebugFlags
|= kIOHibernateDebugRestoreLogs
;
1008 if (IOService::getPMRootDomain()->getHibernateSettings(
1009 &gIOHibernateMode
, &gIOHibernateFreeRatio
, &gIOHibernateFreeTime
))
1010 if (kIOHibernateModeSleep
& gIOHibernateMode
)
1011 // default to discard clean for safe sleep
1012 gIOHibernateMode
^= (kIOHibernateModeDiscardCleanInactive
1013 | kIOHibernateModeDiscardCleanActive
);
1015 if ((obj
= IOService::getPMRootDomain()->copyProperty(kIOHibernateFileKey
)))
1017 if ((str
= OSDynamicCast(OSString
, obj
)))
1018 strlcpy(gIOHibernateFilename
, str
->getCStringNoCopy(),
1019 sizeof(gIOHibernateFilename
));
1023 if (!gIOHibernateMode
|| !gIOHibernateFilename
[0])
1024 return (kIOReturnUnsupported
);
1026 HIBLOG("hibernate image path: %s\n", gIOHibernateFilename
);
1031 vars
->srcBuffer
= IOBufferMemoryDescriptor::withOptions(kIODirectionOutIn
,
1032 4 * page_size
, page_size
);
1033 vars
->ioBuffer
= IOBufferMemoryDescriptor::withOptions(kIODirectionOutIn
,
1034 2 * kDefaultIOSize
, page_size
);
1036 if (!vars
->srcBuffer
|| !vars
->ioBuffer
)
1038 err
= kIOReturnNoMemory
;
1042 err
= IOPolledFileOpen(gIOHibernateFilename
, vars
->ioBuffer
,
1043 &vars
->fileVars
, &vars
->fileExtents
, &data
);
1044 if (KERN_SUCCESS
!= err
)
1046 HIBLOG("IOPolledFileOpen(%x)\n", err
);
1049 if (vars
->fileVars
->fileRef
)
1051 // invalidate the image file
1052 gIOHibernateCurrentHeader
->signature
= kIOHibernateHeaderInvalidSignature
;
1053 int err
= kern_write_file(vars
->fileVars
->fileRef
, 0,
1054 (caddr_t
) gIOHibernateCurrentHeader
, sizeof(IOHibernateImageHeader
));
1055 if (KERN_SUCCESS
!= err
)
1056 HIBLOG("kern_write_file(%d)\n", err
);
1059 bzero(gIOHibernateCurrentHeader
, sizeof(IOHibernateImageHeader
));
1060 gIOHibernateCurrentHeader
->debugFlags
= gIOHibernateDebugFlags
;
1062 dsSSD
= (vars
->fileVars
->solid_state
1063 && (kOSBooleanTrue
== IOService::getPMRootDomain()->getProperty(kIOPMDeepSleepEnabledKey
)));
1067 gIOHibernateCurrentHeader
->options
|=
1068 kIOHibernateOptionSSD
1069 | kIOHibernateOptionColor
;
1073 gIOHibernateCurrentHeader
->options
|= kIOHibernateOptionProgress
;
1076 boolean_t encryptedswap
;
1077 AbsoluteTime startTime
, endTime
;
1080 clock_get_uptime(&startTime
);
1081 err
= hibernate_setup(gIOHibernateCurrentHeader
,
1082 gIOHibernateFreeRatio
, gIOHibernateFreeTime
,
1084 &vars
->page_list
, &vars
->page_list_wired
, &encryptedswap
);
1085 clock_get_uptime(&endTime
);
1086 SUB_ABSOLUTETIME(&endTime
, &startTime
);
1087 absolutetime_to_nanoseconds(endTime
, &nsec
);
1088 HIBLOG("hibernate_setup(%d) took %qd ms\n", err
, nsec
/ 1000000ULL);
1090 if (KERN_SUCCESS
!= err
)
1094 gIOHibernateMode
^= kIOHibernateModeEncrypt
;
1096 if (kIOHibernateOptionProgress
& gIOHibernateCurrentHeader
->options
)
1098 vars
->videoAllocSize
= kVideoMapSize
;
1099 if (KERN_SUCCESS
!= kmem_alloc_pageable(kernel_map
, &vars
->videoMapping
, vars
->videoAllocSize
))
1100 vars
->videoMapping
= 0;
1103 // generate crypt keys
1104 for (uint32_t i
= 0; i
< sizeof(vars
->wiredCryptKey
); i
++)
1105 vars
->wiredCryptKey
[i
] = random();
1106 for (uint32_t i
= 0; i
< sizeof(vars
->cryptKey
); i
++)
1107 vars
->cryptKey
[i
] = random();
1111 IORegistryEntry
* regEntry
;
1112 if (!gIOOptionsEntry
)
1114 regEntry
= IORegistryEntry::fromPath("/options", gIODTPlane
);
1115 gIOOptionsEntry
= OSDynamicCast(IODTNVRAM
, regEntry
);
1116 if (regEntry
&& !gIOOptionsEntry
)
1117 regEntry
->release();
1119 if (!gIOChosenEntry
)
1120 gIOChosenEntry
= IORegistryEntry::fromPath("/chosen", gIODTPlane
);
1122 if (gIOOptionsEntry
)
1124 const OSSymbol
* sym
;
1126 sym
= OSSymbol::withCStringNoCopy(kIOHibernateBootImageKey
);
1129 gIOOptionsEntry
->setProperty(sym
, data
);
1134 #if defined(__ppc__)
1136 char valueString
[16];
1138 vars
->saveBootDevice
= gIOOptionsEntry
->copyProperty(kIOSelectedBootDeviceKey
);
1141 OSData
* bootDevice
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty(kIOBootPathKey
));
1144 sym
= OSSymbol::withCStringNoCopy(kIOSelectedBootDeviceKey
);
1145 OSString
* str2
= OSString::withCStringNoCopy((const char *) bootDevice
->getBytesNoCopy());
1147 gIOOptionsEntry
->setProperty(sym
, str2
);
1153 data
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty(kIOHibernateMemorySignatureKey
));
1156 vars
->haveFastBoot
= true;
1158 len
= snprintf(valueString
, sizeof(valueString
), "0x%lx", *((UInt32
*)data
->getBytesNoCopy()));
1159 data
= OSData::withBytes(valueString
, len
+ 1);
1160 sym
= OSSymbol::withCStringNoCopy(kIOHibernateMemorySignatureEnvKey
);
1162 gIOOptionsEntry
->setProperty(sym
, data
);
1168 data
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty(kIOHibernateMachineSignatureKey
));
1170 gIOHibernateCurrentHeader
->machineSignature
= *((UInt32
*)data
->getBytesNoCopy());
1172 #endif /* __ppc__ */
1173 #if defined(__i386__) || defined(__x86_64__)
1174 struct AppleRTCHibernateVars
1176 uint8_t signature
[4];
1178 uint8_t booterSignature
[20];
1179 uint8_t wiredCryptKey
[16];
1181 AppleRTCHibernateVars rtcVars
;
1183 rtcVars
.signature
[0] = 'A';
1184 rtcVars
.signature
[1] = 'A';
1185 rtcVars
.signature
[2] = 'P';
1186 rtcVars
.signature
[3] = 'L';
1187 rtcVars
.revision
= 1;
1188 bcopy(&vars
->wiredCryptKey
[0], &rtcVars
.wiredCryptKey
[0], sizeof(rtcVars
.wiredCryptKey
));
1189 if (gIOHibernateBootSignature
[0])
1193 for (uint32_t i
= 0;
1194 (c
= gIOHibernateBootSignature
[i
]) && (i
< (sizeof(rtcVars
.booterSignature
) << 1));
1205 value
= (value
<< 4) | c
;
1207 rtcVars
.booterSignature
[i
>> 1] = value
;
1210 data
= OSData::withBytes(&rtcVars
, sizeof(rtcVars
));
1213 IOService::getPMRootDomain()->setProperty(kIOHibernateRTCVariablesKey
, data
);
1215 if( gIOOptionsEntry
)
1217 if( gIOHibernateMode
& kIOHibernateModeSwitch
)
1219 const OSSymbol
*sym
;
1220 sym
= OSSymbol::withCStringNoCopy(kIOHibernateBootSwitchVarsKey
);
1223 gIOOptionsEntry
->setProperty(sym
, data
); /* intentional insecure backup of rtc boot vars */
1233 data
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty(kIOHibernateMachineSignatureKey
));
1235 gIOHibernateCurrentHeader
->machineSignature
= *((UInt32
*)data
->getBytesNoCopy());
1237 #else /* !i386 && !x86_64 */
1238 if (kIOHibernateModeEncrypt
& gIOHibernateMode
)
1240 data
= OSData::withBytes(&vars
->wiredCryptKey
[0], sizeof(vars
->wiredCryptKey
));
1241 sym
= OSSymbol::withCStringNoCopy(kIOHibernateBootImageKeyKey
);
1243 gIOOptionsEntry
->setProperty(sym
, data
);
1248 if (false && gIOHibernateBootSignature
[0])
1250 data
= OSData::withCapacity(16);
1251 sym
= OSSymbol::withCStringNoCopy(kIOHibernateBootSignatureKey
);
1256 for (uint32_t i
= 0; (c
= gIOHibernateBootSignature
[i
]); i
++)
1266 value
= (value
<< 4) | c
;
1268 data
->appendBytes(&value
, sizeof(value
));
1270 gIOOptionsEntry
->setProperty(sym
, data
);
1278 if (!vars
->haveFastBoot
)
1280 // set boot volume to zero
1281 IODTPlatformExpert
* platform
= OSDynamicCast(IODTPlatformExpert
, IOService::getPlatform());
1282 if (platform
&& (kIOReturnSuccess
== platform
->readXPRAM(kXPRamAudioVolume
,
1283 &vars
->saveBootAudioVolume
, sizeof(vars
->saveBootAudioVolume
))))
1286 newVolume
= vars
->saveBootAudioVolume
& 0xf8;
1287 platform
->writeXPRAM(kXPRamAudioVolume
,
1288 &newVolume
, sizeof(newVolume
));
1291 #endif /* !i386 && !x86_64 */
1295 gIOHibernateCurrentHeader
->signature
= kIOHibernateHeaderSignature
;
1296 gIOHibernateState
= kIOHibernateStateHibernating
;
1303 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1305 DECLARE_IOHIBERNATEPROGRESSALPHA
1308 ProgressInit(hibernate_graphics_t
* display
, uint8_t * screen
, uint8_t * saveunder
, uint32_t savelen
)
1310 uint32_t rowBytes
, pixelShift
;
1313 uint32_t alpha
, in
, color
, result
;
1315 uint32_t saveindex
[kIOHibernateProgressCount
] = { 0 };
1317 rowBytes
= display
->rowBytes
;
1318 pixelShift
= display
->depth
>> 4;
1319 if (pixelShift
< 1) return;
1321 screen
+= ((display
->width
1322 - kIOHibernateProgressCount
* (kIOHibernateProgressWidth
+ kIOHibernateProgressSpacing
)) << (pixelShift
- 1))
1323 + (display
->height
- kIOHibernateProgressOriginY
- kIOHibernateProgressHeight
) * rowBytes
;
1325 for (y
= 0; y
< kIOHibernateProgressHeight
; y
++)
1327 out
= screen
+ y
* rowBytes
;
1328 for (blob
= 0; blob
< kIOHibernateProgressCount
; blob
++)
1330 color
= blob
? kIOHibernateProgressDarkGray
: kIOHibernateProgressMidGray
;
1331 for (x
= 0; x
< kIOHibernateProgressWidth
; x
++)
1333 alpha
= gIOHibernateProgressAlpha
[y
][x
];
1339 if (1 == pixelShift
)
1341 in
= *((uint16_t *)out
) & 0x1f; // 16
1342 in
= (in
<< 3) | (in
>> 2);
1345 in
= *((uint32_t *)out
) & 0xff; // 32
1346 saveunder
[blob
* kIOHibernateProgressSaveUnderSize
+ saveindex
[blob
]++] = in
;
1347 result
= ((255 - alpha
) * in
+ alpha
* result
+ 0xff) >> 8;
1349 if (1 == pixelShift
)
1352 *((uint16_t *)out
) = (result
<< 10) | (result
<< 5) | result
; // 16
1355 *((uint32_t *)out
) = (result
<< 16) | (result
<< 8) | result
; // 32
1357 out
+= (1 << pixelShift
);
1359 out
+= (kIOHibernateProgressSpacing
<< pixelShift
);
1366 ProgressUpdate(hibernate_graphics_t
* display
, uint8_t * screen
, int32_t firstBlob
, int32_t select
)
1368 uint32_t rowBytes
, pixelShift
;
1370 int32_t blob
, lastBlob
;
1371 uint32_t alpha
, in
, color
, result
;
1373 uint32_t saveindex
[kIOHibernateProgressCount
] = { 0 };
1375 pixelShift
= display
->depth
>> 4;
1379 rowBytes
= display
->rowBytes
;
1381 screen
+= ((display
->width
1382 - kIOHibernateProgressCount
* (kIOHibernateProgressWidth
+ kIOHibernateProgressSpacing
)) << (pixelShift
- 1))
1383 + (display
->height
- kIOHibernateProgressOriginY
- kIOHibernateProgressHeight
) * rowBytes
;
1385 lastBlob
= (select
< kIOHibernateProgressCount
) ? select
: (kIOHibernateProgressCount
- 1);
1387 screen
+= (firstBlob
* (kIOHibernateProgressWidth
+ kIOHibernateProgressSpacing
)) << pixelShift
;
1389 for (y
= 0; y
< kIOHibernateProgressHeight
; y
++)
1391 out
= screen
+ y
* rowBytes
;
1392 for (blob
= firstBlob
; blob
<= lastBlob
; blob
++)
1394 color
= (blob
< select
) ? kIOHibernateProgressLightGray
: kIOHibernateProgressMidGray
;
1395 for (x
= 0; x
< kIOHibernateProgressWidth
; x
++)
1397 alpha
= gIOHibernateProgressAlpha
[y
][x
];
1403 in
= display
->progressSaveUnder
[blob
][saveindex
[blob
]++];
1404 result
= ((255 - alpha
) * in
+ alpha
* result
+ 0xff) / 255;
1406 if (1 == pixelShift
)
1409 *((uint16_t *)out
) = (result
<< 10) | (result
<< 5) | result
; // 16
1412 *((uint32_t *)out
) = (result
<< 16) | (result
<< 8) | result
; // 32
1414 out
+= (1 << pixelShift
);
1416 out
+= (kIOHibernateProgressSpacing
<< pixelShift
);
1421 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1424 IOHibernateSystemHasSlept(void)
1426 IOHibernateVars
* vars
= &gIOHibernateVars
;
1430 obj
= IOService::getPMRootDomain()->copyProperty(kIOHibernatePreviewBufferKey
);
1431 vars
->previewBuffer
= OSDynamicCast(IOMemoryDescriptor
, obj
);
1432 if (obj
&& !vars
->previewBuffer
)
1435 vars
->consoleMapping
= NULL
;
1436 if (vars
->previewBuffer
&& (kIOReturnSuccess
!= vars
->previewBuffer
->prepare()))
1438 vars
->previewBuffer
->release();
1439 vars
->previewBuffer
= 0;
1442 if ((kIOHibernateOptionProgress
& gIOHibernateCurrentHeader
->options
)
1443 && vars
->previewBuffer
1444 && (data
= OSDynamicCast(OSData
,
1445 IOService::getPMRootDomain()->getProperty(kIOHibernatePreviewActiveKey
))))
1447 UInt32 flags
= *((UInt32
*)data
->getBytesNoCopy());
1448 HIBPRINT("kIOHibernatePreviewActiveKey %08lx\n", (long)flags
);
1450 IOService::getPMRootDomain()->removeProperty(kIOHibernatePreviewActiveKey
);
1452 if (kIOHibernatePreviewUpdates
& flags
)
1454 PE_Video consoleInfo
;
1455 hibernate_graphics_t
* graphicsInfo
= gIOHibernateGraphicsInfo
;
1457 IOService::getPlatform()->getConsoleInfo(&consoleInfo
);
1459 graphicsInfo
->width
= consoleInfo
.v_width
;
1460 graphicsInfo
->height
= consoleInfo
.v_height
;
1461 graphicsInfo
->rowBytes
= consoleInfo
.v_rowBytes
;
1462 graphicsInfo
->depth
= consoleInfo
.v_depth
;
1463 vars
->consoleMapping
= (uint8_t *) consoleInfo
.v_baseAddr
;
1465 HIBPRINT("video %p %d %d %d\n",
1466 vars
->consoleMapping
, graphicsInfo
->depth
,
1467 graphicsInfo
->width
, graphicsInfo
->height
);
1468 if (vars
->consoleMapping
)
1469 ProgressInit(graphicsInfo
, vars
->consoleMapping
,
1470 &graphicsInfo
->progressSaveUnder
[0][0], sizeof(graphicsInfo
->progressSaveUnder
));
1474 if (gIOOptionsEntry
)
1475 gIOOptionsEntry
->sync();
1477 return (kIOReturnSuccess
);
1480 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1483 IOHibernateSystemWake(void)
1485 IOHibernateVars
* vars
= &gIOHibernateVars
;
1487 hibernate_teardown(vars
->page_list
, vars
->page_list_wired
);
1489 if (vars
->videoMapping
)
1491 if (vars
->videoMapSize
)
1493 IOUnmapPages(kernel_map
, vars
->videoMapping
, vars
->videoMapSize
);
1494 if (vars
->videoAllocSize
)
1496 kmem_free(kernel_map
, trunc_page(vars
->videoMapping
), vars
->videoAllocSize
);
1499 if (vars
->previewBuffer
)
1501 vars
->previewBuffer
->release();
1502 vars
->previewBuffer
= 0;
1505 if (kIOHibernateStateWakingFromHibernate
== gIOHibernateState
)
1507 IOService::getPMRootDomain()->setProperty(kIOHibernateOptionsKey
,
1508 gIOHibernateCurrentHeader
->options
, 32);
1512 IOService::getPMRootDomain()->removeProperty(kIOHibernateOptionsKey
);
1515 if ((kIOHibernateStateWakingFromHibernate
== gIOHibernateState
)
1516 && (kIOHibernateGfxStatusUnknown
!= gIOHibernateGraphicsInfo
->gfxStatus
))
1518 IOService::getPMRootDomain()->setProperty(kIOHibernateGfxStatusKey
,
1519 &gIOHibernateGraphicsInfo
->gfxStatus
,
1520 sizeof(gIOHibernateGraphicsInfo
->gfxStatus
));
1524 IOService::getPMRootDomain()->removeProperty(kIOHibernateGfxStatusKey
);
1530 IOPolledFileClose(vars
->fileVars
);
1533 // invalidate nvram properties - (gIOOptionsEntry != 0) => nvram was touched
1536 OSData
* data
= OSData::withCapacity(4);
1537 if (gIOOptionsEntry
&& data
)
1539 const OSSymbol
* sym
= OSSymbol::withCStringNoCopy(kIOHibernateBootImageKey
);
1542 gIOOptionsEntry
->setProperty(sym
, data
);
1545 sym
= OSSymbol::withCStringNoCopy(kIOSelectedBootDeviceKey
);
1548 if (vars
->saveBootDevice
)
1550 gIOOptionsEntry
->setProperty(sym
, vars
->saveBootDevice
);
1551 vars
->saveBootDevice
->release();
1555 sym
= OSSymbol::withCStringNoCopy(kIOHibernateBootImageKeyKey
);
1558 gIOOptionsEntry
->setProperty(sym
, data
);
1561 sym
= OSSymbol::withCStringNoCopy(kIOHibernateMemorySignatureEnvKey
);
1564 gIOOptionsEntry
->removeProperty(sym
);
1571 if (gIOOptionsEntry
)
1573 if (!vars
->haveFastBoot
)
1575 // reset boot audio volume
1576 IODTPlatformExpert
* platform
= OSDynamicCast(IODTPlatformExpert
, IOService::getPlatform());
1578 platform
->writeXPRAM(kXPRamAudioVolume
,
1579 &vars
->saveBootAudioVolume
, sizeof(vars
->saveBootAudioVolume
));
1582 // sync now to hardware if the booter has not
1583 if (kIOHibernateStateInactive
== gIOHibernateState
)
1584 gIOOptionsEntry
->sync();
1586 // just sync the variables in case a later panic syncs nvram (it won't sync variables)
1587 gIOOptionsEntry
->syncOFVariables();
1591 #if defined(__i386__) || defined(__x86_64__)
1592 IOService::getPMRootDomain()->removeProperty(kIOHibernateRTCVariablesKey
);
1595 * Hibernate variable is written to NVRAM on platforms in which RtcRam
1596 * is not backed by coin cell. Remove Hibernate data from NVRAM.
1598 if (gIOOptionsEntry
) {
1599 const OSSymbol
* sym
= OSSymbol::withCStringNoCopy(kIOHibernateRTCVariablesKey
);
1602 if (gIOOptionsEntry
->getProperty(sym
)) {
1603 gIOOptionsEntry
->removeProperty(sym
);
1604 gIOOptionsEntry
->sync();
1611 if (vars
->srcBuffer
)
1612 vars
->srcBuffer
->release();
1614 vars
->ioBuffer
->release();
1615 if (vars
->fileExtents
)
1616 vars
->fileExtents
->release();
1618 bzero(vars
, sizeof(*vars
));
1620 // gIOHibernateState = kIOHibernateStateInactive; // leave it for post wake code to see
1622 return (kIOReturnSuccess
);
1626 IOHibernateSystemPostWake(void)
1628 if (gIOHibernateFileRef
)
1630 // invalidate the image file
1631 gIOHibernateCurrentHeader
->signature
= kIOHibernateHeaderInvalidSignature
;
1632 int err
= kern_write_file(gIOHibernateFileRef
, 0,
1633 (caddr_t
) gIOHibernateCurrentHeader
, sizeof(IOHibernateImageHeader
));
1634 if (KERN_SUCCESS
!= err
)
1635 HIBLOG("kern_write_file(%d)\n", err
);
1637 kern_close_file_for_direct_io(gIOHibernateFileRef
);
1638 gIOHibernateFileRef
= 0;
1640 return (kIOReturnSuccess
);
1643 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1645 SYSCTL_STRING(_kern
, OID_AUTO
, hibernatefile
,
1646 CTLFLAG_RW
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
,
1647 gIOHibernateFilename
, sizeof(gIOHibernateFilename
), "");
1648 SYSCTL_STRING(_kern
, OID_AUTO
, bootsignature
,
1649 CTLFLAG_RW
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
,
1650 gIOHibernateBootSignature
, sizeof(gIOHibernateBootSignature
), "");
1651 SYSCTL_UINT(_kern
, OID_AUTO
, hibernatemode
,
1652 CTLFLAG_RW
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
,
1653 &gIOHibernateMode
, 0, "");
1656 IOHibernateSystemInit(IOPMrootDomain
* rootDomain
)
1658 OSData
* data
= OSData::withBytesNoCopy(&gIOHibernateState
, sizeof(gIOHibernateState
));
1661 rootDomain
->setProperty(kIOHibernateStateKey
, data
);
1665 if (PE_parse_boot_argn("hfile", gIOHibernateFilename
, sizeof(gIOHibernateFilename
)))
1666 gIOHibernateMode
= kIOHibernateModeOn
;
1668 gIOHibernateFilename
[0] = 0;
1670 sysctl_register_oid(&sysctl__kern_hibernatefile
);
1671 sysctl_register_oid(&sysctl__kern_bootsignature
);
1672 sysctl_register_oid(&sysctl__kern_hibernatemode
);
1676 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1679 hibernate_setup_for_wake(void)
1682 // go slow (state needed for wake)
1683 ml_set_processor_speed(1);
1687 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1689 #define C_ASSERT(e) typedef char __C_ASSERT__[(e) ? 1 : -1]
1692 no_encrypt_page(vm_offset_t ppnum
)
1694 if (pmap_is_noencrypt((ppnum_t
)ppnum
) == TRUE
)
1701 uint32_t wired_pages_encrypted
= 0;
1702 uint32_t dirty_pages_encrypted
= 0;
1703 uint32_t wired_pages_clear
= 0;
1706 hibernate_write_image(void)
1708 IOHibernateImageHeader
* header
= gIOHibernateCurrentHeader
;
1709 IOHibernateVars
* vars
= &gIOHibernateVars
;
1710 IOPolledFileExtent
* fileExtents
;
1712 C_ASSERT(sizeof(IOHibernateImageHeader
) == 512);
1714 uint32_t pageCount
, pagesDone
;
1716 vm_offset_t ppnum
, page
;
1720 IOByteCount pageCompressedSize
;
1721 uint64_t compressedSize
, uncompressedSize
;
1722 uint64_t image1Size
= 0;
1723 uint32_t bitmap_size
;
1724 bool iterDone
, pollerOpen
, needEncrypt
;
1725 uint32_t restore1Sum
, sum
, sum1
, sum2
;
1728 uint32_t pageAndCount
[2];
1730 AbsoluteTime startTime
, endTime
;
1731 AbsoluteTime allTime
, compTime
, decoTime
;
1734 uint32_t lastProgressStamp
= 0;
1735 uint32_t progressStamp
;
1736 uint32_t blob
, lastBlob
= (uint32_t) -1L;
1738 hibernate_cryptvars_t _cryptvars
;
1739 hibernate_cryptvars_t
* cryptvars
= 0;
1741 wired_pages_encrypted
= 0;
1742 dirty_pages_encrypted
= 0;
1743 wired_pages_clear
= 0;
1745 if (!vars
->fileVars
|| !vars
->fileVars
->pollers
|| !vars
->fileExtents
)
1746 return (false /* sleep */ );
1748 if (kIOHibernateModeSleep
& gIOHibernateMode
)
1749 kdebug_enable
= save_kdebug_enable
;
1751 KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE
, 1) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
1753 restore1Sum
= sum1
= sum2
= 0;
1756 // encryption data. "iv" is the "initial vector".
1757 if (kIOHibernateModeEncrypt
& gIOHibernateMode
)
1759 static const unsigned char first_iv
[AES_BLOCK_SIZE
]
1760 = { 0xa3, 0x63, 0x65, 0xa9, 0x0b, 0x71, 0x7b, 0x1c,
1761 0xdf, 0x9e, 0x5f, 0x32, 0xd7, 0x61, 0x63, 0xda };
1763 cryptvars
= &gIOHibernateCryptWakeContext
;
1764 bzero(cryptvars
, sizeof(hibernate_cryptvars_t
));
1765 aes_encrypt_key(vars
->cryptKey
,
1766 kIOHibernateAESKeySize
,
1767 &cryptvars
->ctx
.encrypt
);
1768 aes_decrypt_key(vars
->cryptKey
,
1769 kIOHibernateAESKeySize
,
1770 &cryptvars
->ctx
.decrypt
);
1772 cryptvars
= &_cryptvars
;
1773 bzero(cryptvars
, sizeof(hibernate_cryptvars_t
));
1774 aes_encrypt_key(vars
->wiredCryptKey
,
1775 kIOHibernateAESKeySize
,
1776 &cryptvars
->ctx
.encrypt
);
1778 bcopy(&first_iv
[0], &cryptvars
->aes_iv
[0], AES_BLOCK_SIZE
);
1779 bzero(&vars
->wiredCryptKey
[0], sizeof(vars
->wiredCryptKey
));
1780 bzero(&vars
->cryptKey
[0], sizeof(vars
->cryptKey
));
1781 bzero(gIOHibernateCryptWakeVars
, sizeof(hibernate_cryptwakevars_t
));
1785 hibernate_setup_for_wake();
1787 hibernate_page_list_setall(vars
->page_list
,
1788 vars
->page_list_wired
,
1791 HIBLOG("hibernate_page_list_setall found pageCount %d\n", pageCount
);
1793 fileExtents
= (IOPolledFileExtent
*) vars
->fileExtents
->getBytesNoCopy();
1796 count
= vars
->fileExtents
->getLength() / sizeof(IOPolledFileExtent
);
1797 for (page
= 0; page
< count
; page
++)
1799 HIBLOG("fileExtents[%d] %qx, %qx (%qx)\n", page
,
1800 fileExtents
[page
].start
, fileExtents
[page
].length
,
1801 fileExtents
[page
].start
+ fileExtents
[page
].length
);
1805 needEncrypt
= (0 != (kIOHibernateModeEncrypt
& gIOHibernateMode
));
1807 AbsoluteTime_to_scalar(&compTime
) = 0;
1808 AbsoluteTime_to_scalar(&decoTime
) = 0;
1810 clock_get_uptime(&allTime
);
1811 IOService::getPMRootDomain()->pmStatsRecordEvent(
1812 kIOPMStatsHibernateImageWrite
| kIOPMStatsEventStartFlag
, allTime
);
1817 uncompressedSize
= 0;
1819 IOPolledFileSeek(vars
->fileVars
, sizeof(IOHibernateImageHeader
));
1821 HIBLOG("IOHibernatePollerOpen, ml_get_interrupts_enabled %d\n",
1822 ml_get_interrupts_enabled());
1823 err
= IOHibernatePollerOpen(vars
->fileVars
, kIOPolledBeforeSleepState
, vars
->ioBuffer
);
1824 HIBLOG("IOHibernatePollerOpen(%x)\n", err
);
1825 pollerOpen
= (kIOReturnSuccess
== err
);
1829 // copy file block extent list if larger than header
1831 count
= vars
->fileExtents
->getLength();
1832 if (count
> sizeof(header
->fileExtentMap
))
1834 count
-= sizeof(header
->fileExtentMap
);
1835 err
= IOPolledFileWrite(vars
->fileVars
,
1836 ((uint8_t *) &fileExtents
[0]) + sizeof(header
->fileExtentMap
), count
, cryptvars
);
1837 if (kIOReturnSuccess
!= err
)
1841 uintptr_t hibernateBase
;
1842 uintptr_t hibernateEnd
;
1844 #if defined(__i386__) || defined(__x86_64__)
1845 hibernateBase
= sectINITPTB
;
1847 hibernateBase
= sectHIBB
;
1850 hibernateEnd
= (sectHIBB
+ sectSizeHIB
);
1851 // copy out restore1 code
1853 page
= atop_32(hibernateBase
);
1854 count
= atop_32(round_page(hibernateEnd
)) - page
;
1855 header
->restore1CodePage
= page
;
1856 header
->restore1PageCount
= count
;
1857 header
->restore1CodeOffset
= ((uintptr_t) &hibernate_machine_entrypoint
) - hibernateBase
;
1858 header
->restore1StackOffset
= ((uintptr_t) &gIOHibernateRestoreStackEnd
[0]) - 64 - hibernateBase
;
1860 // sum __HIB sect, with zeros for the stack
1861 src
= (uint8_t *) trunc_page(hibernateBase
);
1862 for (page
= 0; page
< count
; page
++)
1864 if ((src
< &gIOHibernateRestoreStack
[0]) || (src
>= &gIOHibernateRestoreStackEnd
[0]))
1865 restore1Sum
+= hibernate_sum_page(src
, header
->restore1CodePage
+ page
);
1867 restore1Sum
+= 0x00000000;
1872 // write the __HIB sect, with zeros for the stack
1874 src
= (uint8_t *) trunc_page(hibernateBase
);
1875 count
= ((uintptr_t) &gIOHibernateRestoreStack
[0]) - trunc_page(hibernateBase
);
1878 err
= IOPolledFileWrite(vars
->fileVars
, src
, count
, cryptvars
);
1879 if (kIOReturnSuccess
!= err
)
1882 err
= IOPolledFileWrite(vars
->fileVars
,
1884 &gIOHibernateRestoreStackEnd
[0] - &gIOHibernateRestoreStack
[0],
1886 if (kIOReturnSuccess
!= err
)
1888 src
= &gIOHibernateRestoreStackEnd
[0];
1889 count
= round_page(hibernateEnd
) - ((uintptr_t) src
);
1892 err
= IOPolledFileWrite(vars
->fileVars
, src
, count
, cryptvars
);
1893 if (kIOReturnSuccess
!= err
)
1897 // write the preview buffer
1902 if (vars
->previewBuffer
)
1908 phys64
= vars
->previewBuffer
->getPhysicalSegment(count
, &segLen
, kIOMemoryMapperNone
);
1909 pageAndCount
[0] = atop_64(phys64
);
1910 pageAndCount
[1] = atop_32(segLen
);
1911 err
= IOPolledFileWrite(vars
->fileVars
,
1912 (const uint8_t *) &pageAndCount
, sizeof(pageAndCount
),
1914 if (kIOReturnSuccess
!= err
)
1917 ppnum
+= sizeof(pageAndCount
);
1920 if (kIOReturnSuccess
!= err
)
1923 src
= (uint8_t *) vars
->previewBuffer
->getPhysicalSegment(0, NULL
, _kIOMemorySourceSegment
);
1924 count
= vars
->previewBuffer
->getLength();
1926 header
->previewPageListSize
= ppnum
;
1927 header
->previewSize
= count
+ ppnum
;
1929 for (page
= 0; page
< count
; page
+= page_size
)
1931 phys64
= vars
->previewBuffer
->getPhysicalSegment(page
, NULL
, kIOMemoryMapperNone
);
1932 sum1
+= hibernate_sum_page(src
+ page
, atop_64(phys64
));
1934 err
= IOPolledFileWrite(vars
->fileVars
, src
, count
, cryptvars
);
1935 if (kIOReturnSuccess
!= err
)
1939 // mark areas for no save
1942 (phys64
= vars
->ioBuffer
->getPhysicalSegment(count
, &segLen
, kIOMemoryMapperNone
));
1945 hibernate_set_page_state(vars
->page_list
, vars
->page_list_wired
,
1946 atop_64(phys64
), atop_32(segLen
),
1947 kIOHibernatePageStateFree
);
1948 pageCount
-= atop_32(segLen
);
1952 (phys64
= vars
->srcBuffer
->getPhysicalSegment(count
, &segLen
, kIOMemoryMapperNone
));
1955 hibernate_set_page_state(vars
->page_list
, vars
->page_list_wired
,
1956 atop_64(phys64
), atop_32(segLen
),
1957 kIOHibernatePageStateFree
);
1958 pageCount
-= atop_32(segLen
);
1961 // copy out bitmap of pages available for trashing during restore
1963 bitmap_size
= vars
->page_list_wired
->list_size
;
1964 src
= (uint8_t *) vars
->page_list_wired
;
1965 err
= IOPolledFileWrite(vars
->fileVars
, src
, bitmap_size
, cryptvars
);
1966 if (kIOReturnSuccess
!= err
)
1969 // mark more areas for no save, but these are not available
1970 // for trashing during restore
1972 hibernate_page_list_set_volatile(vars
->page_list
, vars
->page_list_wired
, &pageCount
);
1974 page
= atop_32(hibernateBase
);
1975 count
= atop_32(round_page(hibernateEnd
)) - page
;
1976 hibernate_set_page_state(vars
->page_list
, vars
->page_list_wired
,
1978 kIOHibernatePageStateFree
);
1981 if (vars
->previewBuffer
) for (count
= 0;
1982 (phys64
= vars
->previewBuffer
->getPhysicalSegment(count
, &segLen
, kIOMemoryMapperNone
));
1985 hibernate_set_page_state(vars
->page_list
, vars
->page_list_wired
,
1986 atop_64(phys64
), atop_32(segLen
),
1987 kIOHibernatePageStateFree
);
1988 pageCount
-= atop_32(segLen
);
1991 src
= (uint8_t *) vars
->srcBuffer
->getBytesNoCopy();
1996 HIBLOG("writing %d pages\n", pageCount
);
2003 kWiredEncrypt
= kWired
| kEncrypt
,
2004 kWiredClear
= kWired
,
2005 kUnwiredEncrypt
= kEncrypt
2008 for (pageType
= kWiredEncrypt
; pageType
>= kUnwiredEncrypt
; pageType
--)
2010 if (needEncrypt
&& (kEncrypt
& pageType
))
2012 vars
->fileVars
->encryptStart
= (vars
->fileVars
->position
& ~(AES_BLOCK_SIZE
- 1));
2013 vars
->fileVars
->encryptEnd
= UINT64_MAX
;
2014 HIBLOG("encryptStart %qx\n", vars
->fileVars
->encryptStart
);
2016 if (kUnwiredEncrypt
== pageType
)
2018 // start unwired image
2019 bcopy(&cryptvars
->aes_iv
[0],
2020 &gIOHibernateCryptWakeContext
.aes_iv
[0],
2021 sizeof(cryptvars
->aes_iv
));
2022 cryptvars
= &gIOHibernateCryptWakeContext
;
2025 for (iterDone
= false, ppnum
= 0; !iterDone
; )
2027 count
= hibernate_page_list_iterate((kWired
& pageType
)
2028 ? vars
->page_list_wired
: vars
->page_list
,
2030 // kprintf("[%d](%x : %x)\n", pageType, ppnum, count);
2033 if (count
&& (kWired
& pageType
) && needEncrypt
)
2035 uint32_t checkIndex
;
2036 for (checkIndex
= 0;
2037 (checkIndex
< count
)
2038 && (((kEncrypt
& pageType
) == 0) == no_encrypt_page(ppnum
+ checkIndex
));
2051 case kWiredEncrypt
: wired_pages_encrypted
+= count
; break;
2052 case kWiredClear
: wired_pages_clear
+= count
; break;
2053 case kUnwiredEncrypt
: dirty_pages_encrypted
+= count
; break;
2056 if (iterDone
&& (kWiredEncrypt
== pageType
)) {/* not yet end of wired list */}
2059 pageAndCount
[0] = ppnum
;
2060 pageAndCount
[1] = count
;
2061 err
= IOPolledFileWrite(vars
->fileVars
,
2062 (const uint8_t *) &pageAndCount
, sizeof(pageAndCount
),
2064 if (kIOReturnSuccess
!= err
)
2068 for (page
= ppnum
; page
< (ppnum
+ count
); page
++)
2070 err
= IOMemoryDescriptorWriteFromPhysical(vars
->srcBuffer
, 0, ptoa_64(page
), page_size
);
2073 HIBLOG("IOMemoryDescriptorWriteFromPhysical %d [%ld] %x\n", __LINE__
, (long)page
, err
);
2077 sum
= hibernate_sum_page(src
, page
);
2078 if (kWired
& pageType
)
2083 clock_get_uptime(&startTime
);
2085 pageCompressedSize
= WKdm_compress ((WK_word
*) src
, (WK_word
*) (src
+ page_size
), PAGE_SIZE_IN_WORDS
);
2087 clock_get_uptime(&endTime
);
2088 ADD_ABSOLUTETIME(&compTime
, &endTime
);
2089 SUB_ABSOLUTETIME(&compTime
, &startTime
);
2090 compBytes
+= page_size
;
2092 if (kIOHibernateModeEncrypt
& gIOHibernateMode
)
2093 pageCompressedSize
= (pageCompressedSize
+ AES_BLOCK_SIZE
- 1) & ~(AES_BLOCK_SIZE
- 1);
2095 if (pageCompressedSize
> page_size
)
2097 // HIBLOG("------------lose: %d\n", pageCompressedSize);
2098 pageCompressedSize
= page_size
;
2101 if (pageCompressedSize
!= page_size
)
2102 data
= (src
+ page_size
);
2106 tag
= pageCompressedSize
| kIOHibernateTagSignature
;
2107 err
= IOPolledFileWrite(vars
->fileVars
, (const uint8_t *) &tag
, sizeof(tag
), cryptvars
);
2108 if (kIOReturnSuccess
!= err
)
2111 err
= IOPolledFileWrite(vars
->fileVars
, data
, (pageCompressedSize
+ 3) & ~3, cryptvars
);
2112 if (kIOReturnSuccess
!= err
)
2115 compressedSize
+= pageCompressedSize
;
2116 if (pageCompressedSize
)
2117 uncompressedSize
+= page_size
;
2120 if (vars
->consoleMapping
&& (0 == (1023 & pagesDone
)))
2122 blob
= ((pagesDone
* kIOHibernateProgressCount
) / pageCount
);
2123 if (blob
!= lastBlob
)
2125 ProgressUpdate(gIOHibernateGraphicsInfo
, vars
->consoleMapping
, lastBlob
, blob
);
2129 if (0 == (8191 & pagesDone
))
2131 clock_get_uptime(&endTime
);
2132 SUB_ABSOLUTETIME(&endTime
, &allTime
);
2133 absolutetime_to_nanoseconds(endTime
, &nsec
);
2134 progressStamp
= nsec
/ 750000000ULL;
2135 if (progressStamp
!= lastProgressStamp
)
2137 lastProgressStamp
= progressStamp
;
2138 HIBPRINT("pages %d (%d%%)\n", pagesDone
, (100 * pagesDone
) / pageCount
);
2142 if (kIOReturnSuccess
!= err
)
2147 if (kIOReturnSuccess
!= err
)
2150 if ((kEncrypt
& pageType
))
2152 vars
->fileVars
->encryptEnd
= (vars
->fileVars
->position
+ AES_BLOCK_SIZE
- 1)
2153 & ~(AES_BLOCK_SIZE
- 1);
2154 HIBLOG("encryptEnd %qx\n", vars
->fileVars
->encryptEnd
);
2157 if (kWiredEncrypt
!= pageType
)
2159 // end of image1/2 - fill to next block
2160 err
= IOPolledFileWrite(vars
->fileVars
, 0, 0, cryptvars
);
2161 if (kIOReturnSuccess
!= err
)
2164 if (kWiredClear
== pageType
)
2167 header
->encryptStart
= vars
->fileVars
->encryptStart
;
2168 header
->encryptEnd
= vars
->fileVars
->encryptEnd
;
2169 image1Size
= vars
->fileVars
->position
;
2170 HIBLOG("image1Size %qd, encryptStart1 %qx, End1 %qx\n",
2171 image1Size
, header
->encryptStart
, header
->encryptEnd
);
2174 if (kIOReturnSuccess
!= err
)
2179 header
->imageSize
= vars
->fileVars
->position
;
2180 header
->image1Size
= image1Size
;
2181 header
->bitmapSize
= bitmap_size
;
2182 header
->pageCount
= pageCount
;
2184 header
->restore1Sum
= restore1Sum
;
2185 header
->image1Sum
= sum1
;
2186 header
->image2Sum
= sum2
;
2188 count
= vars
->fileExtents
->getLength();
2189 if (count
> sizeof(header
->fileExtentMap
))
2191 header
->fileExtentMapSize
= count
;
2192 count
= sizeof(header
->fileExtentMap
);
2195 header
->fileExtentMapSize
= sizeof(header
->fileExtentMap
);
2196 bcopy(&fileExtents
[0], &header
->fileExtentMap
[0], count
);
2198 header
->deviceBase
= vars
->fileVars
->block0
;
2200 IOPolledFileSeek(vars
->fileVars
, 0);
2201 err
= IOPolledFileWrite(vars
->fileVars
,
2202 (uint8_t *) header
, sizeof(IOHibernateImageHeader
),
2204 if (kIOReturnSuccess
!= err
)
2206 err
= IOPolledFileWrite(vars
->fileVars
, 0, 0, cryptvars
);
2207 if (kIOReturnSuccess
!= err
)
2209 err
= IOHibernatePollerIODone(vars
->fileVars
, true);
2210 if (kIOReturnSuccess
!= err
)
2215 clock_get_uptime(&endTime
);
2217 IOService::getPMRootDomain()->pmStatsRecordEvent(
2218 kIOPMStatsHibernateImageWrite
| kIOPMStatsEventStopFlag
, endTime
);
2220 SUB_ABSOLUTETIME(&endTime
, &allTime
);
2221 absolutetime_to_nanoseconds(endTime
, &nsec
);
2222 HIBLOG("all time: %qd ms, ",
2225 absolutetime_to_nanoseconds(compTime
, &nsec
);
2226 HIBLOG("comp time: %qd ms, ",
2229 absolutetime_to_nanoseconds(decoTime
, &nsec
);
2230 HIBLOG("deco time: %qd ms, ",
2233 HIBLOG("\nimage %qd, uncompressed %qd (%d), compressed %qd (%d%%), sum1 %x, sum2 %x\n",
2235 uncompressedSize
, atop_32(uncompressedSize
), compressedSize
,
2236 uncompressedSize
? ((int) ((compressedSize
* 100ULL) / uncompressedSize
)) : 0,
2239 HIBLOG("wired_pages_encrypted %d, wired_pages_clear %d, dirty_pages_encrypted %d\n",
2240 wired_pages_encrypted
, wired_pages_clear
, dirty_pages_encrypted
);
2242 if (vars
->fileVars
->io
)
2243 (void) IOHibernatePollerIODone(vars
->fileVars
, false);
2246 IOHibernatePollerClose(vars
->fileVars
, kIOPolledBeforeSleepState
);
2248 if (vars
->consoleMapping
)
2249 ProgressUpdate(gIOHibernateGraphicsInfo
,
2250 vars
->consoleMapping
, 0, kIOHibernateProgressCount
);
2252 HIBLOG("hibernate_write_image done(%x)\n", err
);
2254 // should we come back via regular wake, set the state in memory.
2255 gIOHibernateState
= kIOHibernateStateInactive
;
2257 KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE
, 1) | DBG_FUNC_END
,
2258 wired_pages_encrypted
, wired_pages_clear
, dirty_pages_encrypted
, 0, 0);
2260 if (kIOReturnSuccess
== err
)
2262 if (kIOHibernateModeSleep
& gIOHibernateMode
)
2264 return (kIOHibernatePostWriteSleep
);
2266 else if(kIOHibernateModeRestart
& gIOHibernateMode
)
2268 return (kIOHibernatePostWriteRestart
);
2272 /* by default, power down */
2273 return (kIOHibernatePostWriteHalt
);
2276 else if (kIOReturnAborted
== err
)
2278 return (kIOHibernatePostWriteWake
);
2282 /* on error, sleep */
2283 return (kIOHibernatePostWriteSleep
);
2287 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2290 hibernate_machine_init(void)
2295 uint32_t pagesRead
= 0;
2296 AbsoluteTime allTime
, endTime
;
2298 uint32_t lastProgressStamp
= 0;
2299 uint32_t progressStamp
;
2300 uint64_t progressZeroPosition
= 0;
2301 uint32_t blob
, lastBlob
= (uint32_t) -1L;
2302 hibernate_cryptvars_t
* cryptvars
= 0;
2304 IOHibernateVars
* vars
= &gIOHibernateVars
;
2306 if (!vars
->fileVars
|| !vars
->fileVars
->pollers
|| !vars
->fileExtents
)
2309 sum
= gIOHibernateCurrentHeader
->actualImage1Sum
;
2310 pagesDone
= gIOHibernateCurrentHeader
->actualUncompressedPages
;
2312 HIBLOG("hibernate_machine_init: state %d, image pages %d, sum was %x, image1Size %qx, conflictCount %d, nextFree %x\n",
2313 gIOHibernateState
, pagesDone
, sum
, gIOHibernateCurrentHeader
->image1Size
,
2314 gIOHibernateCurrentHeader
->conflictCount
, gIOHibernateCurrentHeader
->nextFree
);
2316 if (kIOHibernateStateWakingFromHibernate
!= gIOHibernateState
)
2318 HIBLOG("regular wake\n");
2322 HIBPRINT("diag %x %x %x %x\n",
2323 gIOHibernateCurrentHeader
->diag
[0], gIOHibernateCurrentHeader
->diag
[1],
2324 gIOHibernateCurrentHeader
->diag
[2], gIOHibernateCurrentHeader
->diag
[3]);
2326 HIBPRINT("video %x %d %d %d status %x\n",
2327 gIOHibernateGraphicsInfo
->physicalAddress
, gIOHibernateGraphicsInfo
->depth
,
2328 gIOHibernateGraphicsInfo
->width
, gIOHibernateGraphicsInfo
->height
, gIOHibernateGraphicsInfo
->gfxStatus
);
2330 if ((kIOHibernateModeDiscardCleanActive
| kIOHibernateModeDiscardCleanInactive
) & gIOHibernateMode
)
2331 hibernate_page_list_discard(vars
->page_list
);
2333 boot_args
*args
= (boot_args
*) PE_state
.bootArgs
;
2335 if (vars
->videoMapping
2336 && gIOHibernateGraphicsInfo
->physicalAddress
2337 && (args
->Video
.v_baseAddr
== gIOHibernateGraphicsInfo
->physicalAddress
))
2339 vars
->videoMapSize
= round_page(gIOHibernateGraphicsInfo
->height
2340 * gIOHibernateGraphicsInfo
->rowBytes
);
2341 IOMapPages(kernel_map
,
2342 vars
->videoMapping
, gIOHibernateGraphicsInfo
->physicalAddress
,
2343 vars
->videoMapSize
, kIOMapInhibitCache
);
2346 uint8_t * src
= (uint8_t *) vars
->srcBuffer
->getBytesNoCopy();
2348 if (gIOHibernateWakeMapSize
)
2350 err
= IOMemoryDescriptorWriteFromPhysical(vars
->srcBuffer
, 0, ptoa_64(gIOHibernateWakeMap
),
2351 gIOHibernateWakeMapSize
);
2352 if (kIOReturnSuccess
== err
)
2353 hibernate_newruntime_map(src
, gIOHibernateWakeMapSize
,
2354 gIOHibernateCurrentHeader
->systemTableOffset
);
2355 gIOHibernateWakeMap
= 0;
2356 gIOHibernateWakeMapSize
= 0;
2359 uint32_t decoOffset
;
2361 clock_get_uptime(&allTime
);
2363 HIBLOG("IOHibernatePollerOpen(), ml_get_interrupts_enabled %d\n", ml_get_interrupts_enabled());
2364 err
= IOHibernatePollerOpen(vars
->fileVars
, kIOPolledAfterSleepState
, 0);
2365 HIBLOG("IOHibernatePollerOpen(%x)\n", err
);
2367 if (gIOHibernateCurrentHeader
->previewSize
)
2368 progressZeroPosition
= gIOHibernateCurrentHeader
->previewSize
2369 + gIOHibernateCurrentHeader
->fileExtentMapSize
2370 - sizeof(gIOHibernateCurrentHeader
->fileExtentMap
)
2371 + ptoa_64(gIOHibernateCurrentHeader
->restore1PageCount
);
2373 IOPolledFileSeek(vars
->fileVars
, gIOHibernateCurrentHeader
->image1Size
);
2375 if (vars
->videoMapSize
)
2377 lastBlob
= ((vars
->fileVars
->position
- progressZeroPosition
) * kIOHibernateProgressCount
)
2378 / (gIOHibernateCurrentHeader
->imageSize
- progressZeroPosition
);
2379 ProgressUpdate(gIOHibernateGraphicsInfo
, (uint8_t *) vars
->videoMapping
, 0, lastBlob
);
2382 cryptvars
= (kIOHibernateModeEncrypt
& gIOHibernateMode
) ? &gIOHibernateCryptWakeContext
: 0;
2383 if (kIOHibernateModeEncrypt
& gIOHibernateMode
)
2385 cryptvars
= &gIOHibernateCryptWakeContext
;
2386 bcopy(&gIOHibernateCryptWakeVars
->aes_iv
[0],
2387 &cryptvars
->aes_iv
[0],
2388 sizeof(cryptvars
->aes_iv
));
2391 // kick off the read ahead
2392 vars
->fileVars
->io
= false;
2393 vars
->fileVars
->bufferHalf
= 0;
2394 vars
->fileVars
->bufferLimit
= 0;
2395 vars
->fileVars
->lastRead
= 0;
2396 vars
->fileVars
->bufferOffset
= vars
->fileVars
->bufferLimit
;
2398 IOPolledFileRead(vars
->fileVars
, 0, 0, cryptvars
);
2399 vars
->fileVars
->bufferOffset
= vars
->fileVars
->bufferLimit
;
2402 HIBLOG("hibernate_machine_init reading\n");
2404 uint32_t * header
= (uint32_t *) src
;
2412 vm_offset_t ppnum
, compressedSize
;
2414 err
= IOPolledFileRead(vars
->fileVars
, src
, 8, cryptvars
);
2415 if (kIOReturnSuccess
!= err
)
2421 // HIBPRINT("(%x, %x)\n", ppnum, count);
2426 for (page
= 0; page
< count
; page
++)
2428 err
= IOPolledFileRead(vars
->fileVars
, (uint8_t *) &tag
, 4, cryptvars
);
2429 if (kIOReturnSuccess
!= err
)
2432 compressedSize
= kIOHibernateTagLength
& tag
;
2433 if (kIOHibernateTagSignature
!= (tag
& ~kIOHibernateTagLength
))
2435 err
= kIOReturnIPCError
;
2439 if (!compressedSize
)
2446 err
= IOPolledFileRead(vars
->fileVars
, src
, (compressedSize
+ 3) & ~3, cryptvars
);
2447 if (kIOReturnSuccess
!= err
)
2450 if (compressedSize
< page_size
)
2452 decoOffset
= page_size
;
2453 WKdm_decompress((WK_word
*) src
, (WK_word
*) (src
+ decoOffset
), PAGE_SIZE_IN_WORDS
);
2458 sum
+= hibernate_sum_page((src
+ decoOffset
), ppnum
);
2460 err
= IOMemoryDescriptorReadToPhysical(vars
->srcBuffer
, decoOffset
, ptoa_64(ppnum
), page_size
);
2463 HIBLOG("IOMemoryDescriptorReadToPhysical [%ld] %x\n", (long)ppnum
, err
);
2471 if (vars
->videoMapSize
&& (0 == (1023 & pagesDone
)))
2473 blob
= ((vars
->fileVars
->position
- progressZeroPosition
) * kIOHibernateProgressCount
)
2474 / (gIOHibernateCurrentHeader
->imageSize
- progressZeroPosition
);
2475 if (blob
!= lastBlob
)
2477 ProgressUpdate(gIOHibernateGraphicsInfo
, (uint8_t *) vars
->videoMapping
, lastBlob
, blob
);
2482 if (0 == (8191 & pagesDone
))
2484 clock_get_uptime(&endTime
);
2485 SUB_ABSOLUTETIME(&endTime
, &allTime
);
2486 absolutetime_to_nanoseconds(endTime
, &nsec
);
2487 progressStamp
= nsec
/ 750000000ULL;
2488 if (progressStamp
!= lastProgressStamp
)
2490 lastProgressStamp
= progressStamp
;
2491 HIBPRINT("pages %d (%d%%)\n", pagesDone
,
2492 (100 * pagesDone
) / gIOHibernateCurrentHeader
->pageCount
);
2499 if (kIOReturnSuccess
!= err
)
2500 panic("Hibernate restore error %x", err
);
2502 gIOHibernateCurrentHeader
->actualImage2Sum
= sum
;
2504 if (vars
->fileVars
->io
)
2505 (void) IOHibernatePollerIODone(vars
->fileVars
, false);
2507 err
= IOHibernatePollerClose(vars
->fileVars
, kIOPolledAfterSleepState
);
2509 if (vars
->videoMapSize
)
2510 ProgressUpdate(gIOHibernateGraphicsInfo
,
2511 (uint8_t *) vars
->videoMapping
, 0, kIOHibernateProgressCount
);
2513 clock_get_uptime(&endTime
);
2515 IOService::getPMRootDomain()->pmStatsRecordEvent(
2516 kIOPMStatsHibernateImageRead
| kIOPMStatsEventStartFlag
, allTime
);
2517 IOService::getPMRootDomain()->pmStatsRecordEvent(
2518 kIOPMStatsHibernateImageRead
| kIOPMStatsEventStopFlag
, endTime
);
2520 SUB_ABSOLUTETIME(&endTime
, &allTime
);
2521 absolutetime_to_nanoseconds(endTime
, &nsec
);
2523 HIBLOG("hibernate_machine_init pagesDone %d sum2 %x, time: %qd ms\n",
2524 pagesDone
, sum
, nsec
/ 1000000ULL);
2526 KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE
, 2) | DBG_FUNC_NONE
, pagesRead
, pagesDone
, 0, 0, 0);
2529 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */