VirtualBox

source: vbox/trunk/src/VBox/Runtime/r0drv/darwin/memobj-r0drv-darwin.cpp@ 40974

Last change on this file since 40974 was 39744, checked in by vboxsync, 13 years ago

rtr0memobj: Status code adjustments.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 38.9 KB
Line 
1/* $Id: memobj-r0drv-darwin.cpp 39744 2012-01-10 18:15:04Z vboxsync $ */
2/** @file
3 * IPRT - Ring-0 Memory Objects, Darwin.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#include "the-darwin-kernel.h"
32#include "internal/iprt.h"
33#include <iprt/memobj.h>
34
35#include <iprt/asm.h>
36#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
37# include <iprt/asm-amd64-x86.h>
38#endif
39#include <iprt/assert.h>
40#include <iprt/log.h>
41#include <iprt/mem.h>
42#include <iprt/param.h>
43#include <iprt/process.h>
44#include <iprt/string.h>
45#include <iprt/thread.h>
46#include "internal/memobj.h"
47
48/*#define USE_VM_MAP_WIRE - may re-enable later when non-mapped allocations are added. */
49
50
51/*******************************************************************************
52* Structures and Typedefs *
53*******************************************************************************/
54/**
55 * The Darwin version of the memory object structure.
56 */
57typedef struct RTR0MEMOBJDARWIN
58{
59 /** The core structure. */
60 RTR0MEMOBJINTERNAL Core;
61 /** Pointer to the memory descriptor created for allocated and locked memory. */
62 IOMemoryDescriptor *pMemDesc;
63 /** Pointer to the memory mapping object for mapped memory. */
64 IOMemoryMap *pMemMap;
65} RTR0MEMOBJDARWIN, *PRTR0MEMOBJDARWIN;
66
67
68/**
69 * HACK ALERT!
70 *
71 * Touch the pages to force the kernel to create the page
72 * table entries. This is necessary since the kernel gets
73 * upset if we take a page fault when preemption is disabled
74 * and/or we own a simple lock. It has no problems with us
75 * disabling interrupts when taking the traps, weird stuff.
76 *
77 * @param pv Pointer to the first page.
78 * @param cb The number of bytes.
79 */
80static void rtR0MemObjDarwinTouchPages(void *pv, size_t cb)
81{
82 uint32_t volatile *pu32 = (uint32_t volatile *)pv;
83 for (;;)
84 {
85 ASMAtomicCmpXchgU32(pu32, 0xdeadbeef, 0xdeadbeef);
86 if (cb <= PAGE_SIZE)
87 break;
88 cb -= PAGE_SIZE;
89 pu32 += PAGE_SIZE / sizeof(uint32_t);
90 }
91}
92
93
94/**
95 * Gets the virtual memory map the specified object is mapped into.
96 *
97 * @returns VM map handle on success, NULL if no map.
98 * @param pMem The memory object.
99 */
100DECLINLINE(vm_map_t) rtR0MemObjDarwinGetMap(PRTR0MEMOBJINTERNAL pMem)
101{
102 switch (pMem->enmType)
103 {
104 case RTR0MEMOBJTYPE_PAGE:
105 case RTR0MEMOBJTYPE_LOW:
106 case RTR0MEMOBJTYPE_CONT:
107 return kernel_map;
108
109 case RTR0MEMOBJTYPE_PHYS:
110 case RTR0MEMOBJTYPE_PHYS_NC:
111 return NULL; /* pretend these have no mapping atm. */
112
113 case RTR0MEMOBJTYPE_LOCK:
114 return pMem->u.Lock.R0Process == NIL_RTR0PROCESS
115 ? kernel_map
116 : get_task_map((task_t)pMem->u.Lock.R0Process);
117
118 case RTR0MEMOBJTYPE_RES_VIRT:
119 return pMem->u.ResVirt.R0Process == NIL_RTR0PROCESS
120 ? kernel_map
121 : get_task_map((task_t)pMem->u.ResVirt.R0Process);
122
123 case RTR0MEMOBJTYPE_MAPPING:
124 return pMem->u.Mapping.R0Process == NIL_RTR0PROCESS
125 ? kernel_map
126 : get_task_map((task_t)pMem->u.Mapping.R0Process);
127
128 default:
129 return NULL;
130 }
131}
132
133#if 0 /* not necessary after all*/
134/* My vm_map mockup. */
135struct my_vm_map
136{
137 struct { char pad[8]; } lock;
138 struct my_vm_map_header
139 {
140 struct vm_map_links
141 {
142 void *prev;
143 void *next;
144 vm_map_offset_t start;
145 vm_map_offset_t end;
146 } links;
147 int nentries;
148 boolean_t entries_pageable;
149 } hdr;
150 pmap_t pmap;
151 vm_map_size_t size;
152};
153
154
155/**
156 * Gets the minimum map address, this is similar to get_map_min.
157 *
158 * @returns The start address of the map.
159 * @param pMap The map.
160 */
161static vm_map_offset_t rtR0MemObjDarwinGetMapMin(vm_map_t pMap)
162{
163 /* lazy discovery of the correct offset. The apple guys is a wonderfully secretive bunch. */
164 static int32_t volatile s_offAdjust = INT32_MAX;
165 int32_t off = s_offAdjust;
166 if (off == INT32_MAX)
167 {
168 for (off = 0; ; off += sizeof(pmap_t))
169 {
170 if (*(pmap_t *)((uint8_t *)kernel_map + off) == kernel_pmap)
171 break;
172 AssertReturn(off <= RT_MAX(RT_OFFSETOF(struct my_vm_map, pmap) * 4, 1024), 0x1000);
173 }
174 ASMAtomicWriteS32(&s_offAdjust, off - RT_OFFSETOF(struct my_vm_map, pmap));
175 }
176
177 /* calculate it. */
178 struct my_vm_map *pMyMap = (struct my_vm_map *)((uint8_t *)pMap + off);
179 return pMyMap->hdr.links.start;
180}
181#endif /* unused */
182
183#ifdef RT_STRICT
184
185/**
186 * Read from a physical page.
187 *
188 * @param HCPhys The address to start reading at.
189 * @param cb How many bytes to read.
190 * @param pvDst Where to put the bytes. This is zero'd on failure.
191 */
192static void rtR0MemObjDarwinReadPhys(RTHCPHYS HCPhys, size_t cb, void *pvDst)
193{
194 memset(pvDst, '\0', cb);
195
196 IOAddressRange aRanges[1] = { { (mach_vm_address_t)HCPhys, RT_ALIGN(cb, PAGE_SIZE) } };
197 IOMemoryDescriptor *pMemDesc = IOMemoryDescriptor::withAddressRanges(&aRanges[0], RT_ELEMENTS(aRanges),
198 kIODirectionIn, NULL /*task*/);
199 if (pMemDesc)
200 {
201#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
202 IOMemoryMap *pMemMap = pMemDesc->createMappingInTask(kernel_task, 0, kIOMapAnywhere | kIOMapDefaultCache);
203#else
204 IOMemoryMap *pMemMap = pMemDesc->map(kernel_task, 0, kIOMapAnywhere | kIOMapDefaultCache);
205#endif
206 if (pMemMap)
207 {
208 void const *pvSrc = (void const *)(uintptr_t)pMemMap->getVirtualAddress();
209 memcpy(pvDst, pvSrc, cb);
210 pMemMap->release();
211 }
212 else
213 printf("rtR0MemObjDarwinReadPhys: createMappingInTask failed; HCPhys=%llx\n", HCPhys);
214
215 pMemDesc->release();
216 }
217 else
218 printf("rtR0MemObjDarwinReadPhys: withAddressRanges failed; HCPhys=%llx\n", HCPhys);
219}
220
221
222/**
223 * Gets the PTE for a page.
224 *
225 * @returns the PTE.
226 * @param pvPage The virtual address to get the PTE for.
227 */
228static uint64_t rtR0MemObjDarwinGetPTE(void *pvPage)
229{
230 RTUINT64U u64;
231 RTCCUINTREG cr3 = ASMGetCR3();
232 RTCCUINTREG cr4 = ASMGetCR4();
233 bool fPAE = false;
234 bool fLMA = false;
235 if (cr4 & RT_BIT(5) /*X86_CR4_PAE*/)
236 {
237 fPAE = true;
238 uint32_t fAmdFeatures = ASMCpuId_EDX(0x80000001);
239 if (fAmdFeatures & RT_BIT(29) /*X86_CPUID_AMD_FEATURE_EDX_LONG_MODE*/)
240 {
241 uint64_t efer = ASMRdMsr(0xc0000080 /*MSR_K6_EFER*/);
242 if (efer & RT_BIT(10) /*MSR_K6_EFER_LMA*/)
243 fLMA = true;
244 }
245 }
246
247 if (fLMA)
248 {
249 /* PML4 */
250 rtR0MemObjDarwinReadPhys((cr3 & ~(RTCCUINTREG)PAGE_OFFSET_MASK) | (((uint64_t)(uintptr_t)pvPage >> 39) & 0x1ff) * 8, 8, &u64);
251 if (!(u64.u & RT_BIT(0) /* present */))
252 {
253 printf("rtR0MemObjDarwinGetPTE: %p -> PML4E !p\n", pvPage);
254 return 0;
255 }
256
257 /* PDPTR */
258 rtR0MemObjDarwinReadPhys((u64.u & ~(uint64_t)PAGE_OFFSET_MASK) | (((uintptr_t)pvPage >> 30) & 0x1ff) * 8, 8, &u64);
259 if (!(u64.u & RT_BIT(0) /* present */))
260 {
261 printf("rtR0MemObjDarwinGetPTE: %p -> PDPTE !p\n", pvPage);
262 return 0;
263 }
264 if (u64.u & RT_BIT(7) /* big */)
265 return (u64.u & ~(uint64_t)(_1G -1)) | ((uintptr_t)pvPage & (_1G -1));
266
267 /* PD */
268 rtR0MemObjDarwinReadPhys((u64.u & ~(uint64_t)PAGE_OFFSET_MASK) | (((uintptr_t)pvPage >> 21) & 0x1ff) * 8, 8, &u64);
269 if (!(u64.u & RT_BIT(0) /* present */))
270 {
271 printf("rtR0MemObjDarwinGetPTE: %p -> PDE !p\n", pvPage);
272 return 0;
273 }
274 if (u64.u & RT_BIT(7) /* big */)
275 return (u64.u & ~(uint64_t)(_2M -1)) | ((uintptr_t)pvPage & (_2M -1));
276
277 /* PD */
278 rtR0MemObjDarwinReadPhys((u64.u & ~(uint64_t)PAGE_OFFSET_MASK) | (((uintptr_t)pvPage >> 12) & 0x1ff) * 8, 8, &u64);
279 if (!(u64.u & RT_BIT(0) /* present */))
280 {
281 printf("rtR0MemObjDarwinGetPTE: %p -> PTE !p\n", pvPage);
282 return 0;
283 }
284 return u64.u;
285 }
286
287 if (fPAE)
288 {
289 /* PDPTR */
290 rtR0MemObjDarwinReadPhys((u64.u & 0xffffffe0 /*X86_CR3_PAE_PAGE_MASK*/) | (((uintptr_t)pvPage >> 30) & 0x3) * 8, 8, &u64);
291 if (!(u64.u & RT_BIT(0) /* present */))
292 return 0;
293
294 /* PD */
295 rtR0MemObjDarwinReadPhys((u64.u & ~(uint64_t)PAGE_OFFSET_MASK) | (((uintptr_t)pvPage >> 21) & 0x1ff) * 8, 8, &u64);
296 if (!(u64.u & RT_BIT(0) /* present */))
297 return 0;
298 if (u64.u & RT_BIT(7) /* big */)
299 return (u64.u & ~(uint64_t)(_2M -1)) | ((uintptr_t)pvPage & (_2M -1));
300
301 /* PD */
302 rtR0MemObjDarwinReadPhys((u64.u & ~(uint64_t)PAGE_OFFSET_MASK) | (((uintptr_t)pvPage >> 12) & 0x1ff) * 8, 8, &u64);
303 if (!(u64.u & RT_BIT(0) /* present */))
304 return 0;
305 return u64.u;
306 }
307
308 /* PD */
309 rtR0MemObjDarwinReadPhys((u64.au32[0] & ~(uint32_t)PAGE_OFFSET_MASK) | (((uintptr_t)pvPage >> 22) & 0x3ff) * 4, 4, &u64);
310 if (!(u64.au32[0] & RT_BIT(0) /* present */))
311 return 0;
312 if (u64.au32[0] & RT_BIT(7) /* big */)
313 return (u64.u & ~(uint64_t)(_2M -1)) | ((uintptr_t)pvPage & (_2M -1));
314
315 /* PD */
316 rtR0MemObjDarwinReadPhys((u64.au32[0] & ~(uint32_t)PAGE_OFFSET_MASK) | (((uintptr_t)pvPage >> 12) & 0x3ff) * 4, 4, &u64);
317 if (!(u64.au32[0] & RT_BIT(0) /* present */))
318 return 0;
319 return u64.au32[0];
320
321 return 0;
322}
323
324#endif /* RT_STRICT */
325
326DECLHIDDEN(int) rtR0MemObjNativeFree(RTR0MEMOBJ pMem)
327{
328 PRTR0MEMOBJDARWIN pMemDarwin = (PRTR0MEMOBJDARWIN)pMem;
329
330 /*
331 * Release the IOMemoryDescriptor or/and IOMemoryMap associated with the object.
332 */
333 if (pMemDarwin->pMemDesc)
334 {
335 if (pMemDarwin->Core.enmType == RTR0MEMOBJTYPE_LOCK)
336 pMemDarwin->pMemDesc->complete(); /* paranoia */
337 pMemDarwin->pMemDesc->release();
338 pMemDarwin->pMemDesc = NULL;
339 }
340
341 if (pMemDarwin->pMemMap)
342 {
343 pMemDarwin->pMemMap->release();
344 pMemDarwin->pMemMap = NULL;
345 }
346
347 /*
348 * Release any memory that we've allocated or locked.
349 */
350 switch (pMemDarwin->Core.enmType)
351 {
352 case RTR0MEMOBJTYPE_LOW:
353 case RTR0MEMOBJTYPE_PAGE:
354 case RTR0MEMOBJTYPE_CONT:
355 break;
356
357 case RTR0MEMOBJTYPE_LOCK:
358 {
359#ifdef USE_VM_MAP_WIRE
360 vm_map_t Map = pMemDarwin->Core.u.Lock.R0Process != NIL_RTR0PROCESS
361 ? get_task_map((task_t)pMemDarwin->Core.u.Lock.R0Process)
362 : kernel_map;
363 kern_return_t kr = vm_map_unwire(Map,
364 (vm_map_offset_t)pMemDarwin->Core.pv,
365 (vm_map_offset_t)pMemDarwin->Core.pv + pMemDarwin->Core.cb,
366 0 /* not user */);
367 AssertRC(kr == KERN_SUCCESS); /** @todo don't ignore... */
368#endif
369 break;
370 }
371
372 case RTR0MEMOBJTYPE_PHYS:
373 /*if (pMemDarwin->Core.u.Phys.fAllocated)
374 IOFreePhysical(pMemDarwin->Core.u.Phys.PhysBase, pMemDarwin->Core.cb);*/
375 Assert(!pMemDarwin->Core.u.Phys.fAllocated);
376 break;
377
378 case RTR0MEMOBJTYPE_PHYS_NC:
379 AssertMsgFailed(("RTR0MEMOBJTYPE_PHYS_NC\n"));
380 return VERR_INTERNAL_ERROR;
381
382 case RTR0MEMOBJTYPE_RES_VIRT:
383 AssertMsgFailed(("RTR0MEMOBJTYPE_RES_VIRT\n"));
384 return VERR_INTERNAL_ERROR;
385
386 case RTR0MEMOBJTYPE_MAPPING:
387 /* nothing to do here. */
388 break;
389
390 default:
391 AssertMsgFailed(("enmType=%d\n", pMemDarwin->Core.enmType));
392 return VERR_INTERNAL_ERROR;
393 }
394
395 return VINF_SUCCESS;
396}
397
398
399
400/**
401 * Kernel memory alloc worker that uses inTaskWithPhysicalMask.
402 *
403 * @returns IPRT status code.
404 * @retval VERR_ADDRESS_TOO_BIG try another way.
405 *
406 * @param ppMem Where to return the memory object.
407 * @param cb The page aligned memory size.
408 * @param fExecutable Whether the mapping needs to be executable.
409 * @param fContiguous Whether the backing memory needs to be contiguous.
410 * @param PhysMask The mask for the backing memory (i.e. range). Use 0 if
411 * you don't care that much or is speculating.
412 * @param MaxPhysAddr The max address to verify the result against. Use
413 * UINT64_MAX if it doesn't matter.
414 * @param enmType The object type.
415 */
416static int rtR0MemObjNativeAllocWorker(PPRTR0MEMOBJINTERNAL ppMem, size_t cb,
417 bool fExecutable, bool fContiguous,
418 mach_vm_address_t PhysMask, uint64_t MaxPhysAddr,
419 RTR0MEMOBJTYPE enmType)
420{
421 /*
422 * Try inTaskWithPhysicalMask first, but since we don't quite trust that it
423 * actually respects the physical memory mask (10.5.x is certainly busted),
424 * we'll use rtR0MemObjNativeAllocCont as a fallback for dealing with that.
425 *
426 * The kIOMemoryKernelUserShared flag just forces the result to be page aligned.
427 */
428 int rc;
429 IOBufferMemoryDescriptor *pMemDesc =
430 IOBufferMemoryDescriptor::inTaskWithPhysicalMask(kernel_task,
431 kIOMemoryKernelUserShared
432 | kIODirectionInOut
433 | (fContiguous ? kIOMemoryPhysicallyContiguous : 0),
434 cb,
435 PhysMask);
436 if (pMemDesc)
437 {
438 IOReturn IORet = pMemDesc->prepare(kIODirectionInOut);
439 if (IORet == kIOReturnSuccess)
440 {
441 void *pv = pMemDesc->getBytesNoCopy(0, cb);
442 if (pv)
443 {
444 /*
445 * Check if it's all below 4GB.
446 */
447 addr64_t AddrPrev = 0;
448 MaxPhysAddr &= ~(uint64_t)PAGE_OFFSET_MASK;
449 for (IOByteCount off = 0; off < cb; off += PAGE_SIZE)
450 {
451#ifdef __LP64__ /* Grumble! */
452 addr64_t Addr = pMemDesc->getPhysicalSegment(off, NULL);
453#else
454 addr64_t Addr = pMemDesc->getPhysicalSegment64(off, NULL);
455#endif
456 if ( Addr > MaxPhysAddr
457 || !Addr
458 || (Addr & PAGE_OFFSET_MASK)
459 || ( fContiguous
460 && !off
461 && Addr == AddrPrev + PAGE_SIZE))
462 {
463 /* Buggy API, try allocate the memory another way. */
464 pMemDesc->release();
465 if (PhysMask)
466 LogAlways(("rtR0MemObjNativeAllocWorker: off=%x Addr=%llx AddrPrev=%llx MaxPhysAddr=%llx PhysMas=%llx - buggy API!\n",
467 off, Addr, AddrPrev, MaxPhysAddr, PhysMask));
468 return VERR_ADDRESS_TOO_BIG;
469 }
470 AddrPrev = Addr;
471 }
472
473#ifdef RT_STRICT
474 /* check that the memory is actually mapped. */
475 //addr64_t Addr = pMemDesc->getPhysicalSegment64(0, NULL);
476 //printf("rtR0MemObjNativeAllocWorker: pv=%p %8llx %8llx\n", pv, rtR0MemObjDarwinGetPTE(pv), Addr);
477 RTTHREADPREEMPTSTATE State = RTTHREADPREEMPTSTATE_INITIALIZER;
478 RTThreadPreemptDisable(&State);
479 rtR0MemObjDarwinTouchPages(pv, cb);
480 RTThreadPreemptRestore(&State);
481#endif
482
483 /*
484 * Create the IPRT memory object.
485 */
486 PRTR0MEMOBJDARWIN pMemDarwin = (PRTR0MEMOBJDARWIN)rtR0MemObjNew(sizeof(*pMemDarwin), enmType, pv, cb);
487 if (pMemDarwin)
488 {
489 if (fContiguous)
490 {
491#ifdef __LP64__ /* Grumble! */
492 addr64_t PhysBase64 = pMemDesc->getPhysicalSegment(0, NULL);
493#else
494 addr64_t PhysBase64 = pMemDesc->getPhysicalSegment64(0, NULL);
495#endif
496 RTHCPHYS PhysBase = PhysBase64; Assert(PhysBase == PhysBase64);
497 if (enmType == RTR0MEMOBJTYPE_CONT)
498 pMemDarwin->Core.u.Cont.Phys = PhysBase;
499 else if (enmType == RTR0MEMOBJTYPE_PHYS)
500 pMemDarwin->Core.u.Phys.PhysBase = PhysBase;
501 else
502 AssertMsgFailed(("enmType=%d\n", enmType));
503 }
504
505 pMemDarwin->pMemDesc = pMemDesc;
506 *ppMem = &pMemDarwin->Core;
507 return VINF_SUCCESS;
508 }
509
510 if (enmType == RTR0MEMOBJTYPE_PHYS_NC)
511 rc = VERR_NO_PHYS_MEMORY;
512 else if (enmType == RTR0MEMOBJTYPE_LOW)
513 rc = VERR_NO_LOW_MEMORY;
514 else if (enmType == RTR0MEMOBJTYPE_CONT)
515 rc = VERR_NO_CONT_MEMORY;
516 else
517 rc = VERR_NO_MEMORY;
518 }
519 else
520 rc = VERR_MEMOBJ_INIT_FAILED;
521 }
522 else
523 rc = RTErrConvertFromDarwinIO(IORet);
524 pMemDesc->release();
525 }
526 else
527 rc = VERR_MEMOBJ_INIT_FAILED;
528 Assert(rc != VERR_ADDRESS_TOO_BIG);
529 return rc;
530}
531
532
533DECLHIDDEN(int) rtR0MemObjNativeAllocPage(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, bool fExecutable)
534{
535 return rtR0MemObjNativeAllocWorker(ppMem, cb, fExecutable, false /* fContiguous */,
536 0 /* PhysMask */, UINT64_MAX, RTR0MEMOBJTYPE_PAGE);
537}
538
539
540DECLHIDDEN(int) rtR0MemObjNativeAllocLow(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, bool fExecutable)
541{
542 /*
543 * Try IOMallocPhysical/IOMallocAligned first.
544 * Then try optimistically without a physical address mask, which will always
545 * end up using IOMallocAligned.
546 *
547 * (See bug comment in the worker and IOBufferMemoryDescriptor::initWithPhysicalMask.)
548 */
549 int rc = rtR0MemObjNativeAllocWorker(ppMem, cb, fExecutable, false /* fContiguous */,
550 ~(uint32_t)PAGE_OFFSET_MASK, _4G - PAGE_SIZE, RTR0MEMOBJTYPE_LOW);
551 if (rc == VERR_ADDRESS_TOO_BIG)
552 rc = rtR0MemObjNativeAllocWorker(ppMem, cb, fExecutable, false /* fContiguous */,
553 0 /* PhysMask */, _4G - PAGE_SIZE, RTR0MEMOBJTYPE_LOW);
554 return rc;
555}
556
557
558DECLHIDDEN(int) rtR0MemObjNativeAllocCont(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, bool fExecutable)
559{
560 int rc = rtR0MemObjNativeAllocWorker(ppMem, cb, fExecutable, true /* fContiguous */,
561 ~(uint32_t)PAGE_OFFSET_MASK, _4G - PAGE_SIZE,
562 RTR0MEMOBJTYPE_CONT);
563
564 /*
565 * Workaround for bogus IOKernelAllocateContiguous behavior, just in case.
566 * cb <= PAGE_SIZE allocations take a different path, using a different allocator.
567 */
568 if (RT_FAILURE(rc) && cb <= PAGE_SIZE)
569 rc = rtR0MemObjNativeAllocWorker(ppMem, cb + PAGE_SIZE, fExecutable, true /* fContiguous */,
570 ~(uint32_t)PAGE_OFFSET_MASK, _4G - PAGE_SIZE,
571 RTR0MEMOBJTYPE_CONT);
572 return rc;
573}
574
575
576DECLHIDDEN(int) rtR0MemObjNativeAllocPhys(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, RTHCPHYS PhysHighest, size_t uAlignment)
577{
578 /** @todo alignment */
579 if (uAlignment != PAGE_SIZE)
580 return VERR_NOT_SUPPORTED;
581
582 /*
583 * Translate the PhysHighest address into a mask.
584 */
585 int rc;
586 if (PhysHighest == NIL_RTHCPHYS)
587 rc = rtR0MemObjNativeAllocWorker(ppMem, cb, true /* fExecutable */, true /* fContiguous */,
588 0 /* PhysMask*/, UINT64_MAX, RTR0MEMOBJTYPE_PHYS);
589 else
590 {
591 mach_vm_address_t PhysMask = 0;
592 PhysMask = ~(mach_vm_address_t)0;
593 while (PhysMask > (PhysHighest | PAGE_OFFSET_MASK))
594 PhysMask >>= 1;
595 AssertReturn(PhysMask + 1 <= cb, VERR_INVALID_PARAMETER);
596 PhysMask &= ~(mach_vm_address_t)PAGE_OFFSET_MASK;
597
598 rc = rtR0MemObjNativeAllocWorker(ppMem, cb, true /* fExecutable */, true /* fContiguous */,
599 PhysMask, PhysHighest, RTR0MEMOBJTYPE_PHYS);
600 }
601 return rc;
602}
603
604
605DECLHIDDEN(int) rtR0MemObjNativeAllocPhysNC(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, RTHCPHYS PhysHighest)
606{
607 /** @todo rtR0MemObjNativeAllocPhys / darwin.
608 * This might be a bit problematic and may very well require having to create our own
609 * object which we populate with pages but without mapping it into any address space.
610 * Estimate is 2-3 days.
611 */
612 return VERR_NOT_SUPPORTED;
613}
614
615
616DECLHIDDEN(int) rtR0MemObjNativeEnterPhys(PPRTR0MEMOBJINTERNAL ppMem, RTHCPHYS Phys, size_t cb, uint32_t uCachePolicy)
617{
618 AssertReturn(uCachePolicy == RTMEM_CACHE_POLICY_DONT_CARE, VERR_NOT_SUPPORTED);
619
620 /*
621 * Create a descriptor for it (the validation is always true on intel macs, but
622 * as it doesn't harm us keep it in).
623 */
624 int rc = VERR_ADDRESS_TOO_BIG;
625 IOAddressRange aRanges[1] = { { Phys, cb } };
626 if ( aRanges[0].address == Phys
627 && aRanges[0].length == cb)
628 {
629 IOMemoryDescriptor *pMemDesc = IOMemoryDescriptor::withAddressRanges(&aRanges[0], RT_ELEMENTS(aRanges),
630 kIODirectionInOut, NULL /*task*/);
631 if (pMemDesc)
632 {
633#ifdef __LP64__ /* Grumble! */
634 Assert(Phys == pMemDesc->getPhysicalSegment(0, 0));
635#else
636 Assert(Phys == pMemDesc->getPhysicalSegment64(0, 0));
637#endif
638
639 /*
640 * Create the IPRT memory object.
641 */
642 PRTR0MEMOBJDARWIN pMemDarwin = (PRTR0MEMOBJDARWIN)rtR0MemObjNew(sizeof(*pMemDarwin), RTR0MEMOBJTYPE_PHYS, NULL, cb);
643 if (pMemDarwin)
644 {
645 pMemDarwin->Core.u.Phys.PhysBase = Phys;
646 pMemDarwin->Core.u.Phys.fAllocated = false;
647 pMemDarwin->Core.u.Phys.uCachePolicy = uCachePolicy;
648 pMemDarwin->pMemDesc = pMemDesc;
649 *ppMem = &pMemDarwin->Core;
650 return VINF_SUCCESS;
651 }
652
653 rc = VERR_NO_MEMORY;
654 pMemDesc->release();
655 }
656 else
657 rc = VERR_MEMOBJ_INIT_FAILED;
658 }
659 else
660 AssertMsgFailed(("%#llx %llx\n", (unsigned long long)Phys, (unsigned long long)cb));
661 return rc;
662}
663
664
665/**
666 * Internal worker for locking down pages.
667 *
668 * @return IPRT status code.
669 *
670 * @param ppMem Where to store the memory object pointer.
671 * @param pv First page.
672 * @param cb Number of bytes.
673 * @param fAccess The desired access, a combination of RTMEM_PROT_READ
674 * and RTMEM_PROT_WRITE.
675 * @param Task The task \a pv and \a cb refers to.
676 */
677static int rtR0MemObjNativeLock(PPRTR0MEMOBJINTERNAL ppMem, void *pv, size_t cb, uint32_t fAccess, task_t Task)
678{
679 NOREF(fAccess);
680#ifdef USE_VM_MAP_WIRE
681 vm_map_t Map = get_task_map(Task);
682 Assert(Map);
683
684 /*
685 * First try lock the memory.
686 */
687 int rc = VERR_LOCK_FAILED;
688 kern_return_t kr = vm_map_wire(get_task_map(Task),
689 (vm_map_offset_t)pv,
690 (vm_map_offset_t)pv + cb,
691 VM_PROT_DEFAULT,
692 0 /* not user */);
693 if (kr == KERN_SUCCESS)
694 {
695 /*
696 * Create the IPRT memory object.
697 */
698 PRTR0MEMOBJDARWIN pMemDarwin = (PRTR0MEMOBJDARWIN)rtR0MemObjNew(sizeof(*pMemDarwin), RTR0MEMOBJTYPE_LOCK, pv, cb);
699 if (pMemDarwin)
700 {
701 pMemDarwin->Core.u.Lock.R0Process = (RTR0PROCESS)Task;
702 *ppMem = &pMemDarwin->Core;
703 return VINF_SUCCESS;
704 }
705
706 kr = vm_map_unwire(get_task_map(Task), (vm_map_offset_t)pv, (vm_map_offset_t)pv + cb, 0 /* not user */);
707 Assert(kr == KERN_SUCCESS);
708 rc = VERR_NO_MEMORY;
709 }
710
711#else
712
713 /*
714 * Create a descriptor and try lock it (prepare).
715 */
716 int rc = VERR_MEMOBJ_INIT_FAILED;
717 IOMemoryDescriptor *pMemDesc = IOMemoryDescriptor::withAddressRange((vm_address_t)pv, cb, kIODirectionInOut, Task);
718 if (pMemDesc)
719 {
720 IOReturn IORet = pMemDesc->prepare(kIODirectionInOut);
721 if (IORet == kIOReturnSuccess)
722 {
723 /*
724 * Create the IPRT memory object.
725 */
726 PRTR0MEMOBJDARWIN pMemDarwin = (PRTR0MEMOBJDARWIN)rtR0MemObjNew(sizeof(*pMemDarwin), RTR0MEMOBJTYPE_LOCK, pv, cb);
727 if (pMemDarwin)
728 {
729 pMemDarwin->Core.u.Lock.R0Process = (RTR0PROCESS)Task;
730 pMemDarwin->pMemDesc = pMemDesc;
731 *ppMem = &pMemDarwin->Core;
732 return VINF_SUCCESS;
733 }
734
735 pMemDesc->complete();
736 rc = VERR_NO_MEMORY;
737 }
738 else
739 rc = VERR_LOCK_FAILED;
740 pMemDesc->release();
741 }
742#endif
743 return rc;
744}
745
746
747DECLHIDDEN(int) rtR0MemObjNativeLockUser(PPRTR0MEMOBJINTERNAL ppMem, RTR3PTR R3Ptr, size_t cb, uint32_t fAccess, RTR0PROCESS R0Process)
748{
749 return rtR0MemObjNativeLock(ppMem, (void *)R3Ptr, cb, fAccess, (task_t)R0Process);
750}
751
752
753DECLHIDDEN(int) rtR0MemObjNativeLockKernel(PPRTR0MEMOBJINTERNAL ppMem, void *pv, size_t cb, uint32_t fAccess)
754{
755 return rtR0MemObjNativeLock(ppMem, pv, cb, fAccess, kernel_task);
756}
757
758
759DECLHIDDEN(int) rtR0MemObjNativeReserveKernel(PPRTR0MEMOBJINTERNAL ppMem, void *pvFixed, size_t cb, size_t uAlignment)
760{
761 return VERR_NOT_SUPPORTED;
762}
763
764
765DECLHIDDEN(int) rtR0MemObjNativeReserveUser(PPRTR0MEMOBJINTERNAL ppMem, RTR3PTR R3PtrFixed, size_t cb, size_t uAlignment, RTR0PROCESS R0Process)
766{
767 return VERR_NOT_SUPPORTED;
768}
769
770
771DECLHIDDEN(int) rtR0MemObjNativeMapKernel(PPRTR0MEMOBJINTERNAL ppMem, RTR0MEMOBJ pMemToMap, void *pvFixed, size_t uAlignment,
772 unsigned fProt, size_t offSub, size_t cbSub)
773{
774 AssertReturn(pvFixed == (void *)-1, VERR_NOT_SUPPORTED);
775
776 /*
777 * Check that the specified alignment is supported.
778 */
779 if (uAlignment > PAGE_SIZE)
780 return VERR_NOT_SUPPORTED;
781
782 /*
783 * Must have a memory descriptor that we can map.
784 */
785 int rc = VERR_INVALID_PARAMETER;
786 PRTR0MEMOBJDARWIN pMemToMapDarwin = (PRTR0MEMOBJDARWIN)pMemToMap;
787 if (pMemToMapDarwin->pMemDesc)
788 {
789#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
790 IOMemoryMap *pMemMap = pMemToMapDarwin->pMemDesc->createMappingInTask(kernel_task,
791 0,
792 kIOMapAnywhere | kIOMapDefaultCache,
793 offSub,
794 cbSub);
795#else
796 IOMemoryMap *pMemMap = pMemToMapDarwin->pMemDesc->map(kernel_task,
797 0,
798 kIOMapAnywhere | kIOMapDefaultCache,
799 offSub,
800 cbSub);
801#endif
802 if (pMemMap)
803 {
804 IOVirtualAddress VirtAddr = pMemMap->getVirtualAddress();
805 void *pv = (void *)(uintptr_t)VirtAddr;
806 if ((uintptr_t)pv == VirtAddr)
807 {
808 //addr64_t Addr = pMemToMapDarwin->pMemDesc->getPhysicalSegment64(offSub, NULL);
809 //printf("pv=%p: %8llx %8llx\n", pv, rtR0MemObjDarwinGetPTE(pv), Addr);
810
811// /*
812// * Explicitly lock it so that we're sure it is present and that
813// * its PTEs cannot be recycled.
814// * Note! withAddressRange() doesn't work as it adds kIOMemoryTypeVirtual64
815// * to the options which causes prepare() to not wire the pages.
816// * This is probably a bug.
817// */
818// IOAddressRange Range = { (mach_vm_address_t)pv, cbSub };
819// IOMemoryDescriptor *pMemDesc = IOMemoryDescriptor::withOptions(&Range,
820// 1 /* count */,
821// 0 /* offset */,
822// kernel_task,
823// kIODirectionInOut | kIOMemoryTypeVirtual,
824// kIOMapperSystem);
825// if (pMemDesc)
826// {
827// IOReturn IORet = pMemDesc->prepare(kIODirectionInOut);
828// if (IORet == kIOReturnSuccess)
829// {
830 /* HACK ALERT! */
831 rtR0MemObjDarwinTouchPages(pv, cbSub);
832 /** @todo First, the memory should've been mapped by now, and second, it
833 * should have the wired attribute in the PTE (bit 9). Neither is
834 * seems to be the case. The disabled locking code doesn't make any
835 * difference, which is extremely odd, and breaks
836 * rtR0MemObjNativeGetPagePhysAddr (getPhysicalSegment64 -> 64 for the
837 * lock descriptor. */
838 //addr64_t Addr = pMemDesc->getPhysicalSegment64(0, NULL);
839 //printf("pv=%p: %8llx %8llx (%d)\n", pv, rtR0MemObjDarwinGetPTE(pv), Addr, 2);
840
841 /*
842 * Create the IPRT memory object.
843 */
844 PRTR0MEMOBJDARWIN pMemDarwin = (PRTR0MEMOBJDARWIN)rtR0MemObjNew(sizeof(*pMemDarwin), RTR0MEMOBJTYPE_MAPPING,
845 pv, cbSub);
846 if (pMemDarwin)
847 {
848 pMemDarwin->Core.u.Mapping.R0Process = NIL_RTR0PROCESS;
849 pMemDarwin->pMemMap = pMemMap;
850// pMemDarwin->pMemDesc = pMemDesc;
851 *ppMem = &pMemDarwin->Core;
852 return VINF_SUCCESS;
853 }
854
855// pMemDesc->complete();
856// rc = VERR_NO_MEMORY;
857// }
858// else
859// rc = RTErrConvertFromDarwinIO(IORet);
860// pMemDesc->release();
861// }
862// else
863// rc = VERR_MEMOBJ_INIT_FAILED;
864 }
865 else
866 rc = VERR_ADDRESS_TOO_BIG;
867 pMemMap->release();
868 }
869 else
870 rc = VERR_MAP_FAILED;
871 }
872 return rc;
873}
874
875
876DECLHIDDEN(int) rtR0MemObjNativeMapUser(PPRTR0MEMOBJINTERNAL ppMem, RTR0MEMOBJ pMemToMap, RTR3PTR R3PtrFixed, size_t uAlignment, unsigned fProt, RTR0PROCESS R0Process)
877{
878 /*
879 * Check for unsupported things.
880 */
881 AssertReturn(R3PtrFixed == (RTR3PTR)-1, VERR_NOT_SUPPORTED);
882 if (uAlignment > PAGE_SIZE)
883 return VERR_NOT_SUPPORTED;
884
885 /*
886 * Must have a memory descriptor.
887 */
888 int rc = VERR_INVALID_PARAMETER;
889 PRTR0MEMOBJDARWIN pMemToMapDarwin = (PRTR0MEMOBJDARWIN)pMemToMap;
890 if (pMemToMapDarwin->pMemDesc)
891 {
892#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
893 IOMemoryMap *pMemMap = pMemToMapDarwin->pMemDesc->createMappingInTask((task_t)R0Process,
894 0,
895 kIOMapAnywhere | kIOMapDefaultCache,
896 0 /* offset */,
897 0 /* length */);
898#else
899 IOMemoryMap *pMemMap = pMemToMapDarwin->pMemDesc->map((task_t)R0Process,
900 0,
901 kIOMapAnywhere | kIOMapDefaultCache);
902#endif
903 if (pMemMap)
904 {
905 IOVirtualAddress VirtAddr = pMemMap->getVirtualAddress();
906 void *pv = (void *)(uintptr_t)VirtAddr;
907 if ((uintptr_t)pv == VirtAddr)
908 {
909 /*
910 * Create the IPRT memory object.
911 */
912 PRTR0MEMOBJDARWIN pMemDarwin = (PRTR0MEMOBJDARWIN)rtR0MemObjNew(sizeof(*pMemDarwin), RTR0MEMOBJTYPE_MAPPING,
913 pv, pMemToMapDarwin->Core.cb);
914 if (pMemDarwin)
915 {
916 pMemDarwin->Core.u.Mapping.R0Process = R0Process;
917 pMemDarwin->pMemMap = pMemMap;
918 *ppMem = &pMemDarwin->Core;
919 return VINF_SUCCESS;
920 }
921
922 rc = VERR_NO_MEMORY;
923 }
924 else
925 rc = VERR_ADDRESS_TOO_BIG;
926 pMemMap->release();
927 }
928 else
929 rc = VERR_MAP_FAILED;
930 }
931 return rc;
932}
933
934
935DECLHIDDEN(int) rtR0MemObjNativeProtect(PRTR0MEMOBJINTERNAL pMem, size_t offSub, size_t cbSub, uint32_t fProt)
936{
937 /* Get the map for the object. */
938 vm_map_t pVmMap = rtR0MemObjDarwinGetMap(pMem);
939 if (!pVmMap)
940 return VERR_NOT_SUPPORTED;
941
942 /* Convert the protection. */
943 vm_prot_t fMachProt;
944 switch (fProt)
945 {
946 case RTMEM_PROT_NONE:
947 fMachProt = VM_PROT_NONE;
948 break;
949 case RTMEM_PROT_READ:
950 fMachProt = VM_PROT_READ;
951 break;
952 case RTMEM_PROT_READ | RTMEM_PROT_WRITE:
953 fMachProt = VM_PROT_READ | VM_PROT_WRITE;
954 break;
955 case RTMEM_PROT_READ | RTMEM_PROT_WRITE | RTMEM_PROT_EXEC:
956 fMachProt = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
957 break;
958 case RTMEM_PROT_WRITE | RTMEM_PROT_EXEC:
959 fMachProt = VM_PROT_WRITE | VM_PROT_EXECUTE;
960 break;
961 case RTMEM_PROT_EXEC:
962 fMachProt = VM_PROT_EXECUTE;
963 break;
964 default:
965 AssertFailedReturn(VERR_INVALID_PARAMETER);
966 }
967
968 /* do the job. */
969 vm_offset_t Start = (uintptr_t)pMem->pv + offSub;
970 kern_return_t krc = vm_protect(pVmMap,
971 Start,
972 cbSub,
973 false,
974 fMachProt);
975 if (krc != KERN_SUCCESS)
976 return RTErrConvertFromDarwinKern(krc);
977 return VINF_SUCCESS;
978}
979
980
981DECLHIDDEN(RTHCPHYS) rtR0MemObjNativeGetPagePhysAddr(PRTR0MEMOBJINTERNAL pMem, size_t iPage)
982{
983 RTHCPHYS PhysAddr;
984 PRTR0MEMOBJDARWIN pMemDarwin = (PRTR0MEMOBJDARWIN)pMem;
985
986#ifdef USE_VM_MAP_WIRE
987 /*
988 * Locked memory doesn't have a memory descriptor and
989 * needs to be handled differently.
990 */
991 if (pMemDarwin->Core.enmType == RTR0MEMOBJTYPE_LOCK)
992 {
993 ppnum_t PgNo;
994 if (pMemDarwin->Core.u.Lock.R0Process == NIL_RTR0PROCESS)
995 PgNo = pmap_find_phys(kernel_pmap, (uintptr_t)pMemDarwin->Core.pv + iPage * PAGE_SIZE);
996 else
997 {
998 /*
999 * From what I can tell, Apple seems to have locked up the all the
1000 * available interfaces that could help us obtain the pmap_t of a task
1001 * or vm_map_t.
1002
1003 * So, we'll have to figure out where in the vm_map_t structure it is
1004 * and read it our selves. ASSUMING that kernel_pmap is pointed to by
1005 * kernel_map->pmap, we scan kernel_map to locate the structure offset.
1006 * Not nice, but it will hopefully do the job in a reliable manner...
1007 *
1008 * (get_task_pmap, get_map_pmap or vm_map_pmap is what we really need btw.)
1009 */
1010 static int s_offPmap = -1;
1011 if (RT_UNLIKELY(s_offPmap == -1))
1012 {
1013 pmap_t const *p = (pmap_t *)kernel_map;
1014 pmap_t const * const pEnd = p + 64;
1015 for (; p < pEnd; p++)
1016 if (*p == kernel_pmap)
1017 {
1018 s_offPmap = (uintptr_t)p - (uintptr_t)kernel_map;
1019 break;
1020 }
1021 AssertReturn(s_offPmap >= 0, NIL_RTHCPHYS);
1022 }
1023 pmap_t Pmap = *(pmap_t *)((uintptr_t)get_task_map((task_t)pMemDarwin->Core.u.Lock.R0Process) + s_offPmap);
1024 PgNo = pmap_find_phys(Pmap, (uintptr_t)pMemDarwin->Core.pv + iPage * PAGE_SIZE);
1025 }
1026
1027 AssertReturn(PgNo, NIL_RTHCPHYS);
1028 PhysAddr = (RTHCPHYS)PgNo << PAGE_SHIFT;
1029 Assert((PhysAddr >> PAGE_SHIFT) == PgNo);
1030 }
1031 else
1032#endif /* USE_VM_MAP_WIRE */
1033 {
1034 /*
1035 * Get the memory descriptor.
1036 */
1037 IOMemoryDescriptor *pMemDesc = pMemDarwin->pMemDesc;
1038 if (!pMemDesc)
1039 pMemDesc = pMemDarwin->pMemMap->getMemoryDescriptor();
1040 AssertReturn(pMemDesc, NIL_RTHCPHYS);
1041
1042 /*
1043 * If we've got a memory descriptor, use getPhysicalSegment64().
1044 */
1045#ifdef __LP64__ /* Grumble! */
1046 addr64_t Addr = pMemDesc->getPhysicalSegment(iPage * PAGE_SIZE, NULL);
1047#else
1048 addr64_t Addr = pMemDesc->getPhysicalSegment64(iPage * PAGE_SIZE, NULL);
1049#endif
1050 AssertMsgReturn(Addr, ("iPage=%u\n", iPage), NIL_RTHCPHYS);
1051 PhysAddr = Addr;
1052 AssertMsgReturn(PhysAddr == Addr, ("PhysAddr=%RHp Addr=%RX64\n", PhysAddr, (uint64_t)Addr), NIL_RTHCPHYS);
1053 }
1054
1055 return PhysAddr;
1056}
1057
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette