xref: /xnu-11417.121.6/iokit/Kernel/IOLib.cpp (revision a1e26a70f38d1d7daa7b49b258e2f8538ad81650)
1 /*
2  * Copyright (c) 1998-2006 Apple Computer, Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
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.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
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.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * HISTORY
30  *
31  * 17-Apr-91   Portions from libIO.m, Doug Mitchell at NeXT.
32  * 17-Nov-98   cpp
33  *
34  */
35 
36 #include <IOKit/system.h>
37 #include <mach/sync_policy.h>
38 #include <machine/machine_routines.h>
39 #include <vm/vm_kern_xnu.h>
40 #include <vm/vm_map_xnu.h>
41 #include <libkern/c++/OSCPPDebug.h>
42 
43 #include <IOKit/assert.h>
44 
45 #include <IOKit/IOReturn.h>
46 #include <IOKit/IOLib.h>
47 #include <IOKit/IOLocks.h>
48 #include <IOKit/IOMapper.h>
49 #include <IOKit/IOBufferMemoryDescriptor.h>
50 #include <IOKit/IOKitDebug.h>
51 
52 #include "IOKitKernelInternal.h"
53 
54 #ifdef IOALLOCDEBUG
55 #include <libkern/OSDebug.h>
56 #include <sys/sysctl.h>
57 #endif
58 
59 #include "libkern/OSAtomic.h"
60 #include <libkern/c++/OSKext.h>
61 #include <IOKit/IOStatisticsPrivate.h>
62 #include <os/log_private.h>
63 #include <sys/msgbuf.h>
64 #include <console/serial_protos.h>
65 
66 #if IOKITSTATS
67 
68 #define IOStatisticsAlloc(type, size) \
69 do { \
70 	IOStatistics::countAlloc(type, size); \
71 } while (0)
72 
73 #else
74 
75 #define IOStatisticsAlloc(type, size)
76 
77 #endif /* IOKITSTATS */
78 
79 
80 #define TRACK_ALLOC     (IOTRACKING && (kIOTracking & gIOKitDebug))
81 
82 
83 extern "C"
84 {
85 mach_timespec_t IOZeroTvalspec = { 0, 0 };
86 
87 extern ppnum_t pmap_find_phys(pmap_t pmap, addr64_t va);
88 
89 extern int
90 __doprnt(
91 	const char              *fmt,
92 	va_list                 argp,
93 	void                    (*putc)(int, void *),
94 	void                    *arg,
95 	int                     radix,
96 	int                     is_log);
97 
98 extern bool bsd_log_lock(bool);
99 extern void bsd_log_unlock(void);
100 
101 
102 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
103 
104 lck_grp_t        io_lck_grp;
105 lck_grp_t       *IOLockGroup;
106 
107 /*
108  * Global variables for use by iLogger
109  * These symbols are for use only by Apple diagnostic code.
110  * Binary compatibility is not guaranteed for kexts that reference these symbols.
111  */
112 
113 void *_giDebugLogInternal       = NULL;
114 void *_giDebugLogDataInternal   = NULL;
115 void *_giDebugReserved1         = NULL;
116 void *_giDebugReserved2         = NULL;
117 
118 #if defined(__x86_64__)
119 iopa_t gIOBMDPageAllocator;
120 #endif /* defined(__x86_64__) */
121 
122 /*
123  * Static variables for this module.
124  */
125 
126 static queue_head_t gIOMallocContiguousEntries;
127 static lck_mtx_t *  gIOMallocContiguousEntriesLock;
128 
129 #if __x86_64__
130 enum { kIOPageableMaxAllocSize = 512ULL * 1024 * 1024 };
131 enum { kIOPageableMapSize      = 8ULL * kIOPageableMaxAllocSize  };
132 #else
133 enum { kIOPageableMaxAllocSize = 96ULL * 1024 * 1024 };
134 enum { kIOPageableMapSize      = 16ULL * kIOPageableMaxAllocSize  };
135 #endif
136 
137 typedef struct {
138 	vm_map_t            map;
139 	vm_offset_t address;
140 	vm_offset_t end;
141 } IOMapData;
142 
143 #ifndef __BUILDING_XNU_LIBRARY__
144 /* this makes clang emit a C and C++ symbol which confuses lldb rdar://135688747 */
145 static
146 #endif /* __BUILDING_XNU_LIBRARY__ */
147 SECURITY_READ_ONLY_LATE(struct mach_vm_range) gIOKitPageableFixedRange;
148 IOMapData gIOKitPageableMap;
149 
150 #if defined(__x86_64__)
151 static iopa_t gIOPageablePageAllocator;
152 
153 uint32_t  gIOPageAllocChunkBytes;
154 #endif /* defined(__x86_64__) */
155 
156 #if IOTRACKING
157 IOTrackingQueue * gIOMallocTracking;
158 IOTrackingQueue * gIOWireTracking;
159 IOTrackingQueue * gIOMapTracking;
160 #endif /* IOTRACKING */
161 
162 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
163 
164 KMEM_RANGE_REGISTER_STATIC(gIOKitPageableFixed,
165     &gIOKitPageableFixedRange, kIOPageableMapSize);
166 void
IOLibInit(void)167 IOLibInit(void)
168 {
169 	static bool libInitialized;
170 
171 	if (libInitialized) {
172 		return;
173 	}
174 
175 	lck_grp_init(&io_lck_grp, "IOKit", LCK_GRP_ATTR_NULL);
176 	IOLockGroup = &io_lck_grp;
177 
178 #if IOTRACKING
179 	IOTrackingInit();
180 	gIOMallocTracking = IOTrackingQueueAlloc(kIOMallocTrackingName, 0, 0, 0,
181 	    kIOTrackingQueueTypeAlloc,
182 	    37);
183 	gIOWireTracking   = IOTrackingQueueAlloc(kIOWireTrackingName, 0, 0, page_size, 0, 0);
184 
185 	size_t mapCaptureSize = (kIOTracking & gIOKitDebug) ? page_size : (1024 * 1024);
186 	gIOMapTracking    = IOTrackingQueueAlloc(kIOMapTrackingName, 0, 0, mapCaptureSize,
187 	    kIOTrackingQueueTypeDefaultOn
188 	    | kIOTrackingQueueTypeMap
189 	    | kIOTrackingQueueTypeUser,
190 	    0);
191 #endif
192 
193 	gIOKitPageableMap.map = kmem_suballoc(kernel_map,
194 	    &gIOKitPageableFixedRange.min_address,
195 	    kIOPageableMapSize,
196 	    VM_MAP_CREATE_PAGEABLE,
197 	    VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
198 	    (kms_flags_t)(KMS_PERMANENT | KMS_DATA | KMS_NOFAIL),
199 	    VM_KERN_MEMORY_IOKIT).kmr_submap;
200 
201 	gIOKitPageableMap.address = gIOKitPageableFixedRange.min_address;
202 	gIOKitPageableMap.end     = gIOKitPageableFixedRange.max_address;
203 
204 	gIOMallocContiguousEntriesLock      = lck_mtx_alloc_init(IOLockGroup, LCK_ATTR_NULL);
205 	queue_init( &gIOMallocContiguousEntries );
206 
207 #if defined(__x86_64__)
208 	gIOPageAllocChunkBytes = PAGE_SIZE / 64;
209 
210 	assert(sizeof(iopa_page_t) <= gIOPageAllocChunkBytes);
211 	iopa_init(&gIOBMDPageAllocator);
212 	iopa_init(&gIOPageablePageAllocator);
213 #endif /* defined(__x86_64__) */
214 
215 
216 	libInitialized = true;
217 }
218 
219 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
220 
221 vm_size_t
log2up(vm_size_t size)222 log2up(vm_size_t size)
223 {
224 	if (size <= 1) {
225 		size = 0;
226 	} else {
227 #if __LP64__
228 		size = 64 - __builtin_clzl(size - 1);
229 #else
230 		size = 32 - __builtin_clzl(size - 1);
231 #endif
232 	}
233 	return size;
234 }
235 
236 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
237 
238 IOThread
IOCreateThread(IOThreadFunc fcn,void * arg)239 IOCreateThread(IOThreadFunc fcn, void *arg)
240 {
241 	kern_return_t   result;
242 	thread_t                thread;
243 
244 	result = kernel_thread_start((thread_continue_t)(void (*)(void))fcn, arg, &thread);
245 	if (result != KERN_SUCCESS) {
246 		return NULL;
247 	}
248 
249 	thread_deallocate(thread);
250 
251 	return thread;
252 }
253 
254 
255 void
IOExitThread(void)256 IOExitThread(void)
257 {
258 	(void) thread_terminate(current_thread());
259 }
260 
261 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
262 
263 #if IOTRACKING
264 struct IOLibMallocHeader {
265 	IOTrackingAddress tracking;
266 };
267 #endif
268 
269 #if IOTRACKING
270 #define sizeofIOLibMallocHeader (sizeof(IOLibMallocHeader) - (TRACK_ALLOC ? 0 : sizeof(IOTrackingAddress)))
271 #else
272 #define sizeofIOLibMallocHeader (0)
273 #endif
274 
275 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
276 
277 __typed_allocators_ignore_push // allocator implementation
278 
279 void *
280 (IOMalloc_internal)(struct kalloc_heap *kheap, vm_size_t size,
281 zalloc_flags_t flags)
282 {
283 	void * address;
284 	vm_size_t allocSize;
285 
286 	allocSize = size + sizeofIOLibMallocHeader;
287 #if IOTRACKING
288 	if (sizeofIOLibMallocHeader && (allocSize <= size)) {
289 		return NULL;                                          // overflow
290 	}
291 #endif
292 	address = kheap_alloc(kheap, allocSize,
293 	    Z_VM_TAG(Z_WAITOK | flags, VM_KERN_MEMORY_IOKIT));
294 
295 	if (address) {
296 #if IOTRACKING
297 		if (TRACK_ALLOC) {
298 			IOLibMallocHeader * hdr;
299 			hdr = (typeof(hdr))address;
300 			bzero(&hdr->tracking, sizeof(hdr->tracking));
301 			hdr->tracking.address = ~(((uintptr_t) address) + sizeofIOLibMallocHeader);
302 			hdr->tracking.size    = size;
303 			IOTrackingAdd(gIOMallocTracking, &hdr->tracking.tracking, size, true, VM_KERN_MEMORY_NONE);
304 		}
305 #endif
306 		address = (typeof(address))(((uintptr_t) address) + sizeofIOLibMallocHeader);
307 
308 #if IOALLOCDEBUG
309 		OSAddAtomicLong(size, &debug_iomalloc_size);
310 #endif
311 		IOStatisticsAlloc(kIOStatisticsMalloc, size);
312 	}
313 
314 	return address;
315 }
316 
317 void
IOFree_internal(struct kalloc_heap * kheap,void * inAddress,vm_size_t size)318 IOFree_internal(struct kalloc_heap *kheap, void * inAddress, vm_size_t size)
319 {
320 	void * address;
321 
322 	if ((address = inAddress)) {
323 		address = (typeof(address))(((uintptr_t) address) - sizeofIOLibMallocHeader);
324 
325 #if IOTRACKING
326 		if (TRACK_ALLOC) {
327 			IOLibMallocHeader * hdr;
328 			struct ptr_reference { void * ptr; };
329 			volatile struct ptr_reference ptr;
330 
331 			// we're about to block in IOTrackingRemove(), make sure the original pointer
332 			// exists in memory or a register for leak scanning to find
333 			ptr.ptr = inAddress;
334 
335 			hdr = (typeof(hdr))address;
336 			if (size != hdr->tracking.size) {
337 				OSReportWithBacktrace("bad IOFree size 0x%zx should be 0x%zx",
338 				    (size_t)size, (size_t)hdr->tracking.size);
339 				size = hdr->tracking.size;
340 			}
341 			IOTrackingRemoveAddress(gIOMallocTracking, &hdr->tracking, size);
342 			ptr.ptr = NULL;
343 		}
344 #endif
345 
346 		kheap_free(kheap, address, size + sizeofIOLibMallocHeader);
347 #if IOALLOCDEBUG
348 		OSAddAtomicLong(-size, &debug_iomalloc_size);
349 #endif
350 		IOStatisticsAlloc(kIOStatisticsFree, size);
351 	}
352 }
353 
354 void *
355 IOMalloc_external(
356 	vm_size_t size);
357 void *
IOMalloc_external(vm_size_t size)358 IOMalloc_external(
359 	vm_size_t size)
360 {
361 	return IOMalloc_internal(KHEAP_DEFAULT, size, Z_VM_TAG_BT_BIT);
362 }
363 
364 void
IOFree(void * inAddress,vm_size_t size)365 IOFree(void * inAddress, vm_size_t size)
366 {
367 	IOFree_internal(KHEAP_DEFAULT, inAddress, size);
368 }
369 
370 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
371 
372 void *
373 IOMallocZero_external(
374 	vm_size_t size);
375 void *
IOMallocZero_external(vm_size_t size)376 IOMallocZero_external(
377 	vm_size_t size)
378 {
379 	return IOMalloc_internal(KHEAP_DEFAULT, size, Z_ZERO_VM_TAG_BT_BIT);
380 }
381 
382 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
383 
384 vm_tag_t
IOMemoryTag(vm_map_t map)385 IOMemoryTag(vm_map_t map)
386 {
387 	vm_tag_t tag;
388 
389 	if (!vm_kernel_map_is_kernel(map)) {
390 		return VM_MEMORY_IOKIT;
391 	}
392 
393 	tag = vm_tag_bt();
394 	if (tag == VM_KERN_MEMORY_NONE) {
395 		tag = VM_KERN_MEMORY_IOKIT;
396 	}
397 
398 	return tag;
399 }
400 
401 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
402 
403 struct IOLibPageMallocHeader {
404 	mach_vm_size_t    alignMask;
405 	mach_vm_offset_t  allocationOffset;
406 #if IOTRACKING
407 	IOTrackingAddress tracking;
408 #endif
409 };
410 
411 #if IOTRACKING
412 #define sizeofIOLibPageMallocHeader     (sizeof(IOLibPageMallocHeader) - (TRACK_ALLOC ? 0 : sizeof(IOTrackingAddress)))
413 #else
414 #define sizeofIOLibPageMallocHeader     (sizeof(IOLibPageMallocHeader))
415 #endif
416 
417 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
418 
419 static __header_always_inline void
IOMallocAlignedSetHdr(IOLibPageMallocHeader * hdr,mach_vm_size_t alignMask,mach_vm_address_t allocationStart,mach_vm_address_t alignedStart)420 IOMallocAlignedSetHdr(
421 	IOLibPageMallocHeader  *hdr,
422 	mach_vm_size_t          alignMask,
423 	mach_vm_address_t       allocationStart,
424 	mach_vm_address_t       alignedStart)
425 {
426 	mach_vm_offset_t        offset = alignedStart - allocationStart;
427 #if __has_feature(ptrauth_calls)
428 	offset = (mach_vm_offset_t) ptrauth_sign_unauthenticated((void *)offset,
429 	    ptrauth_key_process_independent_data,
430 	    ptrauth_blend_discriminator((void *)(alignedStart | alignMask),
431 	    OS_PTRAUTH_DISCRIMINATOR("IOLibPageMallocHeader.allocationOffset")));
432 #endif /* __has_feature(ptrauth_calls) */
433 	hdr->allocationOffset = offset;
434 	hdr->alignMask = alignMask;
435 }
436 
437 __abortlike
438 static void
IOMallocAlignedHdrCorruptionPanic(mach_vm_offset_t offset,mach_vm_size_t alignMask,mach_vm_address_t alignedStart,vm_size_t size)439 IOMallocAlignedHdrCorruptionPanic(
440 	mach_vm_offset_t        offset,
441 	mach_vm_size_t          alignMask,
442 	mach_vm_address_t       alignedStart,
443 	vm_size_t               size)
444 {
445 	mach_vm_address_t       address = 0;
446 	mach_vm_address_t       recalAlignedStart = 0;
447 
448 	if (os_sub_overflow(alignedStart, offset, &address)) {
449 		panic("Invalid offset %p for aligned addr %p", (void *)offset,
450 		    (void *)alignedStart);
451 	}
452 	if (os_add3_overflow(address, sizeofIOLibPageMallocHeader, alignMask,
453 	    &recalAlignedStart)) {
454 		panic("alignMask 0x%llx overflows recalAlignedStart %p for provided addr "
455 		    "%p", alignMask, (void *)recalAlignedStart, (void *)alignedStart);
456 	}
457 	if (((recalAlignedStart &= ~alignMask) != alignedStart) &&
458 	    (round_page(recalAlignedStart) != alignedStart)) {
459 		panic("Recalculated aligned addr %p doesn't match provided addr %p",
460 		    (void *)recalAlignedStart, (void *)alignedStart);
461 	}
462 	if (offset < sizeofIOLibPageMallocHeader) {
463 		panic("Offset %zd doesn't accomodate IOLibPageMallocHeader for aligned "
464 		    "addr %p", (size_t)offset, (void *)alignedStart);
465 	}
466 	panic("alignMask 0x%llx overflows adjusted size %zd for aligned addr %p",
467 	    alignMask, (size_t)size, (void *)alignedStart);
468 }
469 
470 static __header_always_inline mach_vm_address_t
IOMallocAlignedGetAddress(IOLibPageMallocHeader * hdr,mach_vm_address_t alignedStart,vm_size_t * size)471 IOMallocAlignedGetAddress(
472 	IOLibPageMallocHeader  *hdr,
473 	mach_vm_address_t       alignedStart,
474 	vm_size_t              *size)
475 {
476 	mach_vm_address_t       address = 0;
477 	mach_vm_address_t       recalAlignedStart = 0;
478 	mach_vm_offset_t        offset = hdr->allocationOffset;
479 	mach_vm_size_t          alignMask = hdr->alignMask;
480 #if __has_feature(ptrauth_calls)
481 	offset = (mach_vm_offset_t) ptrauth_auth_data((void *)offset,
482 	    ptrauth_key_process_independent_data,
483 	    ptrauth_blend_discriminator((void *)(alignedStart | alignMask),
484 	    OS_PTRAUTH_DISCRIMINATOR("IOLibPageMallocHeader.allocationOffset")));
485 #endif /* __has_feature(ptrauth_calls) */
486 	if (os_sub_overflow(alignedStart, offset, &address) ||
487 	    os_add3_overflow(address, sizeofIOLibPageMallocHeader, alignMask,
488 	    &recalAlignedStart) ||
489 	    (((recalAlignedStart &= ~alignMask) != alignedStart) &&
490 	    (round_page(recalAlignedStart) != alignedStart)) ||
491 	    (offset < sizeofIOLibPageMallocHeader) ||
492 	    os_add_overflow(*size, alignMask, size)) {
493 		IOMallocAlignedHdrCorruptionPanic(offset, alignMask, alignedStart, *size);
494 	}
495 	return address;
496 }
497 
498 void *
499 (IOMallocAligned_internal)(struct kalloc_heap *kheap, vm_size_t size,
500 vm_size_t alignment, zalloc_flags_t flags)
501 {
502 	kern_return_t           kr;
503 	vm_offset_t             address;
504 	vm_offset_t             allocationAddress;
505 	vm_size_t               adjustedSize;
506 	uintptr_t               alignMask;
507 	IOLibPageMallocHeader * hdr;
508 	kma_flags_t kma_flags = KMA_NONE;
509 
510 	if (size == 0) {
511 		return NULL;
512 	}
513 	if (((uint32_t) alignment) != alignment) {
514 		return NULL;
515 	}
516 
517 	if (flags & Z_ZERO) {
518 		kma_flags = KMA_ZERO;
519 	}
520 
521 	if (kheap == KHEAP_DATA_BUFFERS) {
522 		kma_flags = (kma_flags_t) (kma_flags | KMA_DATA);
523 	} else if (kheap == KHEAP_DATA_SHARED) {
524 		kma_flags = (kma_flags_t) (kma_flags | KMA_DATA_SHARED);
525 	}
526 
527 	alignment = (1UL << log2up((uint32_t) alignment));
528 	alignMask = alignment - 1;
529 	adjustedSize = size + sizeofIOLibPageMallocHeader;
530 
531 	if (size > adjustedSize) {
532 		address = 0; /* overflow detected */
533 	} else if (adjustedSize >= page_size) {
534 		kr = kernel_memory_allocate(kernel_map, &address,
535 		    size, alignMask, kma_flags, IOMemoryTag(kernel_map));
536 		if (KERN_SUCCESS != kr) {
537 			address = 0;
538 		}
539 #if IOTRACKING
540 		else if (TRACK_ALLOC) {
541 			IOTrackingAlloc(gIOMallocTracking, address, size);
542 		}
543 #endif
544 	} else {
545 		adjustedSize += alignMask;
546 
547 		if (adjustedSize >= page_size) {
548 			kr = kmem_alloc(kernel_map, &allocationAddress,
549 			    adjustedSize, kma_flags, IOMemoryTag(kernel_map));
550 			if (KERN_SUCCESS != kr) {
551 				allocationAddress = 0;
552 			}
553 		} else {
554 			allocationAddress = (vm_address_t) kheap_alloc(kheap,
555 			    adjustedSize, Z_VM_TAG(Z_WAITOK | flags, VM_KERN_MEMORY_IOKIT));
556 		}
557 
558 		if (allocationAddress) {
559 			address = (allocationAddress + alignMask + sizeofIOLibPageMallocHeader)
560 			    & (~alignMask);
561 
562 			hdr = (typeof(hdr))(address - sizeofIOLibPageMallocHeader);
563 			IOMallocAlignedSetHdr(hdr, alignMask, allocationAddress, address);
564 #if IOTRACKING
565 			if (TRACK_ALLOC) {
566 				bzero(&hdr->tracking, sizeof(hdr->tracking));
567 				hdr->tracking.address = ~address;
568 				hdr->tracking.size = size;
569 				IOTrackingAdd(gIOMallocTracking, &hdr->tracking.tracking, size, true, VM_KERN_MEMORY_NONE);
570 			}
571 #endif
572 		} else {
573 			address = 0;
574 		}
575 	}
576 
577 	assert(0 == (address & alignMask));
578 
579 	if (address) {
580 #if IOALLOCDEBUG
581 		OSAddAtomicLong(size, &debug_iomalloc_size);
582 #endif
583 		IOStatisticsAlloc(kIOStatisticsMallocAligned, size);
584 	}
585 
586 	return (void *) address;
587 }
588 
589 void
IOFreeAligned_internal(kalloc_heap_t kheap,void * address,vm_size_t size)590 IOFreeAligned_internal(kalloc_heap_t kheap, void * address, vm_size_t size)
591 {
592 	vm_address_t            allocationAddress;
593 	vm_size_t               adjustedSize;
594 	IOLibPageMallocHeader * hdr;
595 
596 	if (!address) {
597 		return;
598 	}
599 
600 	assert(size);
601 
602 	adjustedSize = size + sizeofIOLibPageMallocHeader;
603 	if (adjustedSize >= page_size) {
604 #if IOTRACKING
605 		if (TRACK_ALLOC) {
606 			IOTrackingFree(gIOMallocTracking, (uintptr_t) address, size);
607 		}
608 #endif
609 		kmem_free(kernel_map, (vm_offset_t) address, size);
610 	} else {
611 		hdr = (typeof(hdr))(((uintptr_t)address) - sizeofIOLibPageMallocHeader);
612 		allocationAddress = IOMallocAlignedGetAddress(hdr,
613 		    (mach_vm_address_t)address, &adjustedSize);
614 
615 #if IOTRACKING
616 		if (TRACK_ALLOC) {
617 			if (size != hdr->tracking.size) {
618 				OSReportWithBacktrace("bad IOFreeAligned size 0x%zx should be 0x%zx",
619 				    (size_t)size, (size_t)hdr->tracking.size);
620 				size = hdr->tracking.size;
621 			}
622 			IOTrackingRemoveAddress(gIOMallocTracking, &hdr->tracking, size);
623 		}
624 #endif
625 		if (adjustedSize >= page_size) {
626 			kmem_free(kernel_map, allocationAddress, adjustedSize);
627 		} else {
628 			kheap_free(kheap, allocationAddress, adjustedSize);
629 		}
630 	}
631 
632 #if IOALLOCDEBUG
633 	OSAddAtomicLong(-size, &debug_iomalloc_size);
634 #endif
635 
636 	IOStatisticsAlloc(kIOStatisticsFreeAligned, size);
637 }
638 
639 void *
640 IOMallocAligned_external(
641 	vm_size_t size, vm_size_t alignment);
642 void *
IOMallocAligned_external(vm_size_t size,vm_size_t alignment)643 IOMallocAligned_external(
644 	vm_size_t size, vm_size_t alignment)
645 {
646 	return IOMallocAligned_internal(KHEAP_DATA_BUFFERS, size, alignment,
647 	           Z_VM_TAG_BT_BIT);
648 }
649 
650 void
IOFreeAligned(void * address,vm_size_t size)651 IOFreeAligned(
652 	void                  * address,
653 	vm_size_t               size)
654 {
655 	IOFreeAligned_internal(KHEAP_DATA_BUFFERS, address, size);
656 }
657 
658 __typed_allocators_ignore_pop
659 
660 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
661 
662 void
IOKernelFreePhysical(kalloc_heap_t kheap,mach_vm_address_t address,mach_vm_size_t size)663 IOKernelFreePhysical(
664 	kalloc_heap_t         kheap,
665 	mach_vm_address_t     address,
666 	mach_vm_size_t        size)
667 {
668 	vm_address_t       allocationAddress;
669 	vm_size_t          adjustedSize;
670 	IOLibPageMallocHeader * hdr;
671 
672 	if (!address) {
673 		return;
674 	}
675 
676 	assert(size);
677 
678 	adjustedSize = (2 * size) + sizeofIOLibPageMallocHeader;
679 	if (adjustedSize >= page_size) {
680 #if IOTRACKING
681 		if (TRACK_ALLOC) {
682 			IOTrackingFree(gIOMallocTracking, address, size);
683 		}
684 #endif
685 		kmem_free(kernel_map, (vm_offset_t) address, size);
686 	} else {
687 		hdr = (typeof(hdr))(((uintptr_t)address) - sizeofIOLibPageMallocHeader);
688 		allocationAddress = IOMallocAlignedGetAddress(hdr, address, &adjustedSize);
689 #if IOTRACKING
690 		if (TRACK_ALLOC) {
691 			IOTrackingRemoveAddress(gIOMallocTracking, &hdr->tracking, size);
692 		}
693 #endif
694 		__typed_allocators_ignore(kheap_free(kheap, allocationAddress, adjustedSize));
695 	}
696 
697 	IOStatisticsAlloc(kIOStatisticsFreeContiguous, size);
698 #if IOALLOCDEBUG
699 	OSAddAtomicLong(-size, &debug_iomalloc_size);
700 #endif
701 }
702 
703 #if __arm64__
704 extern unsigned long gPhysBase, gPhysSize;
705 #endif
706 
707 mach_vm_address_t
IOKernelAllocateWithPhysicalRestrict(kalloc_heap_t kheap,mach_vm_size_t size,mach_vm_address_t maxPhys,mach_vm_size_t alignment,bool contiguous)708 IOKernelAllocateWithPhysicalRestrict(
709 	kalloc_heap_t         kheap,
710 	mach_vm_size_t        size,
711 	mach_vm_address_t     maxPhys,
712 	mach_vm_size_t        alignment,
713 	bool                  contiguous)
714 {
715 	kern_return_t           kr;
716 	mach_vm_address_t       address;
717 	mach_vm_address_t       allocationAddress;
718 	mach_vm_size_t          adjustedSize;
719 	mach_vm_address_t       alignMask;
720 	IOLibPageMallocHeader * hdr;
721 
722 	if (size == 0) {
723 		return 0;
724 	}
725 	if (alignment == 0) {
726 		alignment = 1;
727 	}
728 
729 	alignMask = alignment - 1;
730 
731 	if (os_mul_and_add_overflow(2, size, sizeofIOLibPageMallocHeader, &adjustedSize)) {
732 		return 0;
733 	}
734 
735 	contiguous = (contiguous && (adjustedSize > page_size))
736 	    || (alignment > page_size);
737 
738 	if (contiguous || maxPhys) {
739 		kma_flags_t options = KMA_ZERO;
740 		vm_offset_t virt;
741 
742 		if (kheap == KHEAP_DATA_BUFFERS) {
743 			options = (kma_flags_t) (options | KMA_DATA);
744 		} else if (kheap == KHEAP_DATA_SHARED) {
745 			options = (kma_flags_t) (options | KMA_DATA_SHARED);
746 		}
747 
748 		adjustedSize = size;
749 		contiguous = (contiguous && (adjustedSize > page_size))
750 		    || (alignment > page_size);
751 
752 		if (!contiguous) {
753 #if __arm64__
754 			if (maxPhys >= (mach_vm_address_t)(gPhysBase + gPhysSize)) {
755 				maxPhys = 0;
756 			} else
757 #endif
758 			if (maxPhys <= 0xFFFFFFFF) {
759 				maxPhys = 0;
760 				options = (kma_flags_t)(options | KMA_LOMEM);
761 			} else if (gIOLastPage && (atop_64(maxPhys) > gIOLastPage)) {
762 				maxPhys = 0;
763 			}
764 		}
765 		if (contiguous || maxPhys) {
766 			kr = kmem_alloc_contig(kernel_map, &virt, size,
767 			    alignMask, (ppnum_t) atop(maxPhys), (ppnum_t) atop(alignMask),
768 			    options, IOMemoryTag(kernel_map));
769 		} else {
770 			kr = kernel_memory_allocate(kernel_map, &virt,
771 			    size, alignMask, options, IOMemoryTag(kernel_map));
772 		}
773 		if (KERN_SUCCESS == kr) {
774 			address = virt;
775 #if IOTRACKING
776 			if (TRACK_ALLOC) {
777 				IOTrackingAlloc(gIOMallocTracking, address, size);
778 			}
779 #endif
780 		} else {
781 			address = 0;
782 		}
783 	} else {
784 		adjustedSize += alignMask;
785 		if (adjustedSize < size) {
786 			return 0;
787 		}
788 		/* BEGIN IGNORE CODESTYLE */
789 		__typed_allocators_ignore_push // allocator implementation
790 		allocationAddress = (mach_vm_address_t) kheap_alloc(kheap,
791 		    adjustedSize, Z_VM_TAG_BT(Z_WAITOK, VM_KERN_MEMORY_IOKIT));
792 		__typed_allocators_ignore_pop
793 		/* END IGNORE CODESTYLE */
794 
795 		if (allocationAddress) {
796 			address = (allocationAddress + alignMask + sizeofIOLibPageMallocHeader)
797 			    & (~alignMask);
798 
799 			if (atop_32(address) != atop_32(address + size - 1)) {
800 				address = round_page(address);
801 			}
802 
803 			hdr = (typeof(hdr))(address - sizeofIOLibPageMallocHeader);
804 			IOMallocAlignedSetHdr(hdr, alignMask, allocationAddress, address);
805 #if IOTRACKING
806 			if (TRACK_ALLOC) {
807 				bzero(&hdr->tracking, sizeof(hdr->tracking));
808 				hdr->tracking.address = ~address;
809 				hdr->tracking.size    = size;
810 				IOTrackingAdd(gIOMallocTracking, &hdr->tracking.tracking, size, true, VM_KERN_MEMORY_NONE);
811 			}
812 #endif
813 		} else {
814 			address = 0;
815 		}
816 	}
817 
818 	if (address) {
819 		IOStatisticsAlloc(kIOStatisticsMallocContiguous, size);
820 #if IOALLOCDEBUG
821 		OSAddAtomicLong(size, &debug_iomalloc_size);
822 #endif
823 	}
824 
825 	return address;
826 }
827 
828 
829 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
830 
831 struct _IOMallocContiguousEntry {
832 	mach_vm_address_t          virtualAddr;
833 	IOBufferMemoryDescriptor * md;
834 	queue_chain_t              link;
835 };
836 typedef struct _IOMallocContiguousEntry _IOMallocContiguousEntry;
837 
838 void *
IOMallocContiguous(vm_size_t size,vm_size_t alignment,IOPhysicalAddress * physicalAddress)839 IOMallocContiguous(vm_size_t size, vm_size_t alignment,
840     IOPhysicalAddress * physicalAddress)
841 {
842 	mach_vm_address_t   address = 0;
843 
844 	if (size == 0) {
845 		return NULL;
846 	}
847 	if (alignment == 0) {
848 		alignment = 1;
849 	}
850 
851 	/* Do we want a physical address? */
852 	if (!physicalAddress) {
853 		address = IOKernelAllocateWithPhysicalRestrict(KHEAP_DEFAULT,
854 		    size, 0 /*maxPhys*/, alignment, true);
855 	} else {
856 		do {
857 			IOBufferMemoryDescriptor * bmd;
858 			mach_vm_address_t          physicalMask;
859 			vm_offset_t                alignMask;
860 
861 			alignMask = alignment - 1;
862 			physicalMask = (0xFFFFFFFF ^ alignMask);
863 
864 			bmd = IOBufferMemoryDescriptor::inTaskWithPhysicalMask(
865 				kernel_task, kIOMemoryPhysicallyContiguous, size, physicalMask);
866 			if (!bmd) {
867 				break;
868 			}
869 
870 			_IOMallocContiguousEntry *
871 			    entry = IOMallocType(_IOMallocContiguousEntry);
872 			if (!entry) {
873 				bmd->release();
874 				break;
875 			}
876 			entry->virtualAddr = (mach_vm_address_t) bmd->getBytesNoCopy();
877 			entry->md          = bmd;
878 			lck_mtx_lock(gIOMallocContiguousEntriesLock);
879 			queue_enter( &gIOMallocContiguousEntries, entry,
880 			    _IOMallocContiguousEntry *, link );
881 			lck_mtx_unlock(gIOMallocContiguousEntriesLock);
882 
883 			address          = (mach_vm_address_t) entry->virtualAddr;
884 			*physicalAddress = bmd->getPhysicalAddress();
885 		}while (false);
886 	}
887 
888 	return (void *) address;
889 }
890 
891 void
IOFreeContiguous(void * _address,vm_size_t size)892 IOFreeContiguous(void * _address, vm_size_t size)
893 {
894 	_IOMallocContiguousEntry * entry;
895 	IOMemoryDescriptor *       md = NULL;
896 
897 	mach_vm_address_t address = (mach_vm_address_t) _address;
898 
899 	if (!address) {
900 		return;
901 	}
902 
903 	assert(size);
904 
905 	lck_mtx_lock(gIOMallocContiguousEntriesLock);
906 	queue_iterate( &gIOMallocContiguousEntries, entry,
907 	    _IOMallocContiguousEntry *, link )
908 	{
909 		if (entry->virtualAddr == address) {
910 			md   = entry->md;
911 			queue_remove( &gIOMallocContiguousEntries, entry,
912 			    _IOMallocContiguousEntry *, link );
913 			break;
914 		}
915 	}
916 	lck_mtx_unlock(gIOMallocContiguousEntriesLock);
917 
918 	if (md) {
919 		md->release();
920 		IOFreeType(entry, _IOMallocContiguousEntry);
921 	} else {
922 		IOKernelFreePhysical(KHEAP_DEFAULT, (mach_vm_address_t) address, size);
923 	}
924 }
925 
926 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
927 
928 kern_return_t
IOIteratePageableMaps(vm_size_t size,IOIteratePageableMapsCallback callback,void * ref)929 IOIteratePageableMaps(vm_size_t size,
930     IOIteratePageableMapsCallback callback, void * ref)
931 {
932 	if (size > kIOPageableMaxAllocSize) {
933 		return kIOReturnBadArgument;
934 	}
935 	return (*callback)(gIOKitPageableMap.map, ref);
936 }
937 
938 struct IOMallocPageableRef {
939 	vm_offset_t address;
940 	vm_size_t   size;
941 	vm_tag_t    tag;
942 };
943 
944 static kern_return_t
IOMallocPageableCallback(vm_map_t map,void * _ref)945 IOMallocPageableCallback(vm_map_t map, void * _ref)
946 {
947 	struct IOMallocPageableRef * ref = (struct IOMallocPageableRef *) _ref;
948 	kma_flags_t flags = (kma_flags_t)(KMA_PAGEABLE | KMA_DATA);
949 
950 	return kmem_alloc( map, &ref->address, ref->size, flags, ref->tag );
951 }
952 
953 static void *
IOMallocPageablePages(vm_size_t size,vm_size_t alignment,vm_tag_t tag)954 IOMallocPageablePages(vm_size_t size, vm_size_t alignment, vm_tag_t tag)
955 {
956 	kern_return_t              kr = kIOReturnNotReady;
957 	struct IOMallocPageableRef ref;
958 
959 	if (alignment > page_size) {
960 		return NULL;
961 	}
962 	if (size > kIOPageableMaxAllocSize) {
963 		return NULL;
964 	}
965 
966 	ref.size = size;
967 	ref.tag  = tag;
968 	kr = IOIteratePageableMaps( size, &IOMallocPageableCallback, &ref );
969 	if (kIOReturnSuccess != kr) {
970 		ref.address = 0;
971 	}
972 
973 	return (void *) ref.address;
974 }
975 
976 vm_map_t
IOPageableMapForAddress(uintptr_t address)977 IOPageableMapForAddress(uintptr_t address)
978 {
979 	if (address < gIOKitPageableMap.address || address >= gIOKitPageableMap.end) {
980 		panic("IOPageableMapForAddress: address out of range");
981 	}
982 	return gIOKitPageableMap.map;
983 }
984 
985 static void
IOFreePageablePages(void * address,vm_size_t size)986 IOFreePageablePages(void * address, vm_size_t size)
987 {
988 	vm_map_t map;
989 
990 	map = IOPageableMapForAddress((vm_address_t) address);
991 	if (map) {
992 		kmem_free( map, (vm_offset_t) address, size);
993 	}
994 }
995 
996 #if defined(__x86_64__)
997 static uintptr_t
IOMallocOnePageablePage(kalloc_heap_t kheap __unused,iopa_t * a)998 IOMallocOnePageablePage(kalloc_heap_t kheap __unused, iopa_t * a)
999 {
1000 	return (uintptr_t) IOMallocPageablePages(page_size, page_size, VM_KERN_MEMORY_IOKIT);
1001 }
1002 #endif /* defined(__x86_64__) */
1003 
1004 static void *
IOMallocPageableInternal(vm_size_t size,vm_size_t alignment,bool zeroed)1005 IOMallocPageableInternal(vm_size_t size, vm_size_t alignment, bool zeroed)
1006 {
1007 	void * addr;
1008 
1009 	if (((uint32_t) alignment) != alignment) {
1010 		return NULL;
1011 	}
1012 #if defined(__x86_64__)
1013 	if (size >= (page_size - 4 * gIOPageAllocChunkBytes) ||
1014 	    alignment > page_size) {
1015 		addr = IOMallocPageablePages(size, alignment, IOMemoryTag(kernel_map));
1016 		/* Memory allocated this way will already be zeroed. */
1017 	} else {
1018 		addr = ((void *) iopa_alloc(&gIOPageablePageAllocator,
1019 		    &IOMallocOnePageablePage, KHEAP_DEFAULT, size, (uint32_t) alignment));
1020 		if (addr && zeroed) {
1021 			bzero(addr, size);
1022 		}
1023 	}
1024 #else /* !defined(__x86_64__) */
1025 	vm_size_t allocSize = size;
1026 	if (allocSize == 0) {
1027 		allocSize = 1;
1028 	}
1029 	addr = IOMallocPageablePages(allocSize, alignment, IOMemoryTag(kernel_map));
1030 	/* already zeroed */
1031 #endif /* defined(__x86_64__) */
1032 
1033 	if (addr) {
1034 #if IOALLOCDEBUG
1035 		OSAddAtomicLong(size, &debug_iomallocpageable_size);
1036 #endif
1037 		IOStatisticsAlloc(kIOStatisticsMallocPageable, size);
1038 	}
1039 
1040 	return addr;
1041 }
1042 
1043 void *
IOMallocPageable(vm_size_t size,vm_size_t alignment)1044 IOMallocPageable(vm_size_t size, vm_size_t alignment)
1045 {
1046 	return IOMallocPageableInternal(size, alignment, /*zeroed*/ false);
1047 }
1048 
1049 void *
IOMallocPageableZero(vm_size_t size,vm_size_t alignment)1050 IOMallocPageableZero(vm_size_t size, vm_size_t alignment)
1051 {
1052 	return IOMallocPageableInternal(size, alignment, /*zeroed*/ true);
1053 }
1054 
1055 void
IOFreePageable(void * address,vm_size_t size)1056 IOFreePageable(void * address, vm_size_t size)
1057 {
1058 #if IOALLOCDEBUG
1059 	OSAddAtomicLong(-size, &debug_iomallocpageable_size);
1060 #endif
1061 	IOStatisticsAlloc(kIOStatisticsFreePageable, size);
1062 
1063 #if defined(__x86_64__)
1064 	if (size < (page_size - 4 * gIOPageAllocChunkBytes)) {
1065 		address = (void *) iopa_free(&gIOPageablePageAllocator, (uintptr_t) address, size);
1066 		size = page_size;
1067 	}
1068 	if (address) {
1069 		IOFreePageablePages(address, size);
1070 	}
1071 #else /* !defined(__x86_64__) */
1072 	if (size == 0) {
1073 		size = 1;
1074 	}
1075 	if (address) {
1076 		IOFreePageablePages(address, size);
1077 	}
1078 #endif /* defined(__x86_64__) */
1079 }
1080 
1081 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1082 
1083 void *
1084 IOMallocData_external(
1085 	vm_size_t size);
1086 void *
IOMallocData_external(vm_size_t size)1087 IOMallocData_external(vm_size_t size)
1088 {
1089 	return IOMalloc_internal(KHEAP_DATA_BUFFERS, size, Z_VM_TAG_BT_BIT);
1090 }
1091 
1092 void *
1093 IOMallocZeroData_external(
1094 	vm_size_t size);
1095 void *
IOMallocZeroData_external(vm_size_t size)1096 IOMallocZeroData_external(vm_size_t size)
1097 {
1098 	return IOMalloc_internal(KHEAP_DATA_BUFFERS, size, Z_ZERO_VM_TAG_BT_BIT);
1099 }
1100 
1101 void
IOFreeData(void * address,vm_size_t size)1102 IOFreeData(void * address, vm_size_t size)
1103 {
1104 	return IOFree_internal(KHEAP_DATA_BUFFERS, address, size);
1105 }
1106 
1107 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1108 
1109 __typed_allocators_ignore_push // allocator implementation
1110 
1111 void *
IOMallocTypeImpl(kalloc_type_view_t kt_view)1112 IOMallocTypeImpl(kalloc_type_view_t kt_view)
1113 {
1114 #if IOTRACKING
1115 	/*
1116 	 * When leak detection is on default to using IOMalloc as kalloc
1117 	 * type infrastructure isn't aware of needing additional space for
1118 	 * the header.
1119 	 */
1120 	if (TRACK_ALLOC) {
1121 		uint32_t kt_size = kalloc_type_get_size(kt_view->kt_size);
1122 		void *mem = IOMalloc_internal(KHEAP_DEFAULT, kt_size, Z_ZERO);
1123 		if (!IOMallocType_from_vm(kt_view)) {
1124 			assert(mem);
1125 		}
1126 		return mem;
1127 	}
1128 #endif
1129 	zalloc_flags_t kt_flags = (zalloc_flags_t) (Z_WAITOK | Z_ZERO);
1130 	if (!IOMallocType_from_vm(kt_view)) {
1131 		kt_flags = (zalloc_flags_t) (kt_flags | Z_NOFAIL);
1132 	}
1133 	/*
1134 	 * Use external symbol for kalloc_type_impl as
1135 	 * kalloc_type_views generated at some external callsites
1136 	 * many not have been processed during boot.
1137 	 */
1138 	return kalloc_type_impl_external(kt_view, kt_flags);
1139 }
1140 
1141 void
IOFreeTypeImpl(kalloc_type_view_t kt_view,void * address)1142 IOFreeTypeImpl(kalloc_type_view_t kt_view, void * address)
1143 {
1144 #if IOTRACKING
1145 	if (TRACK_ALLOC) {
1146 		return IOFree_internal(KHEAP_DEFAULT, address,
1147 		           kalloc_type_get_size(kt_view->kt_size));
1148 	}
1149 #endif
1150 	/*
1151 	 * Use external symbol for kalloc_type_impl as
1152 	 * kalloc_type_views generated at some external callsites
1153 	 * many not have been processed during boot.
1154 	 */
1155 	return kfree_type_impl_external(kt_view, address);
1156 }
1157 
1158 void *
IOMallocTypeVarImpl(kalloc_type_var_view_t kt_view,vm_size_t size)1159 IOMallocTypeVarImpl(kalloc_type_var_view_t kt_view, vm_size_t size)
1160 {
1161 #if IOTRACKING
1162 	/*
1163 	 * When leak detection is on default to using IOMalloc as kalloc
1164 	 * type infrastructure isn't aware of needing additional space for
1165 	 * the header.
1166 	 */
1167 	if (TRACK_ALLOC) {
1168 		return IOMalloc_internal(KHEAP_DEFAULT, size, Z_ZERO);
1169 	}
1170 #endif
1171 	zalloc_flags_t kt_flags = (zalloc_flags_t) (Z_WAITOK | Z_ZERO);
1172 
1173 	kt_flags = Z_VM_TAG_BT(kt_flags, VM_KERN_MEMORY_KALLOC_TYPE);
1174 	return kalloc_type_var_impl(kt_view, size, kt_flags, NULL);
1175 }
1176 
1177 void
IOFreeTypeVarImpl(kalloc_type_var_view_t kt_view,void * address,vm_size_t size)1178 IOFreeTypeVarImpl(kalloc_type_var_view_t kt_view, void * address,
1179     vm_size_t size)
1180 {
1181 #if IOTRACKING
1182 	if (TRACK_ALLOC) {
1183 		return IOFree_internal(KHEAP_DEFAULT, address, size);
1184 	}
1185 #endif
1186 
1187 	return kfree_type_var_impl(kt_view, address, size);
1188 }
1189 
1190 __typed_allocators_ignore_pop
1191 
1192 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1193 
1194 #if defined(__x86_64__)
1195 
1196 
1197 extern "C" void
iopa_init(iopa_t * a)1198 iopa_init(iopa_t * a)
1199 {
1200 	bzero(a, sizeof(*a));
1201 	a->lock = IOLockAlloc();
1202 	queue_init(&a->list);
1203 }
1204 
1205 static uintptr_t
iopa_allocinpage(iopa_page_t * pa,uint32_t count,uint64_t align)1206 iopa_allocinpage(iopa_page_t * pa, uint32_t count, uint64_t align)
1207 {
1208 	uint32_t n, s;
1209 	uint64_t avail = pa->avail;
1210 
1211 	assert(avail);
1212 
1213 	// find strings of count 1 bits in avail
1214 	for (n = count; n > 1; n -= s) {
1215 		s = n >> 1;
1216 		avail = avail & (avail << s);
1217 	}
1218 	// and aligned
1219 	avail &= align;
1220 
1221 	if (avail) {
1222 		n = __builtin_clzll(avail);
1223 		pa->avail &= ~((-1ULL << (64 - count)) >> n);
1224 		if (!pa->avail && pa->link.next) {
1225 			remque(&pa->link);
1226 			pa->link.next = NULL;
1227 		}
1228 		return n * gIOPageAllocChunkBytes + trunc_page((uintptr_t) pa);
1229 	}
1230 
1231 	return 0;
1232 }
1233 
1234 uintptr_t
iopa_alloc(iopa_t * a,iopa_proc_t alloc,kalloc_heap_t kheap,vm_size_t bytes,vm_size_t balign)1235 iopa_alloc(
1236 	iopa_t          * a,
1237 	iopa_proc_t       alloc,
1238 	kalloc_heap_t     kheap,
1239 	vm_size_t         bytes,
1240 	vm_size_t         balign)
1241 {
1242 	static const uint64_t align_masks[] = {
1243 		0xFFFFFFFFFFFFFFFF,
1244 		0xAAAAAAAAAAAAAAAA,
1245 		0x8888888888888888,
1246 		0x8080808080808080,
1247 		0x8000800080008000,
1248 		0x8000000080000000,
1249 		0x8000000000000000,
1250 	};
1251 	iopa_page_t * pa;
1252 	uintptr_t     addr = 0;
1253 	uint32_t      count;
1254 	uint64_t      align;
1255 	vm_size_t     align_masks_idx;
1256 
1257 	if (((uint32_t) bytes) != bytes) {
1258 		return 0;
1259 	}
1260 	if (!bytes) {
1261 		bytes = 1;
1262 	}
1263 	count = (((uint32_t) bytes) + gIOPageAllocChunkBytes - 1) / gIOPageAllocChunkBytes;
1264 
1265 	align_masks_idx = log2up((balign + gIOPageAllocChunkBytes - 1) / gIOPageAllocChunkBytes);
1266 	assert(align_masks_idx < sizeof(align_masks) / sizeof(*align_masks));
1267 	align = align_masks[align_masks_idx];
1268 
1269 	IOLockLock(a->lock);
1270 	__IGNORE_WCASTALIGN(pa = (typeof(pa))queue_first(&a->list));
1271 	while (!queue_end(&a->list, &pa->link)) {
1272 		addr = iopa_allocinpage(pa, count, align);
1273 		if (addr) {
1274 			a->bytecount += bytes;
1275 			break;
1276 		}
1277 		__IGNORE_WCASTALIGN(pa = (typeof(pa))queue_next(&pa->link));
1278 	}
1279 	IOLockUnlock(a->lock);
1280 
1281 	if (!addr) {
1282 		addr = alloc(kheap, a);
1283 		if (addr) {
1284 			pa = (typeof(pa))(addr + page_size - gIOPageAllocChunkBytes);
1285 			pa->signature = kIOPageAllocSignature;
1286 			pa->avail     = -2ULL;
1287 
1288 			addr = iopa_allocinpage(pa, count, align);
1289 			IOLockLock(a->lock);
1290 			if (pa->avail) {
1291 				enqueue_head(&a->list, &pa->link);
1292 			}
1293 			a->pagecount++;
1294 			if (addr) {
1295 				a->bytecount += bytes;
1296 			}
1297 			IOLockUnlock(a->lock);
1298 		}
1299 	}
1300 
1301 	assert((addr & ((1 << log2up(balign)) - 1)) == 0);
1302 	return addr;
1303 }
1304 
1305 uintptr_t
iopa_free(iopa_t * a,uintptr_t addr,vm_size_t bytes)1306 iopa_free(iopa_t * a, uintptr_t addr, vm_size_t bytes)
1307 {
1308 	iopa_page_t * pa;
1309 	uint32_t      count;
1310 	uintptr_t     chunk;
1311 
1312 	if (((uint32_t) bytes) != bytes) {
1313 		return 0;
1314 	}
1315 	if (!bytes) {
1316 		bytes = 1;
1317 	}
1318 
1319 	chunk = (addr & page_mask);
1320 	assert(0 == (chunk & (gIOPageAllocChunkBytes - 1)));
1321 
1322 	pa = (typeof(pa))(addr | (page_size - gIOPageAllocChunkBytes));
1323 	assert(kIOPageAllocSignature == pa->signature);
1324 
1325 	count = (((uint32_t) bytes) + gIOPageAllocChunkBytes - 1) / gIOPageAllocChunkBytes;
1326 	chunk /= gIOPageAllocChunkBytes;
1327 
1328 	IOLockLock(a->lock);
1329 	if (!pa->avail) {
1330 		assert(!pa->link.next);
1331 		enqueue_tail(&a->list, &pa->link);
1332 	}
1333 	pa->avail |= ((-1ULL << (64 - count)) >> chunk);
1334 	if (pa->avail != -2ULL) {
1335 		pa = NULL;
1336 	} else {
1337 		remque(&pa->link);
1338 		pa->link.next = NULL;
1339 		pa->signature = 0;
1340 		a->pagecount--;
1341 		// page to free
1342 		pa = (typeof(pa))trunc_page(pa);
1343 	}
1344 	a->bytecount -= bytes;
1345 	IOLockUnlock(a->lock);
1346 
1347 	return (uintptr_t) pa;
1348 }
1349 
1350 #endif /* defined(__x86_64__) */
1351 
1352 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1353 
1354 IOReturn
IOSetProcessorCacheMode(task_t task,IOVirtualAddress address,IOByteCount length,IOOptionBits cacheMode)1355 IOSetProcessorCacheMode( task_t task, IOVirtualAddress address,
1356     IOByteCount length, IOOptionBits cacheMode )
1357 {
1358 	IOReturn    ret = kIOReturnSuccess;
1359 	ppnum_t     pagenum;
1360 
1361 	if (task != kernel_task) {
1362 		return kIOReturnUnsupported;
1363 	}
1364 	if ((address | length) & PAGE_MASK) {
1365 //	OSReportWithBacktrace("IOSetProcessorCacheMode(0x%x, 0x%x, 0x%x) fails\n", address, length, cacheMode);
1366 		return kIOReturnUnsupported;
1367 	}
1368 	length = round_page(address + length) - trunc_page( address );
1369 	address = trunc_page( address );
1370 
1371 	// make map mode
1372 	cacheMode = (cacheMode << kIOMapCacheShift) & kIOMapCacheMask;
1373 
1374 	while ((kIOReturnSuccess == ret) && (length > 0)) {
1375 		// Get the physical page number
1376 		pagenum = pmap_find_phys(kernel_pmap, (addr64_t)address);
1377 		if (pagenum) {
1378 			ret = IOUnmapPages( get_task_map(task), address, page_size );
1379 			ret = IOMapPages( get_task_map(task), address, ptoa_64(pagenum), page_size, cacheMode );
1380 		} else {
1381 			ret = kIOReturnVMError;
1382 		}
1383 
1384 		address += page_size;
1385 		length -= page_size;
1386 	}
1387 
1388 	return ret;
1389 }
1390 
1391 
1392 IOReturn
IOFlushProcessorCache(task_t task,IOVirtualAddress address,IOByteCount length)1393 IOFlushProcessorCache( task_t task, IOVirtualAddress address,
1394     IOByteCount length )
1395 {
1396 	if (task != kernel_task) {
1397 		return kIOReturnUnsupported;
1398 	}
1399 
1400 	flush_dcache64((addr64_t) address, (unsigned) length, false );
1401 
1402 	return kIOReturnSuccess;
1403 }
1404 
1405 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1406 
1407 vm_offset_t
OSKernelStackRemaining(void)1408 OSKernelStackRemaining( void )
1409 {
1410 	return ml_stack_remaining();
1411 }
1412 
1413 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1414 
1415 /*
1416  * Spin for indicated number of milliseconds.
1417  */
1418 void
IOSleep(unsigned milliseconds)1419 IOSleep(unsigned milliseconds)
1420 {
1421 	delay_for_interval(milliseconds, kMillisecondScale);
1422 }
1423 
1424 /*
1425  * Spin for indicated number of milliseconds, and potentially an
1426  * additional number of milliseconds up to the leeway values.
1427  */
1428 void
IOSleepWithLeeway(unsigned intervalMilliseconds,unsigned leewayMilliseconds)1429 IOSleepWithLeeway(unsigned intervalMilliseconds, unsigned leewayMilliseconds)
1430 {
1431 	delay_for_interval_with_leeway(intervalMilliseconds, leewayMilliseconds, kMillisecondScale);
1432 }
1433 
1434 /*
1435  * Spin for indicated number of microseconds.
1436  */
1437 void
IODelay(unsigned microseconds)1438 IODelay(unsigned microseconds)
1439 {
1440 	delay_for_interval(microseconds, kMicrosecondScale);
1441 }
1442 
1443 /*
1444  * Spin for indicated number of nanoseconds.
1445  */
1446 void
IOPause(unsigned nanoseconds)1447 IOPause(unsigned nanoseconds)
1448 {
1449 	delay_for_interval(nanoseconds, kNanosecondScale);
1450 }
1451 
1452 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1453 
1454 static void _IOLogv(const char *format, va_list ap, void *caller) __printflike(1, 0);
1455 
1456 __attribute__((noinline, not_tail_called))
1457 void
IOLog(const char * format,...)1458 IOLog(const char *format, ...)
1459 {
1460 	void *caller = __builtin_return_address(0);
1461 	va_list ap;
1462 
1463 	va_start(ap, format);
1464 	_IOLogv(format, ap, caller);
1465 	va_end(ap);
1466 }
1467 
1468 __attribute__((noinline, not_tail_called))
1469 void
IOLogv(const char * format,va_list ap)1470 IOLogv(const char *format, va_list ap)
1471 {
1472 	void *caller = __builtin_return_address(0);
1473 	_IOLogv(format, ap, caller);
1474 }
1475 
1476 void
_IOLogv(const char * format,va_list ap,void * caller)1477 _IOLogv(const char *format, va_list ap, void *caller)
1478 {
1479 	va_list ap2;
1480 	struct console_printbuf_state info_data;
1481 	console_printbuf_state_init(&info_data, TRUE, TRUE);
1482 
1483 	va_copy(ap2, ap);
1484 
1485 #pragma clang diagnostic push
1486 #pragma clang diagnostic ignored "-Wformat-nonliteral"
1487 	os_log_with_args(OS_LOG_DEFAULT, OS_LOG_TYPE_DEFAULT, format, ap, caller);
1488 #pragma clang diagnostic pop
1489 
1490 	if (!disable_iolog_serial_output) {
1491 		__doprnt(format, ap2, console_printbuf_putc, &info_data, 16, TRUE);
1492 		console_printbuf_clear(&info_data);
1493 	}
1494 	va_end(ap2);
1495 
1496 	assertf(ml_get_interrupts_enabled() || ml_is_quiescing() ||
1497 	    debug_mode_active() || !gCPUsRunning,
1498 	    "IOLog called with interrupts disabled");
1499 }
1500 
1501 #if !__LP64__
1502 void
IOPanic(const char * reason)1503 IOPanic(const char *reason)
1504 {
1505 	panic("%s", reason);
1506 }
1507 #endif
1508 
1509 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1510 
1511 void
IOKitKernelLogBuffer(const char * title,const void * buffer,size_t size,void (* output)(const char * format,...))1512 IOKitKernelLogBuffer(const char * title, const void * buffer, size_t size,
1513     void (*output)(const char *format, ...))
1514 {
1515 	size_t idx, linestart;
1516 	enum { bytelen = (sizeof("0xZZ, ") - 1) };
1517 	char hex[(bytelen * 16) + 1];
1518 	uint8_t c, chars[17];
1519 
1520 	output("%s(0x%lx):\n", title, size);
1521 	output("              0     1     2     3     4     5     6     7     8     9     A     B     C     D     E     F\n");
1522 	if (size > 4096) {
1523 		size = 4096;
1524 	}
1525 	chars[16] = 0;
1526 	for (idx = 0, linestart = 0; idx < size;) {
1527 		c = ((char *)buffer)[idx];
1528 		snprintf(&hex[bytelen * (idx & 15)], bytelen + 1, "0x%02x, ", c);
1529 		chars[idx & 15] = ((c >= 0x20) && (c <= 0x7f)) ? c : ' ';
1530 		idx++;
1531 		if ((idx == size) || !(idx & 15)) {
1532 			if (idx & 15) {
1533 				chars[idx & 15] = 0;
1534 			}
1535 			output("/* %04lx: */ %-96s /* |%-16s| */\n", linestart, hex, chars);
1536 			linestart += 16;
1537 		}
1538 	}
1539 }
1540 
1541 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1542 
1543 /*
1544  * Convert a integer constant (typically a #define or enum) to a string.
1545  */
1546 static char noValue[80];        // that's pretty
1547 
1548 const char *
IOFindNameForValue(int value,const IONamedValue * regValueArray)1549 IOFindNameForValue(int value, const IONamedValue *regValueArray)
1550 {
1551 	for (; regValueArray->name; regValueArray++) {
1552 		if (regValueArray->value == value) {
1553 			return regValueArray->name;
1554 		}
1555 	}
1556 	snprintf(noValue, sizeof(noValue), "0x%x (UNDEFINED)", value);
1557 	return (const char *)noValue;
1558 }
1559 
1560 IOReturn
IOFindValueForName(const char * string,const IONamedValue * regValueArray,int * value)1561 IOFindValueForName(const char *string,
1562     const IONamedValue *regValueArray,
1563     int *value)
1564 {
1565 	for (; regValueArray->name; regValueArray++) {
1566 		if (!strcmp(regValueArray->name, string)) {
1567 			*value = regValueArray->value;
1568 			return kIOReturnSuccess;
1569 		}
1570 	}
1571 	return kIOReturnBadArgument;
1572 }
1573 
1574 OSString *
IOCopyLogNameForPID(int pid)1575 IOCopyLogNameForPID(int pid)
1576 {
1577 	char   buf[128];
1578 	size_t len;
1579 	snprintf(buf, sizeof(buf), "pid %d, ", pid);
1580 	len = strlen(buf);
1581 	proc_name(pid, buf + len, (int) (sizeof(buf) - len));
1582 	return OSString::withCString(buf);
1583 }
1584 
1585 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1586 
1587 IOAlignment
IOSizeToAlignment(unsigned int size)1588 IOSizeToAlignment(unsigned int size)
1589 {
1590 	int shift;
1591 	const int intsize = sizeof(unsigned int) * 8;
1592 
1593 	for (shift = 1; shift < intsize; shift++) {
1594 		if (size & 0x80000000) {
1595 			return (IOAlignment)(intsize - shift);
1596 		}
1597 		size <<= 1;
1598 	}
1599 	return 0;
1600 }
1601 
1602 unsigned int
IOAlignmentToSize(IOAlignment align)1603 IOAlignmentToSize(IOAlignment align)
1604 {
1605 	unsigned int size;
1606 
1607 	for (size = 1; align; align--) {
1608 		size <<= 1;
1609 	}
1610 	return size;
1611 }
1612 } /* extern "C" */
1613