2 * Copyright (c) 1998-2006 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@
31 * 17-Apr-91 Portions from libIO.m, Doug Mitchell at NeXT.
36 #include <IOKit/system.h>
37 #include <mach/sync_policy.h>
38 #include <machine/machine_routines.h>
39 #include <vm/vm_kern.h>
40 #include <libkern/c++/OSCPPDebug.h>
42 #include <IOKit/assert.h>
44 #include <IOKit/IOReturn.h>
45 #include <IOKit/IOLib.h>
46 #include <IOKit/IOLocks.h>
47 #include <IOKit/IOMapper.h>
48 #include <IOKit/IOBufferMemoryDescriptor.h>
49 #include <IOKit/IOKitDebug.h>
51 #include "IOKitKernelInternal.h"
54 #include <libkern/OSDebug.h>
55 #include <sys/sysctl.h>
58 #include "libkern/OSAtomic.h"
59 #include <libkern/c++/OSKext.h>
60 #include <IOKit/IOStatisticsPrivate.h>
61 #include <os/log_private.h>
62 #include <sys/msgbuf.h>
63 #include <console/serial_protos.h>
67 #define IOStatisticsAlloc(type, size) \
69 IOStatistics::countAlloc(type, size); \
74 #define IOStatisticsAlloc(type, size)
76 #endif /* IOKITSTATS */
79 #define TRACK_ALLOC (IOTRACKING && (kIOTracking & gIOKitDebug))
84 mach_timespec_t IOZeroTvalspec
= { 0, 0 };
86 extern ppnum_t
pmap_find_phys(pmap_t pmap
, addr64_t va
);
92 void (*putc
)(int, void *),
97 extern void cons_putc_locked(char);
98 extern void bsd_log_lock(void);
99 extern void bsd_log_unlock(void);
102 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
104 lck_grp_t
*IOLockGroup
;
107 * Global variables for use by iLogger
108 * These symbols are for use only by Apple diagnostic code.
109 * Binary compatibility is not guaranteed for kexts that reference these symbols.
112 void *_giDebugLogInternal
= NULL
;
113 void *_giDebugLogDataInternal
= NULL
;
114 void *_giDebugReserved1
= NULL
;
115 void *_giDebugReserved2
= NULL
;
117 iopa_t gIOBMDPageAllocator
;
120 * Static variables for this module.
123 static queue_head_t gIOMallocContiguousEntries
;
124 static lck_mtx_t
* gIOMallocContiguousEntriesLock
;
127 enum { kIOMaxPageableMaps
= 8 };
128 enum { kIOPageableMapSize
= 512 * 1024 * 1024 };
129 enum { kIOPageableMaxMapSize
= 512 * 1024 * 1024 };
131 enum { kIOMaxPageableMaps
= 16 };
132 enum { kIOPageableMapSize
= 96 * 1024 * 1024 };
133 enum { kIOPageableMaxMapSize
= 96 * 1024 * 1024 };
145 IOMapData maps
[kIOMaxPageableMaps
];
147 } gIOKitPageableSpace
;
149 static iopa_t gIOPageablePageAllocator
;
151 uint32_t gIOPageAllocChunkBytes
;
154 IOTrackingQueue
* gIOMallocTracking
;
155 IOTrackingQueue
* gIOWireTracking
;
156 IOTrackingQueue
* gIOMapTracking
;
157 #endif /* IOTRACKING */
159 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
166 static bool libInitialized
;
168 if (libInitialized
) {
172 IOLockGroup
= lck_grp_alloc_init("IOKit", LCK_GRP_ATTR_NULL
);
176 gIOMallocTracking
= IOTrackingQueueAlloc(kIOMallocTrackingName
, 0, 0, 0,
177 kIOTrackingQueueTypeAlloc
,
179 gIOWireTracking
= IOTrackingQueueAlloc(kIOWireTrackingName
, 0, 0, page_size
, 0, 0);
181 size_t mapCaptureSize
= (kIOTracking
& gIOKitDebug
) ? page_size
: (1024 * 1024);
182 gIOMapTracking
= IOTrackingQueueAlloc(kIOMapTrackingName
, 0, 0, mapCaptureSize
,
183 kIOTrackingQueueTypeDefaultOn
184 | kIOTrackingQueueTypeMap
185 | kIOTrackingQueueTypeUser
,
189 gIOKitPageableSpace
.maps
[0].address
= 0;
190 ret
= kmem_suballoc(kernel_map
,
191 &gIOKitPageableSpace
.maps
[0].address
,
195 VM_MAP_KERNEL_FLAGS_NONE
,
196 VM_KERN_MEMORY_IOKIT
,
197 &gIOKitPageableSpace
.maps
[0].map
);
198 if (ret
!= KERN_SUCCESS
) {
199 panic("failed to allocate iokit pageable map\n");
202 gIOKitPageableSpace
.lock
= lck_mtx_alloc_init(IOLockGroup
, LCK_ATTR_NULL
);
203 gIOKitPageableSpace
.maps
[0].end
= gIOKitPageableSpace
.maps
[0].address
+ kIOPageableMapSize
;
204 gIOKitPageableSpace
.hint
= 0;
205 gIOKitPageableSpace
.count
= 1;
207 gIOMallocContiguousEntriesLock
= lck_mtx_alloc_init(IOLockGroup
, LCK_ATTR_NULL
);
208 queue_init( &gIOMallocContiguousEntries
);
210 gIOPageAllocChunkBytes
= PAGE_SIZE
/ 64;
211 assert(sizeof(iopa_page_t
) <= gIOPageAllocChunkBytes
);
212 iopa_init(&gIOBMDPageAllocator
);
213 iopa_init(&gIOPageablePageAllocator
);
216 libInitialized
= true;
219 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
222 log2up(uint32_t size
)
227 size
= 32 - __builtin_clz(size
- 1);
232 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
235 IOCreateThread(IOThreadFunc fcn
, void *arg
)
237 kern_return_t result
;
240 result
= kernel_thread_start((thread_continue_t
)fcn
, arg
, &thread
);
241 if (result
!= KERN_SUCCESS
) {
245 thread_deallocate(thread
);
254 (void) thread_terminate(current_thread());
257 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
260 IOMallocZero(vm_size_t size
)
263 result
= IOMalloc(size
);
270 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
273 struct IOLibMallocHeader
{
274 IOTrackingAddress tracking
;
279 #define sizeofIOLibMallocHeader (sizeof(IOLibMallocHeader) - (TRACK_ALLOC ? 0 : sizeof(IOTrackingAddress)))
281 #define sizeofIOLibMallocHeader (0)
284 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
287 IOMalloc(vm_size_t size
)
292 allocSize
= size
+ sizeofIOLibMallocHeader
;
294 if (sizeofIOLibMallocHeader
&& (allocSize
<= size
)) {
295 return NULL
; // overflow
298 address
= kalloc_tag_bt(allocSize
, VM_KERN_MEMORY_IOKIT
);
303 IOLibMallocHeader
* hdr
;
304 hdr
= (typeof(hdr
))address
;
305 bzero(&hdr
->tracking
, sizeof(hdr
->tracking
));
306 hdr
->tracking
.address
= ~(((uintptr_t) address
) + sizeofIOLibMallocHeader
);
307 hdr
->tracking
.size
= size
;
308 IOTrackingAdd(gIOMallocTracking
, &hdr
->tracking
.tracking
, size
, true, VM_KERN_MEMORY_NONE
);
311 address
= (typeof(address
))(((uintptr_t) address
) + sizeofIOLibMallocHeader
);
314 OSAddAtomic(size
, &debug_iomalloc_size
);
316 IOStatisticsAlloc(kIOStatisticsMalloc
, size
);
323 IOFree(void * inAddress
, vm_size_t size
)
327 if ((address
= inAddress
)) {
328 address
= (typeof(address
))(((uintptr_t) address
) - sizeofIOLibMallocHeader
);
332 IOLibMallocHeader
* hdr
;
333 struct ptr_reference
{ void * ptr
; };
334 volatile struct ptr_reference ptr
;
336 // we're about to block in IOTrackingRemove(), make sure the original pointer
337 // exists in memory or a register for leak scanning to find
340 hdr
= (typeof(hdr
))address
;
341 if (size
!= hdr
->tracking
.size
) {
342 OSReportWithBacktrace("bad IOFree size 0x%lx should be 0x%lx", size
, hdr
->tracking
.size
);
343 size
= hdr
->tracking
.size
;
345 IOTrackingRemove(gIOMallocTracking
, &hdr
->tracking
.tracking
, size
);
350 kfree(address
, size
+ sizeofIOLibMallocHeader
);
352 OSAddAtomic(-size
, &debug_iomalloc_size
);
354 IOStatisticsAlloc(kIOStatisticsFree
, size
);
358 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
361 IOMemoryTag(vm_map_t map
)
365 if (!vm_kernel_map_is_kernel(map
)) {
366 return VM_MEMORY_IOKIT
;
370 if (tag
== VM_KERN_MEMORY_NONE
) {
371 tag
= VM_KERN_MEMORY_IOKIT
;
377 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
379 struct IOLibPageMallocHeader
{
380 mach_vm_size_t allocationSize
;
381 mach_vm_address_t allocationAddress
;
383 IOTrackingAddress tracking
;
388 #define sizeofIOLibPageMallocHeader (sizeof(IOLibPageMallocHeader) - (TRACK_ALLOC ? 0 : sizeof(IOTrackingAddress)))
390 #define sizeofIOLibPageMallocHeader (sizeof(IOLibPageMallocHeader))
393 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
396 IOMallocAligned(vm_size_t size
, vm_size_t alignment
)
400 vm_offset_t allocationAddress
;
401 vm_size_t adjustedSize
;
403 IOLibPageMallocHeader
* hdr
;
409 alignment
= (1UL << log2up(alignment
));
410 alignMask
= alignment
- 1;
411 adjustedSize
= size
+ sizeofIOLibPageMallocHeader
;
413 if (size
> adjustedSize
) {
414 address
= 0; /* overflow detected */
415 } else if (adjustedSize
>= page_size
) {
416 kr
= kernel_memory_allocate(kernel_map
, &address
,
417 size
, alignMask
, 0, IOMemoryTag(kernel_map
));
418 if (KERN_SUCCESS
!= kr
) {
422 else if (TRACK_ALLOC
) {
423 IOTrackingAlloc(gIOMallocTracking
, address
, size
);
427 adjustedSize
+= alignMask
;
429 if (adjustedSize
>= page_size
) {
430 kr
= kernel_memory_allocate(kernel_map
, &allocationAddress
,
431 adjustedSize
, 0, 0, IOMemoryTag(kernel_map
));
432 if (KERN_SUCCESS
!= kr
) {
433 allocationAddress
= 0;
436 allocationAddress
= (vm_address_t
) kalloc_tag_bt(adjustedSize
, VM_KERN_MEMORY_IOKIT
);
439 if (allocationAddress
) {
440 address
= (allocationAddress
+ alignMask
+ sizeofIOLibPageMallocHeader
)
443 hdr
= (typeof(hdr
))(address
- sizeofIOLibPageMallocHeader
);
444 hdr
->allocationSize
= adjustedSize
;
445 hdr
->allocationAddress
= allocationAddress
;
448 bzero(&hdr
->tracking
, sizeof(hdr
->tracking
));
449 hdr
->tracking
.address
= ~address
;
450 hdr
->tracking
.size
= size
;
451 IOTrackingAdd(gIOMallocTracking
, &hdr
->tracking
.tracking
, size
, true, VM_KERN_MEMORY_NONE
);
459 assert(0 == (address
& alignMask
));
463 OSAddAtomic(size
, &debug_iomalloc_size
);
465 IOStatisticsAlloc(kIOStatisticsMallocAligned
, size
);
468 return (void *) address
;
472 IOFreeAligned(void * address
, vm_size_t size
)
474 vm_address_t allocationAddress
;
475 vm_size_t adjustedSize
;
476 IOLibPageMallocHeader
* hdr
;
484 adjustedSize
= size
+ sizeofIOLibPageMallocHeader
;
485 if (adjustedSize
>= page_size
) {
488 IOTrackingFree(gIOMallocTracking
, (uintptr_t) address
, size
);
491 kmem_free( kernel_map
, (vm_offset_t
) address
, size
);
493 hdr
= (typeof(hdr
))(((uintptr_t)address
) - sizeofIOLibPageMallocHeader
);
494 adjustedSize
= hdr
->allocationSize
;
495 allocationAddress
= hdr
->allocationAddress
;
499 if (size
!= hdr
->tracking
.size
) {
500 OSReportWithBacktrace("bad IOFreeAligned size 0x%lx should be 0x%lx", size
, hdr
->tracking
.size
);
501 size
= hdr
->tracking
.size
;
503 IOTrackingRemove(gIOMallocTracking
, &hdr
->tracking
.tracking
, size
);
506 if (adjustedSize
>= page_size
) {
507 kmem_free( kernel_map
, allocationAddress
, adjustedSize
);
509 kfree(allocationAddress
, adjustedSize
);
514 OSAddAtomic(-size
, &debug_iomalloc_size
);
517 IOStatisticsAlloc(kIOStatisticsFreeAligned
, size
);
520 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
523 IOKernelFreePhysical(mach_vm_address_t address
, mach_vm_size_t size
)
525 mach_vm_address_t allocationAddress
;
526 mach_vm_size_t adjustedSize
;
527 IOLibPageMallocHeader
* hdr
;
535 adjustedSize
= (2 * size
) + sizeofIOLibPageMallocHeader
;
536 if (adjustedSize
>= page_size
) {
539 IOTrackingFree(gIOMallocTracking
, address
, size
);
542 kmem_free( kernel_map
, (vm_offset_t
) address
, size
);
544 hdr
= (typeof(hdr
))(((uintptr_t)address
) - sizeofIOLibPageMallocHeader
);
545 adjustedSize
= hdr
->allocationSize
;
546 allocationAddress
= hdr
->allocationAddress
;
549 IOTrackingRemove(gIOMallocTracking
, &hdr
->tracking
.tracking
, size
);
552 kfree(allocationAddress
, adjustedSize
);
555 IOStatisticsAlloc(kIOStatisticsFreeContiguous
, size
);
557 OSAddAtomic(-size
, &debug_iomalloc_size
);
561 #if __arm__ || __arm64__
562 extern unsigned long gPhysBase
, gPhysSize
;
566 IOKernelAllocateWithPhysicalRestrict(mach_vm_size_t size
, mach_vm_address_t maxPhys
,
567 mach_vm_size_t alignment
, bool contiguous
)
570 mach_vm_address_t address
;
571 mach_vm_address_t allocationAddress
;
572 mach_vm_size_t adjustedSize
;
573 mach_vm_address_t alignMask
;
574 IOLibPageMallocHeader
* hdr
;
579 if (alignment
== 0) {
583 alignMask
= alignment
- 1;
585 if (os_mul_and_add_overflow(2, size
, sizeofIOLibPageMallocHeader
, &adjustedSize
)) {
589 contiguous
= (contiguous
&& (adjustedSize
> page_size
))
590 || (alignment
> page_size
);
592 if (contiguous
|| maxPhys
) {
597 contiguous
= (contiguous
&& (adjustedSize
> page_size
))
598 || (alignment
> page_size
);
601 #if __arm__ || __arm64__
602 if (maxPhys
>= (mach_vm_address_t
)(gPhysBase
+ gPhysSize
)) {
606 if (maxPhys
<= 0xFFFFFFFF) {
608 options
|= KMA_LOMEM
;
609 } else if (gIOLastPage
&& (atop_64(maxPhys
) > gIOLastPage
)) {
613 if (contiguous
|| maxPhys
) {
614 kr
= kmem_alloc_contig(kernel_map
, &virt
, size
,
615 alignMask
, atop(maxPhys
), atop(alignMask
), 0, IOMemoryTag(kernel_map
));
617 kr
= kernel_memory_allocate(kernel_map
, &virt
,
618 size
, alignMask
, options
, IOMemoryTag(kernel_map
));
620 if (KERN_SUCCESS
== kr
) {
624 IOTrackingAlloc(gIOMallocTracking
, address
, size
);
631 adjustedSize
+= alignMask
;
632 if (adjustedSize
< size
) {
635 allocationAddress
= (mach_vm_address_t
) kalloc_tag_bt(adjustedSize
, VM_KERN_MEMORY_IOKIT
);
637 if (allocationAddress
) {
638 address
= (allocationAddress
+ alignMask
+ sizeofIOLibPageMallocHeader
)
641 if (atop_32(address
) != atop_32(address
+ size
- 1)) {
642 address
= round_page(address
);
645 hdr
= (typeof(hdr
))(address
- sizeofIOLibPageMallocHeader
);
646 hdr
->allocationSize
= adjustedSize
;
647 hdr
->allocationAddress
= allocationAddress
;
650 bzero(&hdr
->tracking
, sizeof(hdr
->tracking
));
651 hdr
->tracking
.address
= ~address
;
652 hdr
->tracking
.size
= size
;
653 IOTrackingAdd(gIOMallocTracking
, &hdr
->tracking
.tracking
, size
, true, VM_KERN_MEMORY_NONE
);
662 IOStatisticsAlloc(kIOStatisticsMallocContiguous
, size
);
664 OSAddAtomic(size
, &debug_iomalloc_size
);
672 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
674 struct _IOMallocContiguousEntry
{
675 mach_vm_address_t virtualAddr
;
676 IOBufferMemoryDescriptor
* md
;
679 typedef struct _IOMallocContiguousEntry _IOMallocContiguousEntry
;
682 IOMallocContiguous(vm_size_t size
, vm_size_t alignment
,
683 IOPhysicalAddress
* physicalAddress
)
685 mach_vm_address_t address
= 0;
690 if (alignment
== 0) {
694 /* Do we want a physical address? */
695 if (!physicalAddress
) {
696 address
= IOKernelAllocateWithPhysicalRestrict(size
, 0 /*maxPhys*/, alignment
, true);
699 IOBufferMemoryDescriptor
* bmd
;
700 mach_vm_address_t physicalMask
;
701 vm_offset_t alignMask
;
703 alignMask
= alignment
- 1;
704 physicalMask
= (0xFFFFFFFF ^ alignMask
);
706 bmd
= IOBufferMemoryDescriptor::inTaskWithPhysicalMask(
707 kernel_task
, kIOMemoryPhysicallyContiguous
, size
, physicalMask
);
712 _IOMallocContiguousEntry
*
713 entry
= IONew(_IOMallocContiguousEntry
, 1);
718 entry
->virtualAddr
= (mach_vm_address_t
) bmd
->getBytesNoCopy();
720 lck_mtx_lock(gIOMallocContiguousEntriesLock
);
721 queue_enter( &gIOMallocContiguousEntries
, entry
,
722 _IOMallocContiguousEntry
*, link
);
723 lck_mtx_unlock(gIOMallocContiguousEntriesLock
);
725 address
= (mach_vm_address_t
) entry
->virtualAddr
;
726 *physicalAddress
= bmd
->getPhysicalAddress();
730 return (void *) address
;
734 IOFreeContiguous(void * _address
, vm_size_t size
)
736 _IOMallocContiguousEntry
* entry
;
737 IOMemoryDescriptor
* md
= NULL
;
739 mach_vm_address_t address
= (mach_vm_address_t
) _address
;
747 lck_mtx_lock(gIOMallocContiguousEntriesLock
);
748 queue_iterate( &gIOMallocContiguousEntries
, entry
,
749 _IOMallocContiguousEntry
*, link
)
751 if (entry
->virtualAddr
== address
) {
753 queue_remove( &gIOMallocContiguousEntries
, entry
,
754 _IOMallocContiguousEntry
*, link
);
758 lck_mtx_unlock(gIOMallocContiguousEntriesLock
);
762 IODelete(entry
, _IOMallocContiguousEntry
, 1);
764 IOKernelFreePhysical((mach_vm_address_t
) address
, size
);
768 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
771 IOIteratePageableMaps(vm_size_t size
,
772 IOIteratePageableMapsCallback callback
, void * ref
)
774 kern_return_t kr
= kIOReturnNotReady
;
781 if (size
> kIOPageableMaxMapSize
) {
782 return kIOReturnBadArgument
;
786 index
= gIOKitPageableSpace
.hint
;
787 attempts
= gIOKitPageableSpace
.count
;
789 kr
= (*callback
)(gIOKitPageableSpace
.maps
[index
].map
, ref
);
790 if (KERN_SUCCESS
== kr
) {
791 gIOKitPageableSpace
.hint
= index
;
797 index
= gIOKitPageableSpace
.count
- 1;
800 if (KERN_NO_SPACE
!= kr
) {
804 lck_mtx_lock( gIOKitPageableSpace
.lock
);
806 index
= gIOKitPageableSpace
.count
;
807 if (index
>= (kIOMaxPageableMaps
- 1)) {
808 lck_mtx_unlock( gIOKitPageableSpace
.lock
);
812 if (size
< kIOPageableMapSize
) {
813 segSize
= kIOPageableMapSize
;
819 kr
= kmem_suballoc(kernel_map
,
824 VM_MAP_KERNEL_FLAGS_NONE
,
825 VM_KERN_MEMORY_IOKIT
,
827 if (KERN_SUCCESS
!= kr
) {
828 lck_mtx_unlock( gIOKitPageableSpace
.lock
);
832 gIOKitPageableSpace
.maps
[index
].map
= map
;
833 gIOKitPageableSpace
.maps
[index
].address
= min
;
834 gIOKitPageableSpace
.maps
[index
].end
= min
+ segSize
;
835 gIOKitPageableSpace
.hint
= index
;
836 gIOKitPageableSpace
.count
= index
+ 1;
838 lck_mtx_unlock( gIOKitPageableSpace
.lock
);
844 struct IOMallocPageableRef
{
851 IOMallocPageableCallback(vm_map_t map
, void * _ref
)
853 struct IOMallocPageableRef
* ref
= (struct IOMallocPageableRef
*) _ref
;
856 kr
= kmem_alloc_pageable( map
, &ref
->address
, ref
->size
, ref
->tag
);
862 IOMallocPageablePages(vm_size_t size
, vm_size_t alignment
, vm_tag_t tag
)
864 kern_return_t kr
= kIOReturnNotReady
;
865 struct IOMallocPageableRef ref
;
867 if (alignment
> page_size
) {
870 if (size
> kIOPageableMaxMapSize
) {
876 kr
= IOIteratePageableMaps( size
, &IOMallocPageableCallback
, &ref
);
877 if (kIOReturnSuccess
!= kr
) {
881 return (void *) ref
.address
;
885 IOPageableMapForAddress( uintptr_t address
)
890 for (index
= 0; index
< gIOKitPageableSpace
.count
; index
++) {
891 if ((address
>= gIOKitPageableSpace
.maps
[index
].address
)
892 && (address
< gIOKitPageableSpace
.maps
[index
].end
)) {
893 map
= gIOKitPageableSpace
.maps
[index
].map
;
898 panic("IOPageableMapForAddress: null");
905 IOFreePageablePages(void * address
, vm_size_t size
)
909 map
= IOPageableMapForAddress((vm_address_t
) address
);
911 kmem_free( map
, (vm_offset_t
) address
, size
);
916 IOMallocOnePageablePage(iopa_t
* a
)
918 return (uintptr_t) IOMallocPageablePages(page_size
, page_size
, VM_KERN_MEMORY_IOKIT
);
922 IOMallocPageable(vm_size_t size
, vm_size_t alignment
)
926 if (size
>= (page_size
- 4 * gIOPageAllocChunkBytes
)) {
927 addr
= IOMallocPageablePages(size
, alignment
, IOMemoryTag(kernel_map
));
929 addr
= ((void *) iopa_alloc(&gIOPageablePageAllocator
, &IOMallocOnePageablePage
, size
, alignment
));
934 OSAddAtomicLong(size
, &debug_iomallocpageable_size
);
936 IOStatisticsAlloc(kIOStatisticsMallocPageable
, size
);
943 IOFreePageable(void * address
, vm_size_t size
)
946 OSAddAtomicLong(-size
, &debug_iomallocpageable_size
);
948 IOStatisticsAlloc(kIOStatisticsFreePageable
, size
);
950 if (size
< (page_size
- 4 * gIOPageAllocChunkBytes
)) {
951 address
= (void *) iopa_free(&gIOPageablePageAllocator
, (uintptr_t) address
, size
);
955 IOFreePageablePages(address
, size
);
959 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
962 iopa_init(iopa_t
* a
)
964 bzero(a
, sizeof(*a
));
965 a
->lock
= IOLockAlloc();
966 queue_init(&a
->list
);
970 iopa_allocinpage(iopa_page_t
* pa
, uint32_t count
, uint64_t align
)
973 uint64_t avail
= pa
->avail
;
977 // find strings of count 1 bits in avail
978 for (n
= count
; n
> 1; n
-= s
) {
980 avail
= avail
& (avail
<< s
);
986 n
= __builtin_clzll(avail
);
987 pa
->avail
&= ~((-1ULL << (64 - count
)) >> n
);
988 if (!pa
->avail
&& pa
->link
.next
) {
990 pa
->link
.next
= NULL
;
992 return n
* gIOPageAllocChunkBytes
+ trunc_page((uintptr_t) pa
);
999 iopa_alloc(iopa_t
* a
, iopa_proc_t alloc
, vm_size_t bytes
, uint32_t balign
)
1001 static const uint64_t align_masks
[] = {
1018 count
= (bytes
+ gIOPageAllocChunkBytes
- 1) / gIOPageAllocChunkBytes
;
1019 align
= align_masks
[log2up((balign
+ gIOPageAllocChunkBytes
- 1) / gIOPageAllocChunkBytes
)];
1021 IOLockLock(a
->lock
);
1022 __IGNORE_WCASTALIGN(pa
= (typeof(pa
))queue_first(&a
->list
));
1023 while (!queue_end(&a
->list
, &pa
->link
)) {
1024 addr
= iopa_allocinpage(pa
, count
, align
);
1026 a
->bytecount
+= bytes
;
1029 __IGNORE_WCASTALIGN(pa
= (typeof(pa
))queue_next(&pa
->link
));
1031 IOLockUnlock(a
->lock
);
1036 pa
= (typeof(pa
))(addr
+ page_size
- gIOPageAllocChunkBytes
);
1037 pa
->signature
= kIOPageAllocSignature
;
1040 addr
= iopa_allocinpage(pa
, count
, align
);
1041 IOLockLock(a
->lock
);
1043 enqueue_head(&a
->list
, &pa
->link
);
1047 a
->bytecount
+= bytes
;
1049 IOLockUnlock(a
->lock
);
1053 assert((addr
& ((1 << log2up(balign
)) - 1)) == 0);
1058 iopa_free(iopa_t
* a
, uintptr_t addr
, vm_size_t bytes
)
1068 chunk
= (addr
& page_mask
);
1069 assert(0 == (chunk
& (gIOPageAllocChunkBytes
- 1)));
1071 pa
= (typeof(pa
))(addr
| (page_size
- gIOPageAllocChunkBytes
));
1072 assert(kIOPageAllocSignature
== pa
->signature
);
1074 count
= (bytes
+ gIOPageAllocChunkBytes
- 1) / gIOPageAllocChunkBytes
;
1075 chunk
/= gIOPageAllocChunkBytes
;
1077 IOLockLock(a
->lock
);
1079 assert(!pa
->link
.next
);
1080 enqueue_tail(&a
->list
, &pa
->link
);
1082 pa
->avail
|= ((-1ULL << (64 - count
)) >> chunk
);
1083 if (pa
->avail
!= -2ULL) {
1087 pa
->link
.next
= NULL
;
1091 pa
= (typeof(pa
))trunc_page(pa
);
1093 a
->bytecount
-= bytes
;
1094 IOLockUnlock(a
->lock
);
1096 return (uintptr_t) pa
;
1099 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1102 IOSetProcessorCacheMode( task_t task
, IOVirtualAddress address
,
1103 IOByteCount length
, IOOptionBits cacheMode
)
1105 IOReturn ret
= kIOReturnSuccess
;
1108 if (task
!= kernel_task
) {
1109 return kIOReturnUnsupported
;
1111 if ((address
| length
) & PAGE_MASK
) {
1112 // OSReportWithBacktrace("IOSetProcessorCacheMode(0x%x, 0x%x, 0x%x) fails\n", address, length, cacheMode);
1113 return kIOReturnUnsupported
;
1115 length
= round_page(address
+ length
) - trunc_page( address
);
1116 address
= trunc_page( address
);
1119 cacheMode
= (cacheMode
<< kIOMapCacheShift
) & kIOMapCacheMask
;
1121 while ((kIOReturnSuccess
== ret
) && (length
> 0)) {
1122 // Get the physical page number
1123 pagenum
= pmap_find_phys(kernel_pmap
, (addr64_t
)address
);
1125 ret
= IOUnmapPages( get_task_map(task
), address
, page_size
);
1126 ret
= IOMapPages( get_task_map(task
), address
, ptoa_64(pagenum
), page_size
, cacheMode
);
1128 ret
= kIOReturnVMError
;
1131 address
+= page_size
;
1132 length
-= page_size
;
1140 IOFlushProcessorCache( task_t task
, IOVirtualAddress address
,
1141 IOByteCount length
)
1143 if (task
!= kernel_task
) {
1144 return kIOReturnUnsupported
;
1147 flush_dcache64((addr64_t
) address
, (unsigned) length
, false );
1149 return kIOReturnSuccess
;
1152 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1155 OSKernelStackRemaining( void )
1157 return ml_stack_remaining();
1160 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1163 * Spin for indicated number of milliseconds.
1166 IOSleep(unsigned milliseconds
)
1168 delay_for_interval(milliseconds
, kMillisecondScale
);
1172 * Spin for indicated number of milliseconds, and potentially an
1173 * additional number of milliseconds up to the leeway values.
1176 IOSleepWithLeeway(unsigned intervalMilliseconds
, unsigned leewayMilliseconds
)
1178 delay_for_interval_with_leeway(intervalMilliseconds
, leewayMilliseconds
, kMillisecondScale
);
1182 * Spin for indicated number of microseconds.
1185 IODelay(unsigned microseconds
)
1187 delay_for_interval(microseconds
, kMicrosecondScale
);
1191 * Spin for indicated number of nanoseconds.
1194 IOPause(unsigned nanoseconds
)
1196 delay_for_interval(nanoseconds
, kNanosecondScale
);
1199 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1201 static void _IOLogv(const char *format
, va_list ap
, void *caller
) __printflike(1, 0);
1203 __attribute__((noinline
, not_tail_called
))
1205 IOLog(const char *format
, ...)
1207 void *caller
= __builtin_return_address(0);
1210 va_start(ap
, format
);
1211 _IOLogv(format
, ap
, caller
);
1215 __attribute__((noinline
, not_tail_called
))
1217 IOLogv(const char *format
, va_list ap
)
1219 void *caller
= __builtin_return_address(0);
1220 _IOLogv(format
, ap
, caller
);
1224 _IOLogv(const char *format
, va_list ap
, void *caller
)
1227 struct console_printbuf_state info_data
;
1228 console_printbuf_state_init(&info_data
, TRUE
, TRUE
);
1232 os_log_with_args(OS_LOG_DEFAULT
, OS_LOG_TYPE_DEFAULT
, format
, ap
, caller
);
1234 __doprnt(format
, ap2
, console_printbuf_putc
, &info_data
, 16, TRUE
);
1235 console_printbuf_clear(&info_data
);
1238 assertf(ml_get_interrupts_enabled() || ml_is_quiescing() || debug_mode_active() || !gCPUsRunning
, "IOLog called with interrupts disabled");
1243 IOPanic(const char *reason
)
1245 panic("%s", reason
);
1249 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1252 IOKitKernelLogBuffer(const char * title
, const void * buffer
, size_t size
,
1253 void (*output
)(const char *format
, ...))
1255 size_t idx
, linestart
;
1256 enum { bytelen
= (sizeof("0xZZ, ") - 1) };
1257 char hex
[(bytelen
* 16) + 1];
1258 uint8_t c
, chars
[17];
1260 output("%s(0x%lx):\n", title
, size
);
1261 output(" 0 1 2 3 4 5 6 7 8 9 A B C D E F\n");
1266 for (idx
= 0, linestart
= 0; idx
< size
;) {
1267 c
= ((char *)buffer
)[idx
];
1268 snprintf(&hex
[bytelen
* (idx
& 15)], bytelen
+ 1, "0x%02x, ", c
);
1269 chars
[idx
& 15] = ((c
>= 0x20) && (c
<= 0x7f)) ? c
: ' ';
1271 if ((idx
== size
) || !(idx
& 15)) {
1273 chars
[idx
& 15] = 0;
1275 output("/* %04lx: */ %-96s /* |%-16s| */\n", linestart
, hex
, chars
);
1281 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1284 * Convert a integer constant (typically a #define or enum) to a string.
1286 static char noValue
[80]; // that's pretty
1289 IOFindNameForValue(int value
, const IONamedValue
*regValueArray
)
1291 for (; regValueArray
->name
; regValueArray
++) {
1292 if (regValueArray
->value
== value
) {
1293 return regValueArray
->name
;
1296 snprintf(noValue
, sizeof(noValue
), "0x%x (UNDEFINED)", value
);
1297 return (const char *)noValue
;
1301 IOFindValueForName(const char *string
,
1302 const IONamedValue
*regValueArray
,
1305 for (; regValueArray
->name
; regValueArray
++) {
1306 if (!strcmp(regValueArray
->name
, string
)) {
1307 *value
= regValueArray
->value
;
1308 return kIOReturnSuccess
;
1311 return kIOReturnBadArgument
;
1315 IOCopyLogNameForPID(int pid
)
1319 snprintf(buf
, sizeof(buf
), "pid %d, ", pid
);
1321 proc_name(pid
, buf
+ len
, sizeof(buf
) - len
);
1322 return OSString::withCString(buf
);
1325 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1328 IOSizeToAlignment(unsigned int size
)
1331 const int intsize
= sizeof(unsigned int) * 8;
1333 for (shift
= 1; shift
< intsize
; shift
++) {
1334 if (size
& 0x80000000) {
1335 return (IOAlignment
)(intsize
- shift
);
1343 IOAlignmentToSize(IOAlignment align
)
1347 for (size
= 1; align
; align
--) {