2 * Copyright (c) 1998-2007 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
30 #include <sys/cdefs.h>
32 #include <IOKit/assert.h>
33 #include <IOKit/system.h>
34 #include <IOKit/IOLib.h>
35 #include <IOKit/IOMemoryDescriptor.h>
36 #include <IOKit/IOMapper.h>
37 #include <IOKit/IODMACommand.h>
38 #include <IOKit/IOKitKeysPrivate.h>
40 #include <IOKit/IOSubMemoryDescriptor.h>
41 #include <IOKit/IOMultiMemoryDescriptor.h>
43 #include <IOKit/IOKitDebug.h>
44 #include <libkern/OSDebug.h>
46 #include "IOKitKernelInternal.h"
48 #include <libkern/c++/OSContainers.h>
49 #include <libkern/c++/OSDictionary.h>
50 #include <libkern/c++/OSArray.h>
51 #include <libkern/c++/OSSymbol.h>
52 #include <libkern/c++/OSNumber.h>
58 #include <vm/vm_pageout.h>
59 #include <mach/memory_object_types.h>
60 #include <device/device_port.h>
62 #include <mach/vm_prot.h>
63 #include <mach/mach_vm.h>
64 #include <vm/vm_fault.h>
65 #include <vm/vm_protos.h>
67 extern ppnum_t
pmap_find_phys(pmap_t pmap
, addr64_t va
);
68 extern void ipc_port_release_send(ipc_port_t port
);
70 // osfmk/device/iokit_rpc.c
71 unsigned int IODefaultCacheBits(addr64_t pa
);
72 unsigned int IOTranslateCacheBits(struct phys_entry
*pp
);
76 #define kIOMapperWaitSystem ((IOMapper *) 1)
78 static IOMapper
* gIOSystemMapper
= NULL
;
82 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
84 OSDefineMetaClassAndAbstractStructors( IOMemoryDescriptor
, OSObject
)
86 #define super IOMemoryDescriptor
88 OSDefineMetaClassAndStructors(IOGeneralMemoryDescriptor
, IOMemoryDescriptor
)
90 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
92 static IORecursiveLock
* gIOMemoryLock
;
94 #define LOCK IORecursiveLockLock( gIOMemoryLock)
95 #define UNLOCK IORecursiveLockUnlock( gIOMemoryLock)
96 #define SLEEP IORecursiveLockSleep( gIOMemoryLock, (void *)this, THREAD_UNINT)
98 IORecursiveLockWakeup( gIOMemoryLock, (void *)this, /* one-thread */ false)
101 #define DEBG(fmt, args...) { kprintf(fmt, ## args); }
103 #define DEBG(fmt, args...) {}
106 #define IOMD_DEBUG_DMAACTIVE 1
108 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
110 // Some data structures and accessor macros used by the initWithOptions
113 enum ioPLBlockFlags
{
114 kIOPLOnDevice
= 0x00000001,
115 kIOPLExternUPL
= 0x00000002,
118 struct IOMDPersistentInitData
120 const IOGeneralMemoryDescriptor
* fMD
;
121 IOMemoryReference
* fMemRef
;
126 vm_address_t fPageInfo
; // Pointer to page list or index into it
127 uint32_t fIOMDOffset
; // The offset of this iopl in descriptor
128 ppnum_t fMappedPage
; // Page number of first page in this iopl
129 unsigned int fPageOffset
; // Offset within first page of iopl
130 unsigned int fFlags
; // Flags
135 uint8_t fDMAMapNumAddressBits
;
136 uint64_t fDMAMapAlignment
;
137 uint64_t fMappedBase
;
138 uint64_t fMappedLength
;
139 uint64_t fPreparationID
;
141 IOTracking fWireTracking
;
143 unsigned int fPageCnt
;
144 unsigned char fDiscontig
:1;
145 unsigned char fCompletionError
:1;
146 unsigned char _resv
:6;
148 // align arrays to 8 bytes so following macros work
149 unsigned char fPad
[3];
151 upl_page_info_t fPageList
[1]; /* variable length */
152 ioPLBlock fBlocks
[1]; /* variable length */
155 #define getDataP(osd) ((ioGMDData *) (osd)->getBytesNoCopy())
156 #define getIOPLList(d) ((ioPLBlock *) (void *)&(d->fPageList[d->fPageCnt]))
157 #define getNumIOPL(osd, d) \
158 (((osd)->getLength() - ((char *) getIOPLList(d) - (char *) d)) / sizeof(ioPLBlock))
159 #define getPageList(d) (&(d->fPageList[0]))
160 #define computeDataSize(p, u) \
161 (offsetof(ioGMDData, fPageList) + p * sizeof(upl_page_info_t) + u * sizeof(ioPLBlock))
163 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
165 #define next_page(a) ( trunc_page(a) + PAGE_SIZE )
169 kern_return_t
device_data_action(
170 uintptr_t device_handle
,
171 ipc_port_t device_pager
,
172 vm_prot_t protection
,
173 vm_object_offset_t offset
,
177 IOMemoryDescriptorReserved
* ref
= (IOMemoryDescriptorReserved
*) device_handle
;
178 IOMemoryDescriptor
* memDesc
;
181 memDesc
= ref
->dp
.memory
;
185 kr
= memDesc
->handleFault(device_pager
, offset
, size
);
195 kern_return_t
device_close(
196 uintptr_t device_handle
)
198 IOMemoryDescriptorReserved
* ref
= (IOMemoryDescriptorReserved
*) device_handle
;
200 IODelete( ref
, IOMemoryDescriptorReserved
, 1 );
202 return( kIOReturnSuccess
);
206 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
208 // Note this inline function uses C++ reference arguments to return values
209 // This means that pointers are not passed and NULLs don't have to be
210 // checked for as a NULL reference is illegal.
212 getAddrLenForInd(mach_vm_address_t
&addr
, mach_vm_size_t
&len
, // Output variables
213 UInt32 type
, IOGeneralMemoryDescriptor::Ranges r
, UInt32 ind
)
215 assert(kIOMemoryTypeUIO
== type
216 || kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
217 || kIOMemoryTypePhysical
== type
|| kIOMemoryTypePhysical64
== type
);
218 if (kIOMemoryTypeUIO
== type
) {
221 uio_getiov((uio_t
) r
.uio
, ind
, &ad
, &us
); addr
= ad
; len
= us
;
224 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
)) {
225 IOAddressRange cur
= r
.v64
[ind
];
229 #endif /* !__LP64__ */
231 IOVirtualRange cur
= r
.v
[ind
];
237 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
240 purgeableControlBits(IOOptionBits newState
, vm_purgable_t
* control
, int * state
)
242 IOReturn err
= kIOReturnSuccess
;
244 *control
= VM_PURGABLE_SET_STATE
;
246 enum { kIOMemoryPurgeableControlMask
= 15 };
248 switch (kIOMemoryPurgeableControlMask
& newState
)
250 case kIOMemoryPurgeableKeepCurrent
:
251 *control
= VM_PURGABLE_GET_STATE
;
254 case kIOMemoryPurgeableNonVolatile
:
255 *state
= VM_PURGABLE_NONVOLATILE
;
257 case kIOMemoryPurgeableVolatile
:
258 *state
= VM_PURGABLE_VOLATILE
| (newState
& ~kIOMemoryPurgeableControlMask
);
260 case kIOMemoryPurgeableEmpty
:
261 *state
= VM_PURGABLE_EMPTY
;
264 err
= kIOReturnBadArgument
;
271 purgeableStateBits(int * state
)
273 IOReturn err
= kIOReturnSuccess
;
275 switch (VM_PURGABLE_STATE_MASK
& *state
)
277 case VM_PURGABLE_NONVOLATILE
:
278 *state
= kIOMemoryPurgeableNonVolatile
;
280 case VM_PURGABLE_VOLATILE
:
281 *state
= kIOMemoryPurgeableVolatile
;
283 case VM_PURGABLE_EMPTY
:
284 *state
= kIOMemoryPurgeableEmpty
;
287 *state
= kIOMemoryPurgeableNonVolatile
;
288 err
= kIOReturnNotReady
;
296 vmProtForCacheMode(IOOptionBits cacheMode
)
301 case kIOInhibitCache
:
302 SET_MAP_MEM(MAP_MEM_IO
, prot
);
305 case kIOWriteThruCache
:
306 SET_MAP_MEM(MAP_MEM_WTHRU
, prot
);
309 case kIOWriteCombineCache
:
310 SET_MAP_MEM(MAP_MEM_WCOMB
, prot
);
313 case kIOCopybackCache
:
314 SET_MAP_MEM(MAP_MEM_COPYBACK
, prot
);
317 case kIOCopybackInnerCache
:
318 SET_MAP_MEM(MAP_MEM_INNERWBACK
, prot
);
321 case kIODefaultCache
:
323 SET_MAP_MEM(MAP_MEM_NOOP
, prot
);
331 pagerFlagsForCacheMode(IOOptionBits cacheMode
)
333 unsigned int pagerFlags
= 0;
336 case kIOInhibitCache
:
337 pagerFlags
= DEVICE_PAGER_CACHE_INHIB
| DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
340 case kIOWriteThruCache
:
341 pagerFlags
= DEVICE_PAGER_WRITE_THROUGH
| DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
344 case kIOWriteCombineCache
:
345 pagerFlags
= DEVICE_PAGER_CACHE_INHIB
| DEVICE_PAGER_COHERENT
;
348 case kIOCopybackCache
:
349 pagerFlags
= DEVICE_PAGER_COHERENT
;
352 case kIOCopybackInnerCache
:
353 pagerFlags
= DEVICE_PAGER_COHERENT
;
356 case kIODefaultCache
:
364 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
365 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
374 struct IOMemoryReference
376 volatile SInt32 refCount
;
380 IOMemoryEntry entries
[0];
385 kIOMemoryReferenceReuse
= 0x00000001,
386 kIOMemoryReferenceWrite
= 0x00000002,
389 SInt32 gIOMemoryReferenceCount
;
392 IOGeneralMemoryDescriptor::memoryReferenceAlloc(uint32_t capacity
, IOMemoryReference
* realloc
)
394 IOMemoryReference
* ref
;
395 size_t newSize
, oldSize
, copySize
;
397 newSize
= (sizeof(IOMemoryReference
)
398 - sizeof(ref
->entries
)
399 + capacity
* sizeof(ref
->entries
[0]));
400 ref
= (typeof(ref
)) IOMalloc(newSize
);
403 oldSize
= (sizeof(IOMemoryReference
)
404 - sizeof(realloc
->entries
)
405 + realloc
->capacity
* sizeof(realloc
->entries
[0]));
407 if (copySize
> newSize
) copySize
= newSize
;
408 if (ref
) bcopy(realloc
, ref
, copySize
);
409 IOFree(realloc
, oldSize
);
413 bzero(ref
, sizeof(*ref
));
415 OSIncrementAtomic(&gIOMemoryReferenceCount
);
417 if (!ref
) return (0);
418 ref
->capacity
= capacity
;
423 IOGeneralMemoryDescriptor::memoryReferenceFree(IOMemoryReference
* ref
)
425 IOMemoryEntry
* entries
;
428 entries
= ref
->entries
+ ref
->count
;
429 while (entries
> &ref
->entries
[0])
432 ipc_port_release_send(entries
->entry
);
434 size
= (sizeof(IOMemoryReference
)
435 - sizeof(ref
->entries
)
436 + ref
->capacity
* sizeof(ref
->entries
[0]));
439 OSDecrementAtomic(&gIOMemoryReferenceCount
);
443 IOGeneralMemoryDescriptor::memoryReferenceRelease(IOMemoryReference
* ref
)
445 if (1 == OSDecrementAtomic(&ref
->refCount
)) memoryReferenceFree(ref
);
450 IOGeneralMemoryDescriptor::memoryReferenceCreate(
451 IOOptionBits options
,
452 IOMemoryReference
** reference
)
454 enum { kCapacity
= 4, kCapacityInc
= 4 };
457 IOMemoryReference
* ref
;
458 IOMemoryEntry
* entries
;
459 IOMemoryEntry
* cloneEntries
;
461 ipc_port_t entry
, cloneEntry
;
463 memory_object_size_t actualSize
;
466 mach_vm_address_t entryAddr
, endAddr
, entrySize
;
467 mach_vm_size_t srcAddr
, srcLen
;
468 mach_vm_size_t nextAddr
, nextLen
;
469 mach_vm_size_t offset
, remain
;
471 IOOptionBits type
= (_flags
& kIOMemoryTypeMask
);
472 IOOptionBits cacheMode
;
473 unsigned int pagerFlags
;
476 ref
= memoryReferenceAlloc(kCapacity
, NULL
);
477 if (!ref
) return (kIOReturnNoMemory
);
479 tag
= IOMemoryTag(kernel_map
);
480 entries
= &ref
->entries
[0];
485 if (_task
) getAddrLenForInd(nextAddr
, nextLen
, type
, _ranges
, rangeIdx
);
488 nextAddr
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
491 // default cache mode for physical
492 if (kIODefaultCache
== ((_flags
& kIOMemoryBufferCacheMask
) >> kIOMemoryBufferCacheShift
))
495 pagerFlags
= IODefaultCacheBits(nextAddr
);
496 if (DEVICE_PAGER_CACHE_INHIB
& pagerFlags
)
498 if (DEVICE_PAGER_GUARDED
& pagerFlags
)
499 mode
= kIOInhibitCache
;
501 mode
= kIOWriteCombineCache
;
503 else if (DEVICE_PAGER_WRITE_THROUGH
& pagerFlags
)
504 mode
= kIOWriteThruCache
;
506 mode
= kIOCopybackCache
;
507 _flags
|= (mode
<< kIOMemoryBufferCacheShift
);
511 // cache mode & vm_prot
513 cacheMode
= ((_flags
& kIOMemoryBufferCacheMask
) >> kIOMemoryBufferCacheShift
);
514 prot
|= vmProtForCacheMode(cacheMode
);
515 // VM system requires write access to change cache mode
516 if (kIODefaultCache
!= cacheMode
) prot
|= VM_PROT_WRITE
;
517 if (kIODirectionOut
!= (kIODirectionOutIn
& _flags
)) prot
|= VM_PROT_WRITE
;
518 if (kIOMemoryReferenceWrite
& options
) prot
|= VM_PROT_WRITE
;
520 if ((kIOMemoryReferenceReuse
& options
) && _memRef
)
522 cloneEntries
= &_memRef
->entries
[0];
523 prot
|= MAP_MEM_NAMED_REUSE
;
530 if (kIOMemoryBufferPageable
& _flags
)
532 // IOBufferMemoryDescriptor alloc - set flags for entry + object create
533 prot
|= MAP_MEM_NAMED_CREATE
;
534 if (kIOMemoryBufferPurgeable
& _flags
) prot
|= MAP_MEM_PURGABLE
;
535 prot
|= VM_PROT_WRITE
;
538 else map
= get_task_map(_task
);
547 // coalesce addr range
548 for (++rangeIdx
; rangeIdx
< _rangesCount
; rangeIdx
++)
550 getAddrLenForInd(nextAddr
, nextLen
, type
, _ranges
, rangeIdx
);
551 if ((srcAddr
+ srcLen
) != nextAddr
) break;
554 entryAddr
= trunc_page_64(srcAddr
);
555 endAddr
= round_page_64(srcAddr
+ srcLen
);
558 entrySize
= (endAddr
- entryAddr
);
559 if (!entrySize
) break;
560 actualSize
= entrySize
;
562 cloneEntry
= MACH_PORT_NULL
;
563 if (MAP_MEM_NAMED_REUSE
& prot
)
565 if (cloneEntries
< &_memRef
->entries
[_memRef
->count
]) cloneEntry
= cloneEntries
->entry
;
566 else prot
&= ~MAP_MEM_NAMED_REUSE
;
569 err
= mach_make_memory_entry_64(map
,
570 &actualSize
, entryAddr
, prot
, &entry
, cloneEntry
);
572 if (KERN_SUCCESS
!= err
) break;
573 if (actualSize
> entrySize
) panic("mach_make_memory_entry_64 actualSize");
575 if (count
>= ref
->capacity
)
577 ref
= memoryReferenceAlloc(ref
->capacity
+ kCapacityInc
, ref
);
578 entries
= &ref
->entries
[count
];
580 entries
->entry
= entry
;
581 entries
->size
= actualSize
;
582 entries
->offset
= offset
+ (entryAddr
- srcAddr
);
583 entryAddr
+= actualSize
;
584 if (MAP_MEM_NAMED_REUSE
& prot
)
586 if ((cloneEntries
->entry
== entries
->entry
)
587 && (cloneEntries
->size
== entries
->size
)
588 && (cloneEntries
->offset
== entries
->offset
)) cloneEntries
++;
589 else prot
&= ~MAP_MEM_NAMED_REUSE
;
601 // _task == 0, physical or kIOMemoryTypeUPL
602 memory_object_t pager
;
603 vm_size_t size
= ptoa_32(_pages
);
605 if (!getKernelReserved()) panic("getKernelReserved");
607 reserved
->dp
.pagerContig
= (1 == _rangesCount
);
608 reserved
->dp
.memory
= this;
610 pagerFlags
= pagerFlagsForCacheMode(cacheMode
);
611 if (-1U == pagerFlags
) panic("phys is kIODefaultCache");
612 if (reserved
->dp
.pagerContig
) pagerFlags
|= DEVICE_PAGER_CONTIGUOUS
;
614 pager
= device_pager_setup((memory_object_t
) 0, (uintptr_t) reserved
,
617 if (!pager
) err
= kIOReturnVMError
;
621 entryAddr
= trunc_page_64(srcAddr
);
622 err
= mach_memory_object_memory_entry_64((host_t
) 1, false /*internal*/,
623 size
, VM_PROT_READ
| VM_PROT_WRITE
, pager
, &entry
);
624 assert (KERN_SUCCESS
== err
);
625 if (KERN_SUCCESS
!= err
) device_pager_deallocate(pager
);
628 reserved
->dp
.devicePager
= pager
;
629 entries
->entry
= entry
;
630 entries
->size
= size
;
631 entries
->offset
= offset
+ (entryAddr
- srcAddr
);
641 if (KERN_SUCCESS
== err
)
643 if (MAP_MEM_NAMED_REUSE
& prot
)
645 memoryReferenceFree(ref
);
646 OSIncrementAtomic(&_memRef
->refCount
);
652 memoryReferenceFree(ref
);
662 IOMemoryDescriptorMapAlloc(vm_map_t map
, void * _ref
)
664 IOMemoryDescriptorMapAllocRef
* ref
= (typeof(ref
))_ref
;
666 vm_map_offset_t addr
;
670 err
= vm_map_enter_mem_object(map
, &addr
, ref
->size
,
672 (((ref
->options
& kIOMapAnywhere
)
675 | VM_MAKE_TAG(ref
->tag
)
676 | VM_FLAGS_IOKIT_ACCT
), /* iokit accounting */
678 (memory_object_offset_t
) 0,
683 if (KERN_SUCCESS
== err
)
685 ref
->mapped
= (mach_vm_address_t
) addr
;
693 IOGeneralMemoryDescriptor::memoryReferenceMap(
694 IOMemoryReference
* ref
,
696 mach_vm_size_t inoffset
,
698 IOOptionBits options
,
699 mach_vm_address_t
* inaddr
)
702 int64_t offset
= inoffset
;
703 uint32_t rangeIdx
, entryIdx
;
704 vm_map_offset_t addr
, mapAddr
;
705 vm_map_offset_t pageOffset
, entryOffset
, remain
, chunk
;
707 mach_vm_address_t nextAddr
;
708 mach_vm_size_t nextLen
;
710 IOMemoryEntry
* entry
;
711 vm_prot_t prot
, memEntryCacheMode
;
713 IOOptionBits cacheMode
;
717 * For the kIOMapPrefault option.
719 upl_page_info_t
*pageList
= NULL
;
720 UInt currentPageIndex
= 0;
722 type
= _flags
& kIOMemoryTypeMask
;
724 if (!(kIOMapReadOnly
& options
)) prot
|= VM_PROT_WRITE
;
727 cacheMode
= ((options
& kIOMapCacheMask
) >> kIOMapCacheShift
);
728 if (kIODefaultCache
!= cacheMode
)
730 // VM system requires write access to update named entry cache mode
731 memEntryCacheMode
= (MAP_MEM_ONLY
| VM_PROT_WRITE
| prot
| vmProtForCacheMode(cacheMode
));
734 tag
= IOMemoryTag(map
);
738 // Find first range for offset
739 for (remain
= offset
, rangeIdx
= 0; rangeIdx
< _rangesCount
; rangeIdx
++)
741 getAddrLenForInd(nextAddr
, nextLen
, type
, _ranges
, rangeIdx
);
742 if (remain
< nextLen
) break;
750 nextAddr
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
754 assert(remain
< nextLen
);
755 if (remain
>= nextLen
) return (kIOReturnBadArgument
);
759 pageOffset
= (page_mask
& nextAddr
);
761 if (!(options
& kIOMapAnywhere
))
764 if (pageOffset
!= (page_mask
& addr
)) return (kIOReturnNotAligned
);
768 // find first entry for offset
770 (entryIdx
< ref
->count
) && (offset
>= ref
->entries
[entryIdx
].offset
);
773 entry
= &ref
->entries
[entryIdx
];
776 size
= round_page_64(size
+ pageOffset
);
777 if (kIOMapOverwrite
& options
)
779 if ((map
== kernel_map
) && (kIOMemoryBufferPageable
& _flags
))
781 map
= IOPageableMapForAddress(addr
);
787 IOMemoryDescriptorMapAllocRef ref
;
790 ref
.options
= options
;
793 if (options
& kIOMapAnywhere
)
794 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
798 if ((ref
.map
== kernel_map
) && (kIOMemoryBufferPageable
& _flags
))
799 err
= IOIteratePageableMaps( ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
801 err
= IOMemoryDescriptorMapAlloc(ref
.map
, &ref
);
802 if (KERN_SUCCESS
== err
)
810 * Prefaulting is only possible if we wired the memory earlier. Check the
811 * memory type, and the underlying data.
813 if (options
& kIOMapPrefault
)
816 * The memory must have been wired by calling ::prepare(), otherwise
817 * we don't have the UPL. Without UPLs, pages cannot be pre-faulted
819 assert(map
!= kernel_map
);
820 assert(_wireCount
!= 0);
821 assert(_memoryEntries
!= NULL
);
822 if ((map
== kernel_map
) ||
824 (_memoryEntries
== NULL
))
826 return kIOReturnBadArgument
;
829 // Get the page list.
830 ioGMDData
* dataP
= getDataP(_memoryEntries
);
831 ioPLBlock
const* ioplList
= getIOPLList(dataP
);
832 pageList
= getPageList(dataP
);
834 // Get the number of IOPLs.
835 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
838 * Scan through the IOPL Info Blocks, looking for the first block containing
839 * the offset. The research will go past it, so we'll need to go back to the
840 * right range at the end.
843 while (ioplIndex
< numIOPLs
&& offset
>= ioplList
[ioplIndex
].fIOMDOffset
)
847 // Retrieve the IOPL info block.
848 ioPLBlock ioplInfo
= ioplList
[ioplIndex
];
851 * For external UPLs, the fPageInfo points directly to the UPL's page_info_t
854 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
855 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
857 pageList
= &pageList
[ioplInfo
.fPageInfo
];
859 // Rebase [offset] into the IOPL in order to looks for the first page index.
860 mach_vm_size_t offsetInIOPL
= offset
- ioplInfo
.fIOMDOffset
+ ioplInfo
.fPageOffset
;
862 // Retrieve the index of the first page corresponding to the offset.
863 currentPageIndex
= atop_32(offsetInIOPL
);
871 while (remain
&& (KERN_SUCCESS
== err
))
873 entryOffset
= offset
- entry
->offset
;
874 if ((page_mask
& entryOffset
) != pageOffset
)
876 err
= kIOReturnNotAligned
;
880 if (kIODefaultCache
!= cacheMode
)
882 vm_size_t unused
= 0;
883 err
= mach_make_memory_entry(NULL
/*unused*/, &unused
, 0 /*unused*/,
884 memEntryCacheMode
, NULL
, entry
->entry
);
885 assert (KERN_SUCCESS
== err
);
888 entryOffset
-= pageOffset
;
889 if (entryOffset
>= entry
->size
) panic("entryOffset");
890 chunk
= entry
->size
- entryOffset
;
893 if (chunk
> remain
) chunk
= remain
;
894 if (options
& kIOMapPrefault
)
896 UInt nb_pages
= round_page(chunk
) / PAGE_SIZE
;
897 err
= vm_map_enter_mem_object_prefault(map
,
903 | VM_FLAGS_IOKIT_ACCT
), /* iokit accounting */
908 &pageList
[currentPageIndex
],
911 // Compute the next index in the page list.
912 currentPageIndex
+= nb_pages
;
913 assert(currentPageIndex
<= _pages
);
917 err
= vm_map_enter_mem_object(map
,
923 | VM_FLAGS_IOKIT_ACCT
), /* iokit accounting */
931 if (KERN_SUCCESS
!= err
) break;
935 offset
+= chunk
- pageOffset
;
940 if (entryIdx
>= ref
->count
)
942 err
= kIOReturnOverrun
;
947 if ((KERN_SUCCESS
!= err
) && addr
&& !(kIOMapOverwrite
& options
))
949 (void) mach_vm_deallocate(map
, trunc_page_64(addr
), size
);
958 IOGeneralMemoryDescriptor::memoryReferenceGetPageCounts(
959 IOMemoryReference
* ref
,
960 IOByteCount
* residentPageCount
,
961 IOByteCount
* dirtyPageCount
)
964 IOMemoryEntry
* entries
;
965 unsigned int resident
, dirty
;
966 unsigned int totalResident
, totalDirty
;
968 totalResident
= totalDirty
= 0;
969 entries
= ref
->entries
+ ref
->count
;
970 while (entries
> &ref
->entries
[0])
973 err
= mach_memory_entry_get_page_counts(entries
->entry
, &resident
, &dirty
);
974 if (KERN_SUCCESS
!= err
) break;
975 totalResident
+= resident
;
979 if (residentPageCount
) *residentPageCount
= totalResident
;
980 if (dirtyPageCount
) *dirtyPageCount
= totalDirty
;
985 IOGeneralMemoryDescriptor::memoryReferenceSetPurgeable(
986 IOMemoryReference
* ref
,
987 IOOptionBits newState
,
988 IOOptionBits
* oldState
)
991 IOMemoryEntry
* entries
;
992 vm_purgable_t control
;
993 int totalState
, state
;
995 entries
= ref
->entries
+ ref
->count
;
996 totalState
= kIOMemoryPurgeableNonVolatile
;
997 while (entries
> &ref
->entries
[0])
1001 err
= purgeableControlBits(newState
, &control
, &state
);
1002 if (KERN_SUCCESS
!= err
) break;
1003 err
= mach_memory_entry_purgable_control(entries
->entry
, control
, &state
);
1004 if (KERN_SUCCESS
!= err
) break;
1005 err
= purgeableStateBits(&state
);
1006 if (KERN_SUCCESS
!= err
) break;
1008 if (kIOMemoryPurgeableEmpty
== state
) totalState
= kIOMemoryPurgeableEmpty
;
1009 else if (kIOMemoryPurgeableEmpty
== totalState
) continue;
1010 else if (kIOMemoryPurgeableVolatile
== totalState
) continue;
1011 else if (kIOMemoryPurgeableVolatile
== state
) totalState
= kIOMemoryPurgeableVolatile
;
1012 else totalState
= kIOMemoryPurgeableNonVolatile
;
1015 if (oldState
) *oldState
= totalState
;
1019 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1021 IOMemoryDescriptor
*
1022 IOMemoryDescriptor::withAddress(void * address
,
1024 IODirection direction
)
1026 return IOMemoryDescriptor::
1027 withAddressRange((IOVirtualAddress
) address
, length
, direction
| kIOMemoryAutoPrepare
, kernel_task
);
1031 IOMemoryDescriptor
*
1032 IOMemoryDescriptor::withAddress(IOVirtualAddress address
,
1034 IODirection direction
,
1037 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1040 if (that
->initWithAddress(address
, length
, direction
, task
))
1047 #endif /* !__LP64__ */
1049 IOMemoryDescriptor
*
1050 IOMemoryDescriptor::withPhysicalAddress(
1051 IOPhysicalAddress address
,
1053 IODirection direction
)
1055 return (IOMemoryDescriptor::withAddressRange(address
, length
, direction
, TASK_NULL
));
1059 IOMemoryDescriptor
*
1060 IOMemoryDescriptor::withRanges( IOVirtualRange
* ranges
,
1062 IODirection direction
,
1066 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1069 if (that
->initWithRanges(ranges
, withCount
, direction
, task
, asReference
))
1076 #endif /* !__LP64__ */
1078 IOMemoryDescriptor
*
1079 IOMemoryDescriptor::withAddressRange(mach_vm_address_t address
,
1080 mach_vm_size_t length
,
1081 IOOptionBits options
,
1084 IOAddressRange range
= { address
, length
};
1085 return (IOMemoryDescriptor::withAddressRanges(&range
, 1, options
, task
));
1088 IOMemoryDescriptor
*
1089 IOMemoryDescriptor::withAddressRanges(IOAddressRange
* ranges
,
1091 IOOptionBits options
,
1094 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1098 options
|= kIOMemoryTypeVirtual64
;
1100 options
|= kIOMemoryTypePhysical64
;
1102 if (that
->initWithOptions(ranges
, rangeCount
, 0, task
, options
, /* mapper */ 0))
1115 * Create a new IOMemoryDescriptor. The buffer is made up of several
1116 * virtual address ranges, from a given task.
1118 * Passing the ranges as a reference will avoid an extra allocation.
1120 IOMemoryDescriptor
*
1121 IOMemoryDescriptor::withOptions(void * buffers
,
1128 IOGeneralMemoryDescriptor
*self
= new IOGeneralMemoryDescriptor
;
1131 && !self
->initWithOptions(buffers
, count
, offset
, task
, opts
, mapper
))
1140 bool IOMemoryDescriptor::initWithOptions(void * buffers
,
1144 IOOptionBits options
,
1151 IOMemoryDescriptor
*
1152 IOMemoryDescriptor::withPhysicalRanges( IOPhysicalRange
* ranges
,
1154 IODirection direction
,
1157 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1160 if (that
->initWithPhysicalRanges(ranges
, withCount
, direction
, asReference
))
1168 IOMemoryDescriptor
*
1169 IOMemoryDescriptor::withSubRange(IOMemoryDescriptor
* of
,
1172 IODirection direction
)
1174 return (IOSubMemoryDescriptor::withSubRange(of
, offset
, length
, direction
));
1176 #endif /* !__LP64__ */
1178 IOMemoryDescriptor
*
1179 IOMemoryDescriptor::withPersistentMemoryDescriptor(IOMemoryDescriptor
*originalMD
)
1181 IOGeneralMemoryDescriptor
*origGenMD
=
1182 OSDynamicCast(IOGeneralMemoryDescriptor
, originalMD
);
1185 return IOGeneralMemoryDescriptor::
1186 withPersistentMemoryDescriptor(origGenMD
);
1191 IOMemoryDescriptor
*
1192 IOGeneralMemoryDescriptor::withPersistentMemoryDescriptor(IOGeneralMemoryDescriptor
*originalMD
)
1194 IOMemoryReference
* memRef
;
1196 if (kIOReturnSuccess
!= originalMD
->memoryReferenceCreate(kIOMemoryReferenceReuse
, &memRef
)) return (0);
1198 if (memRef
== originalMD
->_memRef
)
1200 originalMD
->retain(); // Add a new reference to ourselves
1201 originalMD
->memoryReferenceRelease(memRef
);
1205 IOGeneralMemoryDescriptor
* self
= new IOGeneralMemoryDescriptor
;
1206 IOMDPersistentInitData initData
= { originalMD
, memRef
};
1209 && !self
->initWithOptions(&initData
, 1, 0, 0, kIOMemoryTypePersistentMD
, 0)) {
1218 IOGeneralMemoryDescriptor::initWithAddress(void * address
,
1219 IOByteCount withLength
,
1220 IODirection withDirection
)
1222 _singleRange
.v
.address
= (vm_offset_t
) address
;
1223 _singleRange
.v
.length
= withLength
;
1225 return initWithRanges(&_singleRange
.v
, 1, withDirection
, kernel_task
, true);
1229 IOGeneralMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
1230 IOByteCount withLength
,
1231 IODirection withDirection
,
1234 _singleRange
.v
.address
= address
;
1235 _singleRange
.v
.length
= withLength
;
1237 return initWithRanges(&_singleRange
.v
, 1, withDirection
, withTask
, true);
1241 IOGeneralMemoryDescriptor::initWithPhysicalAddress(
1242 IOPhysicalAddress address
,
1243 IOByteCount withLength
,
1244 IODirection withDirection
)
1246 _singleRange
.p
.address
= address
;
1247 _singleRange
.p
.length
= withLength
;
1249 return initWithPhysicalRanges( &_singleRange
.p
, 1, withDirection
, true);
1253 IOGeneralMemoryDescriptor::initWithPhysicalRanges(
1254 IOPhysicalRange
* ranges
,
1256 IODirection direction
,
1259 IOOptionBits mdOpts
= direction
| kIOMemoryTypePhysical
;
1262 mdOpts
|= kIOMemoryAsReference
;
1264 return initWithOptions(ranges
, count
, 0, 0, mdOpts
, /* mapper */ 0);
1268 IOGeneralMemoryDescriptor::initWithRanges(
1269 IOVirtualRange
* ranges
,
1271 IODirection direction
,
1275 IOOptionBits mdOpts
= direction
;
1278 mdOpts
|= kIOMemoryAsReference
;
1281 mdOpts
|= kIOMemoryTypeVirtual
;
1283 // Auto-prepare if this is a kernel memory descriptor as very few
1284 // clients bother to prepare() kernel memory.
1285 // But it was not enforced so what are you going to do?
1286 if (task
== kernel_task
)
1287 mdOpts
|= kIOMemoryAutoPrepare
;
1290 mdOpts
|= kIOMemoryTypePhysical
;
1292 return initWithOptions(ranges
, count
, 0, task
, mdOpts
, /* mapper */ 0);
1294 #endif /* !__LP64__ */
1299 * IOMemoryDescriptor. The buffer is made up of several virtual address ranges,
1300 * from a given task, several physical ranges, an UPL from the ubc
1301 * system or a uio (may be 64bit) from the BSD subsystem.
1303 * Passing the ranges as a reference will avoid an extra allocation.
1305 * An IOMemoryDescriptor can be re-used by calling initWithOptions again on an
1306 * existing instance -- note this behavior is not commonly supported in other
1307 * I/O Kit classes, although it is supported here.
1311 IOGeneralMemoryDescriptor::initWithOptions(void * buffers
,
1315 IOOptionBits options
,
1318 IOOptionBits type
= options
& kIOMemoryTypeMask
;
1322 && (kIOMemoryTypeVirtual
== type
)
1323 && vm_map_is_64bit(get_task_map(task
))
1324 && ((IOVirtualRange
*) buffers
)->address
)
1326 OSReportWithBacktrace("IOMemoryDescriptor: attempt to create 32b virtual in 64b task, use ::withAddressRange()");
1329 #endif /* !__LP64__ */
1331 // Grab the original MD's configuation data to initialse the
1332 // arguments to this function.
1333 if (kIOMemoryTypePersistentMD
== type
) {
1335 IOMDPersistentInitData
*initData
= (typeof(initData
)) buffers
;
1336 const IOGeneralMemoryDescriptor
*orig
= initData
->fMD
;
1337 ioGMDData
*dataP
= getDataP(orig
->_memoryEntries
);
1339 // Only accept persistent memory descriptors with valid dataP data.
1340 assert(orig
->_rangesCount
== 1);
1341 if ( !(orig
->_flags
& kIOMemoryPersistent
) || !dataP
)
1344 _memRef
= initData
->fMemRef
; // Grab the new named entry
1345 options
= orig
->_flags
& ~kIOMemoryAsReference
;
1346 type
= options
& kIOMemoryTypeMask
;
1347 buffers
= orig
->_ranges
.v
;
1348 count
= orig
->_rangesCount
;
1350 // Now grab the original task and whatever mapper was previously used
1352 mapper
= dataP
->fMapper
;
1354 // We are ready to go through the original initialisation now
1358 case kIOMemoryTypeUIO
:
1359 case kIOMemoryTypeVirtual
:
1361 case kIOMemoryTypeVirtual64
:
1362 #endif /* !__LP64__ */
1368 case kIOMemoryTypePhysical
: // Neither Physical nor UPL should have a task
1370 case kIOMemoryTypePhysical64
:
1371 #endif /* !__LP64__ */
1372 case kIOMemoryTypeUPL
:
1376 return false; /* bad argument */
1383 * We can check the _initialized instance variable before having ever set
1384 * it to an initial value because I/O Kit guarantees that all our instance
1385 * variables are zeroed on an object's allocation.
1390 * An existing memory descriptor is being retargeted to point to
1391 * somewhere else. Clean up our present state.
1393 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1394 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
1399 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
1401 if (kIOMemoryTypeUIO
== type
)
1402 uio_free((uio_t
) _ranges
.v
);
1404 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
1405 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
1406 #endif /* !__LP64__ */
1408 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
1411 options
|= (kIOMemoryRedirected
& _flags
);
1412 if (!(kIOMemoryRedirected
& options
))
1416 memoryReferenceRelease(_memRef
);
1420 _mappings
->flushCollection();
1426 _initialized
= true;
1429 // Grab the appropriate mapper
1430 if (kIOMemoryHostOnly
& options
) options
|= kIOMemoryMapperNone
;
1431 if (kIOMemoryMapperNone
& options
)
1432 mapper
= 0; // No Mapper
1433 else if (mapper
== kIOMapperSystem
) {
1434 IOMapper::checkForSystemMapper();
1435 gIOSystemMapper
= mapper
= IOMapper::gSystem
;
1438 // Temp binary compatibility for kIOMemoryThreadSafe
1439 if (kIOMemoryReserved6156215
& options
)
1441 options
&= ~kIOMemoryReserved6156215
;
1442 options
|= kIOMemoryThreadSafe
;
1444 // Remove the dynamic internal use flags from the initial setting
1445 options
&= ~(kIOMemoryPreparedReadOnly
);
1450 _direction
= (IODirection
) (_flags
& kIOMemoryDirectionMask
);
1451 #endif /* !__LP64__ */
1453 __iomd_reservedA
= 0;
1454 __iomd_reservedB
= 0;
1457 if (kIOMemoryThreadSafe
& options
)
1460 _prepareLock
= IOLockAlloc();
1462 else if (_prepareLock
)
1464 IOLockFree(_prepareLock
);
1465 _prepareLock
= NULL
;
1468 if (kIOMemoryTypeUPL
== type
) {
1471 unsigned int dataSize
= computeDataSize(/* pages */ 0, /* upls */ 1);
1473 if (!initMemoryEntries(dataSize
, mapper
)) return (false);
1474 dataP
= getDataP(_memoryEntries
);
1475 dataP
->fPageCnt
= 0;
1477 // _wireCount++; // UPLs start out life wired
1480 _pages
+= atop_32(offset
+ count
+ PAGE_MASK
) - atop_32(offset
);
1483 iopl
.fIOPL
= (upl_t
) buffers
;
1484 upl_set_referenced(iopl
.fIOPL
, true);
1485 upl_page_info_t
*pageList
= UPL_GET_INTERNAL_PAGE_LIST(iopl
.fIOPL
);
1487 if (upl_get_size(iopl
.fIOPL
) < (count
+ offset
))
1488 panic("short external upl");
1490 _highestPage
= upl_get_highest_page(iopl
.fIOPL
);
1492 // Set the flag kIOPLOnDevice convieniently equal to 1
1493 iopl
.fFlags
= pageList
->device
| kIOPLExternUPL
;
1494 if (!pageList
->device
) {
1495 // Pre-compute the offset into the UPL's page list
1496 pageList
= &pageList
[atop_32(offset
)];
1497 offset
&= PAGE_MASK
;
1499 iopl
.fIOMDOffset
= 0;
1500 iopl
.fMappedPage
= 0;
1501 iopl
.fPageInfo
= (vm_address_t
) pageList
;
1502 iopl
.fPageOffset
= offset
;
1503 _memoryEntries
->appendBytes(&iopl
, sizeof(iopl
));
1506 // kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO
1507 // kIOMemoryTypePhysical | kIOMemoryTypePhysical64
1509 // Initialize the memory descriptor
1510 if (options
& kIOMemoryAsReference
) {
1512 _rangesIsAllocated
= false;
1513 #endif /* !__LP64__ */
1515 // Hack assignment to get the buffer arg into _ranges.
1516 // I'd prefer to do _ranges = (Ranges) buffers, but that doesn't
1518 // This also initialises the uio & physical ranges.
1519 _ranges
.v
= (IOVirtualRange
*) buffers
;
1523 _rangesIsAllocated
= true;
1524 #endif /* !__LP64__ */
1527 case kIOMemoryTypeUIO
:
1528 _ranges
.v
= (IOVirtualRange
*) uio_duplicate((uio_t
) buffers
);
1532 case kIOMemoryTypeVirtual64
:
1533 case kIOMemoryTypePhysical64
:
1535 && (((IOAddressRange
*) buffers
)->address
+ ((IOAddressRange
*) buffers
)->length
) <= 0x100000000ULL
1537 if (kIOMemoryTypeVirtual64
== type
)
1538 type
= kIOMemoryTypeVirtual
;
1540 type
= kIOMemoryTypePhysical
;
1541 _flags
= (_flags
& ~kIOMemoryTypeMask
) | type
| kIOMemoryAsReference
;
1542 _rangesIsAllocated
= false;
1543 _ranges
.v
= &_singleRange
.v
;
1544 _singleRange
.v
.address
= ((IOAddressRange
*) buffers
)->address
;
1545 _singleRange
.v
.length
= ((IOAddressRange
*) buffers
)->length
;
1548 _ranges
.v64
= IONew(IOAddressRange
, count
);
1551 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOAddressRange
));
1553 #endif /* !__LP64__ */
1554 case kIOMemoryTypeVirtual
:
1555 case kIOMemoryTypePhysical
:
1557 _flags
|= kIOMemoryAsReference
;
1559 _rangesIsAllocated
= false;
1560 #endif /* !__LP64__ */
1561 _ranges
.v
= &_singleRange
.v
;
1563 _ranges
.v
= IONew(IOVirtualRange
, count
);
1567 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOVirtualRange
));
1572 // Find starting address within the vector of ranges
1573 Ranges vec
= _ranges
;
1574 mach_vm_size_t totalLength
= 0;
1575 unsigned int ind
, pages
= 0;
1576 for (ind
= 0; ind
< count
; ind
++) {
1577 mach_vm_address_t addr
;
1580 // addr & len are returned by this function
1581 getAddrLenForInd(addr
, len
, type
, vec
, ind
);
1582 if ((addr
+ len
+ PAGE_MASK
) < addr
) break; /* overflow */
1583 pages
+= (atop_64(addr
+ len
+ PAGE_MASK
) - atop_64(addr
));
1585 if (totalLength
< len
) break; /* overflow */
1586 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
1588 ppnum_t highPage
= atop_64(addr
+ len
- 1);
1589 if (highPage
> _highestPage
)
1590 _highestPage
= highPage
;
1594 || (totalLength
!= ((IOByteCount
) totalLength
))) return (false); /* overflow */
1596 _length
= totalLength
;
1598 _rangesCount
= count
;
1600 // Auto-prepare memory at creation time.
1601 // Implied completion when descriptor is free-ed
1602 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
1603 _wireCount
++; // Physical MDs are, by definition, wired
1604 else { /* kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO */
1606 mach_vm_size_t dataSize
= computeDataSize(_pages
, /* upls */ count
* 2);
1607 if (dataSize
!= ((unsigned) dataSize
)) return false; /* overflow */
1609 if (!initMemoryEntries(dataSize
, mapper
)) return false;
1610 dataP
= getDataP(_memoryEntries
);
1611 dataP
->fPageCnt
= _pages
;
1613 if ( (kIOMemoryPersistent
& _flags
) && !_memRef
)
1616 err
= memoryReferenceCreate(0, &_memRef
);
1617 if (kIOReturnSuccess
!= err
) return false;
1620 if ((_flags
& kIOMemoryAutoPrepare
)
1621 && prepare() != kIOReturnSuccess
)
1634 void IOGeneralMemoryDescriptor::free()
1636 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1641 reserved
->dp
.memory
= 0;
1644 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
1647 if (_memoryEntries
&& (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
1649 dataP
->fMapper
->iovmUnmapMemory(this, NULL
, dataP
->fMappedBase
, dataP
->fMappedLength
);
1650 dataP
->fMappedBase
= 0;
1655 while (_wireCount
) complete();
1658 if (_memoryEntries
) _memoryEntries
->release();
1660 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
1662 if (kIOMemoryTypeUIO
== type
)
1663 uio_free((uio_t
) _ranges
.v
);
1665 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
1666 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
1667 #endif /* !__LP64__ */
1669 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
1676 if (reserved
->dp
.devicePager
)
1678 // memEntry holds a ref on the device pager which owns reserved
1679 // (IOMemoryDescriptorReserved) so no reserved access after this point
1680 device_pager_deallocate( (memory_object_t
) reserved
->dp
.devicePager
);
1683 IODelete(reserved
, IOMemoryDescriptorReserved
, 1);
1687 if (_memRef
) memoryReferenceRelease(_memRef
);
1688 if (_prepareLock
) IOLockFree(_prepareLock
);
1694 void IOGeneralMemoryDescriptor::unmapFromKernel()
1696 panic("IOGMD::unmapFromKernel deprecated");
1699 void IOGeneralMemoryDescriptor::mapIntoKernel(unsigned rangeIndex
)
1701 panic("IOGMD::mapIntoKernel deprecated");
1703 #endif /* !__LP64__ */
1708 * Get the direction of the transfer.
1710 IODirection
IOMemoryDescriptor::getDirection() const
1715 #endif /* !__LP64__ */
1716 return (IODirection
) (_flags
& kIOMemoryDirectionMask
);
1722 * Get the length of the transfer (over all ranges).
1724 IOByteCount
IOMemoryDescriptor::getLength() const
1729 void IOMemoryDescriptor::setTag( IOOptionBits tag
)
1734 IOOptionBits
IOMemoryDescriptor::getTag( void )
1740 // @@@ gvdl: who is using this API? Seems like a wierd thing to implement.
1742 IOMemoryDescriptor::getSourceSegment( IOByteCount offset
, IOByteCount
* length
)
1744 addr64_t physAddr
= 0;
1746 if( prepare() == kIOReturnSuccess
) {
1747 physAddr
= getPhysicalSegment64( offset
, length
);
1751 return( (IOPhysicalAddress
) physAddr
); // truncated but only page offset is used
1753 #endif /* !__LP64__ */
1755 IOByteCount
IOMemoryDescriptor::readBytes
1756 (IOByteCount offset
, void *bytes
, IOByteCount length
)
1758 addr64_t dstAddr
= CAST_DOWN(addr64_t
, bytes
);
1759 IOByteCount remaining
;
1761 // Assert that this entire I/O is withing the available range
1762 assert(offset
<= _length
);
1763 assert(offset
+ length
<= _length
);
1764 if ((offset
>= _length
)
1765 || ((offset
+ length
) > _length
)) {
1769 if (kIOMemoryThreadSafe
& _flags
)
1772 remaining
= length
= min(length
, _length
- offset
);
1773 while (remaining
) { // (process another target segment?)
1777 srcAddr64
= getPhysicalSegment(offset
, &srcLen
, kIOMemoryMapperNone
);
1781 // Clip segment length to remaining
1782 if (srcLen
> remaining
)
1785 copypv(srcAddr64
, dstAddr
, srcLen
,
1786 cppvPsrc
| cppvNoRefSrc
| cppvFsnk
| cppvKmap
);
1790 remaining
-= srcLen
;
1793 if (kIOMemoryThreadSafe
& _flags
)
1798 return length
- remaining
;
1801 IOByteCount
IOMemoryDescriptor::writeBytes
1802 (IOByteCount inoffset
, const void *bytes
, IOByteCount length
)
1804 addr64_t srcAddr
= CAST_DOWN(addr64_t
, bytes
);
1805 IOByteCount remaining
;
1806 IOByteCount offset
= inoffset
;
1808 // Assert that this entire I/O is withing the available range
1809 assert(offset
<= _length
);
1810 assert(offset
+ length
<= _length
);
1812 assert( !(kIOMemoryPreparedReadOnly
& _flags
) );
1814 if ( (kIOMemoryPreparedReadOnly
& _flags
)
1815 || (offset
>= _length
)
1816 || ((offset
+ length
) > _length
)) {
1820 if (kIOMemoryThreadSafe
& _flags
)
1823 remaining
= length
= min(length
, _length
- offset
);
1824 while (remaining
) { // (process another target segment?)
1828 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1832 // Clip segment length to remaining
1833 if (dstLen
> remaining
)
1836 if (!srcAddr
) bzero_phys(dstAddr64
, dstLen
);
1839 copypv(srcAddr
, (addr64_t
) dstAddr64
, dstLen
,
1840 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
1844 remaining
-= dstLen
;
1847 if (kIOMemoryThreadSafe
& _flags
)
1852 if (!srcAddr
) performOperation(kIOMemoryIncoherentIOFlush
, inoffset
, length
);
1854 return length
- remaining
;
1858 void IOGeneralMemoryDescriptor::setPosition(IOByteCount position
)
1860 panic("IOGMD::setPosition deprecated");
1862 #endif /* !__LP64__ */
1864 static volatile SInt64 gIOMDPreparationID
__attribute__((aligned(8))) = (1ULL << 32);
1867 IOGeneralMemoryDescriptor::getPreparationID( void )
1872 return (kIOPreparationIDUnprepared
);
1874 if (((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical
)
1875 || ((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical64
))
1877 IOMemoryDescriptor::setPreparationID();
1878 return (IOMemoryDescriptor::getPreparationID());
1881 if (!_memoryEntries
|| !(dataP
= getDataP(_memoryEntries
)))
1882 return (kIOPreparationIDUnprepared
);
1884 if (kIOPreparationIDUnprepared
== dataP
->fPreparationID
)
1886 dataP
->fPreparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1888 return (dataP
->fPreparationID
);
1891 IOMemoryDescriptorReserved
* IOMemoryDescriptor::getKernelReserved( void )
1895 reserved
= IONew(IOMemoryDescriptorReserved
, 1);
1897 bzero(reserved
, sizeof(IOMemoryDescriptorReserved
));
1902 void IOMemoryDescriptor::setPreparationID( void )
1904 if (getKernelReserved() && (kIOPreparationIDUnprepared
== reserved
->preparationID
))
1906 #if defined(__ppc__ )
1907 reserved
->preparationID
= gIOMDPreparationID
++;
1909 reserved
->preparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1914 uint64_t IOMemoryDescriptor::getPreparationID( void )
1917 return (reserved
->preparationID
);
1919 return (kIOPreparationIDUnsupported
);
1922 IOReturn
IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1924 IOReturn err
= kIOReturnSuccess
;
1925 DMACommandOps params
;
1926 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
1929 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
1930 op
&= kIOMDDMACommandOperationMask
;
1932 if (kIOMDDMAMap
== op
)
1934 if (dataSize
< sizeof(IOMDDMAMapArgs
))
1935 return kIOReturnUnderrun
;
1937 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
1940 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1942 if (_memoryEntries
&& data
->fMapper
)
1944 bool remap
, keepMap
;
1945 dataP
= getDataP(_memoryEntries
);
1947 if (data
->fMapSpec
.numAddressBits
< dataP
->fDMAMapNumAddressBits
) dataP
->fDMAMapNumAddressBits
= data
->fMapSpec
.numAddressBits
;
1948 if (data
->fMapSpec
.alignment
> dataP
->fDMAMapAlignment
) dataP
->fDMAMapAlignment
= data
->fMapSpec
.alignment
;
1950 keepMap
= (data
->fMapper
== gIOSystemMapper
);
1951 keepMap
&= ((data
->fOffset
== 0) && (data
->fLength
== _length
));
1954 remap
|= (dataP
->fDMAMapNumAddressBits
< 64)
1955 && ((dataP
->fMappedBase
+ _length
) > (1ULL << dataP
->fDMAMapNumAddressBits
));
1956 remap
|= (dataP
->fDMAMapAlignment
> page_size
);
1958 if (remap
|| !dataP
->fMappedBase
)
1960 // if (dataP->fMappedBase) OSReportWithBacktrace("kIOMDDMAMap whole %d remap %d params %d\n", whole, remap, params);
1961 err
= md
->dmaMap(data
->fMapper
, data
->fCommand
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocLength
);
1962 if (keepMap
&& (kIOReturnSuccess
== err
) && !dataP
->fMappedBase
)
1964 dataP
->fMappedBase
= data
->fAlloc
;
1965 dataP
->fMappedLength
= data
->fAllocLength
;
1966 data
->fAllocLength
= 0; // IOMD owns the alloc now
1971 data
->fAlloc
= dataP
->fMappedBase
;
1972 data
->fAllocLength
= 0; // give out IOMD map
1974 data
->fMapContig
= !dataP
->fDiscontig
;
1980 if (kIOMDAddDMAMapSpec
== op
)
1982 if (dataSize
< sizeof(IODMAMapSpecification
))
1983 return kIOReturnUnderrun
;
1985 IODMAMapSpecification
* data
= (IODMAMapSpecification
*) vData
;
1988 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1992 dataP
= getDataP(_memoryEntries
);
1993 if (data
->numAddressBits
< dataP
->fDMAMapNumAddressBits
)
1994 dataP
->fDMAMapNumAddressBits
= data
->numAddressBits
;
1995 if (data
->alignment
> dataP
->fDMAMapAlignment
)
1996 dataP
->fDMAMapAlignment
= data
->alignment
;
1998 return kIOReturnSuccess
;
2001 if (kIOMDGetCharacteristics
== op
) {
2003 if (dataSize
< sizeof(IOMDDMACharacteristics
))
2004 return kIOReturnUnderrun
;
2006 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
2007 data
->fLength
= _length
;
2008 data
->fSGCount
= _rangesCount
;
2009 data
->fPages
= _pages
;
2010 data
->fDirection
= getDirection();
2012 data
->fIsPrepared
= false;
2014 data
->fIsPrepared
= true;
2015 data
->fHighestPage
= _highestPage
;
2018 dataP
= getDataP(_memoryEntries
);
2019 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2020 UInt count
= getNumIOPL(_memoryEntries
, dataP
);
2022 data
->fPageAlign
= (ioplList
[0].fPageOffset
& PAGE_MASK
) | ~PAGE_MASK
;
2026 return kIOReturnSuccess
;
2028 #if IOMD_DEBUG_DMAACTIVE
2029 } else if (kIOMDDMAActive
== op
) {
2030 if (params
) OSIncrementAtomic(&md
->__iomd_reservedA
);
2032 if (md
->__iomd_reservedA
)
2033 OSDecrementAtomic(&md
->__iomd_reservedA
);
2035 panic("kIOMDSetDMAInactive");
2037 #endif /* IOMD_DEBUG_DMAACTIVE */
2039 } else if (kIOMDWalkSegments
!= op
)
2040 return kIOReturnBadArgument
;
2042 // Get the next segment
2043 struct InternalState
{
2044 IOMDDMAWalkSegmentArgs fIO
;
2050 // Find the next segment
2051 if (dataSize
< sizeof(*isP
))
2052 return kIOReturnUnderrun
;
2054 isP
= (InternalState
*) vData
;
2055 UInt offset
= isP
->fIO
.fOffset
;
2056 bool mapped
= isP
->fIO
.fMapped
;
2058 if (IOMapper::gSystem
&& mapped
2059 && (!(kIOMemoryHostOnly
& _flags
))
2060 && (!_memoryEntries
|| !getDataP(_memoryEntries
)->fMappedBase
))
2061 // && (_memoryEntries && !getDataP(_memoryEntries)->fMappedBase))
2064 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
2066 dataP
= getDataP(_memoryEntries
);
2069 IODMAMapSpecification mapSpec
;
2070 bzero(&mapSpec
, sizeof(mapSpec
));
2071 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
2072 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
2073 err
= md
->dmaMap(dataP
->fMapper
, NULL
, &mapSpec
, 0, _length
, &dataP
->fMappedBase
, &dataP
->fMappedLength
);
2074 if (kIOReturnSuccess
!= err
) return (err
);
2078 if (offset
>= _length
)
2079 return (offset
== _length
)? kIOReturnOverrun
: kIOReturnInternalError
;
2081 // Validate the previous offset
2082 UInt ind
, off2Ind
= isP
->fOffset2Index
;
2085 && (offset
== isP
->fNextOffset
|| off2Ind
<= offset
))
2088 ind
= off2Ind
= 0; // Start from beginning
2094 if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
) {
2096 // Physical address based memory descriptor
2097 const IOPhysicalRange
*physP
= (IOPhysicalRange
*) &_ranges
.p
[0];
2099 // Find the range after the one that contains the offset
2101 for (len
= 0; off2Ind
<= offset
; ind
++) {
2102 len
= physP
[ind
].length
;
2106 // Calculate length within range and starting address
2107 length
= off2Ind
- offset
;
2108 address
= physP
[ind
- 1].address
+ len
- length
;
2110 if (true && mapped
&& _memoryEntries
2111 && (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
2113 address
= dataP
->fMappedBase
+ offset
;
2117 // see how far we can coalesce ranges
2118 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
2119 len
= physP
[ind
].length
;
2126 // correct contiguous check overshoot
2131 else if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
) {
2133 // Physical address based memory descriptor
2134 const IOAddressRange
*physP
= (IOAddressRange
*) &_ranges
.v64
[0];
2136 // Find the range after the one that contains the offset
2138 for (len
= 0; off2Ind
<= offset
; ind
++) {
2139 len
= physP
[ind
].length
;
2143 // Calculate length within range and starting address
2144 length
= off2Ind
- offset
;
2145 address
= physP
[ind
- 1].address
+ len
- length
;
2147 if (true && mapped
&& _memoryEntries
2148 && (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
2150 address
= dataP
->fMappedBase
+ offset
;
2154 // see how far we can coalesce ranges
2155 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
2156 len
= physP
[ind
].length
;
2162 // correct contiguous check overshoot
2166 #endif /* !__LP64__ */
2169 panic("IOGMD: not wired for the IODMACommand");
2171 assert(_memoryEntries
);
2173 dataP
= getDataP(_memoryEntries
);
2174 const ioPLBlock
*ioplList
= getIOPLList(dataP
);
2175 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
2176 upl_page_info_t
*pageList
= getPageList(dataP
);
2178 assert(numIOPLs
> 0);
2180 // Scan through iopl info blocks looking for block containing offset
2181 while (ind
< numIOPLs
&& offset
>= ioplList
[ind
].fIOMDOffset
)
2184 // Go back to actual range as search goes past it
2185 ioPLBlock ioplInfo
= ioplList
[ind
- 1];
2186 off2Ind
= ioplInfo
.fIOMDOffset
;
2189 length
= ioplList
[ind
].fIOMDOffset
;
2192 length
-= offset
; // Remainder within iopl
2194 // Subtract offset till this iopl in total list
2197 // If a mapped address is requested and this is a pre-mapped IOPL
2198 // then just need to compute an offset relative to the mapped base.
2199 if (mapped
&& dataP
->fMappedBase
) {
2200 offset
+= (ioplInfo
.fPageOffset
& PAGE_MASK
);
2201 address
= trunc_page_64(dataP
->fMappedBase
) + ptoa_64(ioplInfo
.fMappedPage
) + offset
;
2202 continue; // Done leave do/while(false) now
2205 // The offset is rebased into the current iopl.
2206 // Now add the iopl 1st page offset.
2207 offset
+= ioplInfo
.fPageOffset
;
2209 // For external UPLs the fPageInfo field points directly to
2210 // the upl's upl_page_info_t array.
2211 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
2212 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
2214 pageList
= &pageList
[ioplInfo
.fPageInfo
];
2216 // Check for direct device non-paged memory
2217 if ( ioplInfo
.fFlags
& kIOPLOnDevice
) {
2218 address
= ptoa_64(pageList
->phys_addr
) + offset
;
2219 continue; // Done leave do/while(false) now
2222 // Now we need compute the index into the pageList
2223 UInt pageInd
= atop_32(offset
);
2224 offset
&= PAGE_MASK
;
2226 // Compute the starting address of this segment
2227 IOPhysicalAddress pageAddr
= pageList
[pageInd
].phys_addr
;
2229 panic("!pageList phys_addr");
2232 address
= ptoa_64(pageAddr
) + offset
;
2234 // length is currently set to the length of the remainider of the iopl.
2235 // We need to check that the remainder of the iopl is contiguous.
2236 // This is indicated by pageList[ind].phys_addr being sequential.
2237 IOByteCount contigLength
= PAGE_SIZE
- offset
;
2238 while (contigLength
< length
2239 && ++pageAddr
== pageList
[++pageInd
].phys_addr
)
2241 contigLength
+= PAGE_SIZE
;
2244 if (contigLength
< length
)
2245 length
= contigLength
;
2253 // Update return values and state
2254 isP
->fIO
.fIOVMAddr
= address
;
2255 isP
->fIO
.fLength
= length
;
2257 isP
->fOffset2Index
= off2Ind
;
2258 isP
->fNextOffset
= isP
->fIO
.fOffset
+ length
;
2260 return kIOReturnSuccess
;
2264 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
2267 mach_vm_address_t address
= 0;
2268 mach_vm_size_t length
= 0;
2269 IOMapper
* mapper
= gIOSystemMapper
;
2270 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2272 if (lengthOfSegment
)
2273 *lengthOfSegment
= 0;
2275 if (offset
>= _length
)
2278 // IOMemoryDescriptor::doMap() cannot use getPhysicalSegment() to obtain the page offset, since it must
2279 // support the unwired memory case in IOGeneralMemoryDescriptor, and hibernate_write_image() cannot use
2280 // map()->getVirtualAddress() to obtain the kernel pointer, since it must prevent the memory allocation
2281 // due to IOMemoryMap, so _kIOMemorySourceSegment is a necessary evil until all of this gets cleaned up
2283 if ((options
& _kIOMemorySourceSegment
) && (kIOMemoryTypeUPL
!= type
))
2285 unsigned rangesIndex
= 0;
2286 Ranges vec
= _ranges
;
2287 mach_vm_address_t addr
;
2289 // Find starting address within the vector of ranges
2291 getAddrLenForInd(addr
, length
, type
, vec
, rangesIndex
);
2292 if (offset
< length
)
2294 offset
-= length
; // (make offset relative)
2298 // Now that we have the starting range,
2299 // lets find the last contiguous range
2303 for ( ++rangesIndex
; rangesIndex
< _rangesCount
; rangesIndex
++ ) {
2304 mach_vm_address_t newAddr
;
2305 mach_vm_size_t newLen
;
2307 getAddrLenForInd(newAddr
, newLen
, type
, vec
, rangesIndex
);
2308 if (addr
+ length
!= newAddr
)
2313 address
= (IOPhysicalAddress
) addr
; // Truncate address to 32bit
2317 IOMDDMAWalkSegmentState _state
;
2318 IOMDDMAWalkSegmentArgs
* state
= (IOMDDMAWalkSegmentArgs
*) (void *)&_state
;
2320 state
->fOffset
= offset
;
2321 state
->fLength
= _length
- offset
;
2322 state
->fMapped
= (0 == (options
& kIOMemoryMapperNone
)) && !(_flags
& kIOMemoryHostOnly
);
2324 ret
= dmaCommandOperation(kIOMDFirstSegment
, _state
, sizeof(_state
));
2326 if ((kIOReturnSuccess
!= ret
) && (kIOReturnOverrun
!= ret
))
2327 DEBG("getPhysicalSegment dmaCommandOperation(%lx), %p, offset %qx, addr %qx, len %qx\n",
2328 ret
, this, state
->fOffset
,
2329 state
->fIOVMAddr
, state
->fLength
);
2330 if (kIOReturnSuccess
== ret
)
2332 address
= state
->fIOVMAddr
;
2333 length
= state
->fLength
;
2336 // dmaCommandOperation() does not distinguish between "mapped" and "unmapped" physical memory, even
2337 // with fMapped set correctly, so we must handle the transformation here until this gets cleaned up
2339 if (mapper
&& ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
)))
2341 if ((options
& kIOMemoryMapperNone
) && !(_flags
& kIOMemoryMapperNone
))
2343 addr64_t origAddr
= address
;
2344 IOByteCount origLen
= length
;
2346 address
= mapper
->mapToPhysicalAddress(origAddr
);
2347 length
= page_size
- (address
& (page_size
- 1));
2348 while ((length
< origLen
)
2349 && ((address
+ length
) == mapper
->mapToPhysicalAddress(origAddr
+ length
)))
2350 length
+= page_size
;
2351 if (length
> origLen
)
2360 if (lengthOfSegment
)
2361 *lengthOfSegment
= length
;
2368 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
2370 addr64_t address
= 0;
2372 if (options
& _kIOMemorySourceSegment
)
2374 address
= getSourceSegment(offset
, lengthOfSegment
);
2376 else if (options
& kIOMemoryMapperNone
)
2378 address
= getPhysicalSegment64(offset
, lengthOfSegment
);
2382 address
= getPhysicalSegment(offset
, lengthOfSegment
);
2389 IOGeneralMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2391 return (getPhysicalSegment(offset
, lengthOfSegment
, kIOMemoryMapperNone
));
2395 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2397 addr64_t address
= 0;
2398 IOByteCount length
= 0;
2400 address
= getPhysicalSegment(offset
, lengthOfSegment
, 0);
2402 if (lengthOfSegment
)
2403 length
= *lengthOfSegment
;
2405 if ((address
+ length
) > 0x100000000ULL
)
2407 panic("getPhysicalSegment() out of 32b range 0x%qx, len 0x%lx, class %s",
2408 address
, (long) length
, (getMetaClass())->getClassName());
2411 return ((IOPhysicalAddress
) address
);
2415 IOMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2417 IOPhysicalAddress phys32
;
2420 IOMapper
* mapper
= 0;
2422 phys32
= getPhysicalSegment(offset
, lengthOfSegment
);
2426 if (gIOSystemMapper
)
2427 mapper
= gIOSystemMapper
;
2431 IOByteCount origLen
;
2433 phys64
= mapper
->mapToPhysicalAddress(phys32
);
2434 origLen
= *lengthOfSegment
;
2435 length
= page_size
- (phys64
& (page_size
- 1));
2436 while ((length
< origLen
)
2437 && ((phys64
+ length
) == mapper
->mapToPhysicalAddress(phys32
+ length
)))
2438 length
+= page_size
;
2439 if (length
> origLen
)
2442 *lengthOfSegment
= length
;
2445 phys64
= (addr64_t
) phys32
;
2451 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2453 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, 0));
2457 IOGeneralMemoryDescriptor::getSourceSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2459 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, _kIOMemorySourceSegment
));
2462 void * IOGeneralMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
2463 IOByteCount
* lengthOfSegment
)
2465 if (_task
== kernel_task
)
2466 return (void *) getSourceSegment(offset
, lengthOfSegment
);
2468 panic("IOGMD::getVirtualSegment deprecated");
2472 #endif /* !__LP64__ */
2475 IOMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
2477 IOMemoryDescriptor
*md
= const_cast<IOMemoryDescriptor
*>(this);
2478 DMACommandOps params
;
2481 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
2482 op
&= kIOMDDMACommandOperationMask
;
2484 if (kIOMDGetCharacteristics
== op
) {
2485 if (dataSize
< sizeof(IOMDDMACharacteristics
))
2486 return kIOReturnUnderrun
;
2488 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
2489 data
->fLength
= getLength();
2491 data
->fDirection
= getDirection();
2492 data
->fIsPrepared
= true; // Assume prepared - fails safe
2494 else if (kIOMDWalkSegments
== op
) {
2495 if (dataSize
< sizeof(IOMDDMAWalkSegmentArgs
))
2496 return kIOReturnUnderrun
;
2498 IOMDDMAWalkSegmentArgs
*data
= (IOMDDMAWalkSegmentArgs
*) vData
;
2499 IOByteCount offset
= (IOByteCount
) data
->fOffset
;
2501 IOPhysicalLength length
;
2502 if (data
->fMapped
&& IOMapper::gSystem
)
2503 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
);
2505 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
, kIOMemoryMapperNone
);
2506 data
->fLength
= length
;
2508 else if (kIOMDAddDMAMapSpec
== op
) return kIOReturnUnsupported
;
2509 else if (kIOMDDMAMap
== op
)
2511 if (dataSize
< sizeof(IOMDDMAMapArgs
))
2512 return kIOReturnUnderrun
;
2513 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
2515 if (params
) panic("class %s does not support IODMACommand::kIterateOnly", getMetaClass()->getClassName());
2517 data
->fMapContig
= true;
2518 err
= md
->dmaMap(data
->fMapper
, data
->fCommand
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocLength
);
2521 else return kIOReturnBadArgument
;
2523 return kIOReturnSuccess
;
2527 IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState
,
2528 IOOptionBits
* oldState
)
2530 IOReturn err
= kIOReturnSuccess
;
2532 vm_purgable_t control
;
2537 err
= super::setPurgeable(newState
, oldState
);
2541 if (kIOMemoryThreadSafe
& _flags
)
2545 // Find the appropriate vm_map for the given task
2547 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
2549 err
= kIOReturnNotReady
;
2554 err
= kIOReturnUnsupported
;
2558 curMap
= get_task_map(_task
);
2560 // can only do one range
2561 Ranges vec
= _ranges
;
2562 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2563 mach_vm_address_t addr
;
2565 getAddrLenForInd(addr
, len
, type
, vec
, 0);
2567 err
= purgeableControlBits(newState
, &control
, &state
);
2568 if (kIOReturnSuccess
!= err
)
2570 err
= mach_vm_purgable_control(curMap
, addr
, control
, &state
);
2573 if (kIOReturnSuccess
== err
)
2575 err
= purgeableStateBits(&state
);
2581 if (kIOMemoryThreadSafe
& _flags
)
2588 IOReturn
IOMemoryDescriptor::setPurgeable( IOOptionBits newState
,
2589 IOOptionBits
* oldState
)
2591 IOReturn err
= kIOReturnNotReady
;
2593 if (kIOMemoryThreadSafe
& _flags
) LOCK
;
2594 if (_memRef
) err
= IOGeneralMemoryDescriptor::memoryReferenceSetPurgeable(_memRef
, newState
, oldState
);
2595 if (kIOMemoryThreadSafe
& _flags
) UNLOCK
;
2600 IOReturn
IOMemoryDescriptor::getPageCounts( IOByteCount
* residentPageCount
,
2601 IOByteCount
* dirtyPageCount
)
2603 IOReturn err
= kIOReturnNotReady
;
2605 if (kIOMemoryThreadSafe
& _flags
) LOCK
;
2606 if (_memRef
) err
= IOGeneralMemoryDescriptor::memoryReferenceGetPageCounts(_memRef
, residentPageCount
, dirtyPageCount
);
2609 IOMultiMemoryDescriptor
* mmd
;
2610 IOSubMemoryDescriptor
* smd
;
2611 if ((smd
= OSDynamicCast(IOSubMemoryDescriptor
, this)))
2613 err
= smd
->getPageCounts(residentPageCount
, dirtyPageCount
);
2615 else if ((mmd
= OSDynamicCast(IOMultiMemoryDescriptor
, this)))
2617 err
= mmd
->getPageCounts(residentPageCount
, dirtyPageCount
);
2620 if (kIOMemoryThreadSafe
& _flags
) UNLOCK
;
2626 extern "C" void dcache_incoherent_io_flush64(addr64_t pa
, unsigned int count
);
2627 extern "C" void dcache_incoherent_io_store64(addr64_t pa
, unsigned int count
);
2629 static void SetEncryptOp(addr64_t pa
, unsigned int count
)
2633 page
= atop_64(round_page_64(pa
));
2634 end
= atop_64(trunc_page_64(pa
+ count
));
2635 for (; page
< end
; page
++)
2637 pmap_clear_noencrypt(page
);
2641 static void ClearEncryptOp(addr64_t pa
, unsigned int count
)
2645 page
= atop_64(round_page_64(pa
));
2646 end
= atop_64(trunc_page_64(pa
+ count
));
2647 for (; page
< end
; page
++)
2649 pmap_set_noencrypt(page
);
2653 IOReturn
IOMemoryDescriptor::performOperation( IOOptionBits options
,
2654 IOByteCount offset
, IOByteCount length
)
2656 IOByteCount remaining
;
2658 void (*func
)(addr64_t pa
, unsigned int count
) = 0;
2662 case kIOMemoryIncoherentIOFlush
:
2663 func
= &dcache_incoherent_io_flush64
;
2665 case kIOMemoryIncoherentIOStore
:
2666 func
= &dcache_incoherent_io_store64
;
2669 case kIOMemorySetEncrypted
:
2670 func
= &SetEncryptOp
;
2672 case kIOMemoryClearEncrypted
:
2673 func
= &ClearEncryptOp
;
2678 return (kIOReturnUnsupported
);
2680 if (kIOMemoryThreadSafe
& _flags
)
2684 remaining
= length
= min(length
, getLength() - offset
);
2686 // (process another target segment?)
2691 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
2695 // Clip segment length to remaining
2696 if (dstLen
> remaining
)
2699 (*func
)(dstAddr64
, dstLen
);
2702 remaining
-= dstLen
;
2705 if (kIOMemoryThreadSafe
& _flags
)
2708 return (remaining
? kIOReturnUnderrun
: kIOReturnSuccess
);
2711 #if defined(__i386__) || defined(__x86_64__)
2713 #define io_kernel_static_start vm_kernel_stext
2714 #define io_kernel_static_end vm_kernel_etext
2717 #error io_kernel_static_end is undefined for this architecture
2720 static kern_return_t
2721 io_get_kernel_static_upl(
2724 upl_size_t
*upl_size
,
2726 upl_page_info_array_t page_list
,
2727 unsigned int *count
,
2728 ppnum_t
*highest_page
)
2730 unsigned int pageCount
, page
;
2732 ppnum_t highestPage
= 0;
2734 pageCount
= atop_32(*upl_size
);
2735 if (pageCount
> *count
)
2740 for (page
= 0; page
< pageCount
; page
++)
2742 phys
= pmap_find_phys(kernel_pmap
, ((addr64_t
)offset
) + ptoa_64(page
));
2745 page_list
[page
].phys_addr
= phys
;
2746 page_list
[page
].pageout
= 0;
2747 page_list
[page
].absent
= 0;
2748 page_list
[page
].dirty
= 0;
2749 page_list
[page
].precious
= 0;
2750 page_list
[page
].device
= 0;
2751 if (phys
> highestPage
)
2755 *highest_page
= highestPage
;
2757 return ((page
>= pageCount
) ? kIOReturnSuccess
: kIOReturnVMError
);
2760 IOReturn
IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection
)
2762 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2763 IOReturn error
= kIOReturnCannotWire
;
2765 upl_page_info_array_t pageInfo
;
2768 assert(kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
);
2770 if ((kIODirectionOutIn
& forDirection
) == kIODirectionNone
)
2771 forDirection
= (IODirection
) (forDirection
| getDirection());
2773 upl_control_flags_t uplFlags
; // This Mem Desc's default flags for upl creation
2774 switch (kIODirectionOutIn
& forDirection
)
2776 case kIODirectionOut
:
2777 // Pages do not need to be marked as dirty on commit
2778 uplFlags
= UPL_COPYOUT_FROM
;
2781 case kIODirectionIn
:
2783 uplFlags
= 0; // i.e. ~UPL_COPYOUT_FROM
2789 if ((kIOMemoryPreparedReadOnly
& _flags
) && !(UPL_COPYOUT_FROM
& uplFlags
))
2791 OSReportWithBacktrace("IOMemoryDescriptor 0x%lx prepared read only", VM_KERNEL_ADDRPERM(this));
2792 error
= kIOReturnNotWritable
;
2794 else error
= kIOReturnSuccess
;
2798 dataP
= getDataP(_memoryEntries
);
2800 mapper
= dataP
->fMapper
;
2801 dataP
->fMappedBase
= 0;
2803 uplFlags
|= UPL_SET_IO_WIRE
| UPL_SET_LITE
;
2804 uplFlags
|= UPL_MEMORY_TAG_MAKE(IOMemoryTag(kernel_map
));
2806 if (kIODirectionPrepareToPhys32
& forDirection
)
2808 if (!mapper
) uplFlags
|= UPL_NEED_32BIT_ADDR
;
2809 if (dataP
->fDMAMapNumAddressBits
> 32) dataP
->fDMAMapNumAddressBits
= 32;
2811 if (kIODirectionPrepareNoFault
& forDirection
) uplFlags
|= UPL_REQUEST_NO_FAULT
;
2812 if (kIODirectionPrepareNoZeroFill
& forDirection
) uplFlags
|= UPL_NOZEROFILLIO
;
2813 if (kIODirectionPrepareNonCoherent
& forDirection
) uplFlags
|= UPL_REQUEST_FORCE_COHERENCY
;
2817 // Note that appendBytes(NULL) zeros the data up to the desired length
2818 // and the length parameter is an unsigned int
2819 size_t uplPageSize
= dataP
->fPageCnt
* sizeof(upl_page_info_t
);
2820 if (uplPageSize
> ((unsigned int)uplPageSize
)) return (kIOReturnNoMemory
);
2821 if (!_memoryEntries
->appendBytes(0, uplPageSize
)) return (kIOReturnNoMemory
);
2824 // Find the appropriate vm_map for the given task
2826 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
)) curMap
= 0;
2827 else curMap
= get_task_map(_task
);
2829 // Iterate over the vector of virtual ranges
2830 Ranges vec
= _ranges
;
2831 unsigned int pageIndex
= 0;
2832 IOByteCount mdOffset
= 0;
2833 ppnum_t highestPage
= 0;
2835 IOMemoryEntry
* memRefEntry
= 0;
2836 if (_memRef
) memRefEntry
= &_memRef
->entries
[0];
2838 for (UInt range
= 0; range
< _rangesCount
; range
++) {
2840 mach_vm_address_t startPage
;
2841 mach_vm_size_t numBytes
;
2842 ppnum_t highPage
= 0;
2844 // Get the startPage address and length of vec[range]
2845 getAddrLenForInd(startPage
, numBytes
, type
, vec
, range
);
2846 iopl
.fPageOffset
= startPage
& PAGE_MASK
;
2847 numBytes
+= iopl
.fPageOffset
;
2848 startPage
= trunc_page_64(startPage
);
2851 iopl
.fMappedPage
= mapBase
+ pageIndex
;
2853 iopl
.fMappedPage
= 0;
2855 // Iterate over the current range, creating UPLs
2857 vm_address_t kernelStart
= (vm_address_t
) startPage
;
2859 if (curMap
) theMap
= curMap
;
2866 assert(_task
== kernel_task
);
2867 theMap
= IOPageableMapForAddress(kernelStart
);
2870 // ioplFlags is an in/out parameter
2871 upl_control_flags_t ioplFlags
= uplFlags
;
2872 dataP
= getDataP(_memoryEntries
);
2873 pageInfo
= getPageList(dataP
);
2874 upl_page_list_ptr_t baseInfo
= &pageInfo
[pageIndex
];
2876 upl_size_t ioplSize
= round_page(numBytes
);
2877 unsigned int numPageInfo
= atop_32(ioplSize
);
2879 if ((theMap
== kernel_map
)
2880 && (kernelStart
>= io_kernel_static_start
)
2881 && (kernelStart
< io_kernel_static_end
)) {
2882 error
= io_get_kernel_static_upl(theMap
,
2891 memory_object_offset_t entryOffset
;
2893 entryOffset
= mdOffset
;
2894 entryOffset
= (entryOffset
- iopl
.fPageOffset
- memRefEntry
->offset
);
2895 if (entryOffset
>= memRefEntry
->size
) {
2897 if (memRefEntry
>= &_memRef
->entries
[_memRef
->count
]) panic("memRefEntry");
2900 if (ioplSize
> (memRefEntry
->size
- entryOffset
)) ioplSize
= (memRefEntry
->size
- entryOffset
);
2901 error
= memory_object_iopl_request(memRefEntry
->entry
,
2911 error
= vm_map_create_upl(theMap
,
2913 (upl_size_t
*)&ioplSize
,
2921 if (error
!= KERN_SUCCESS
)
2925 highPage
= upl_get_highest_page(iopl
.fIOPL
);
2926 if (highPage
> highestPage
)
2927 highestPage
= highPage
;
2929 error
= kIOReturnCannotWire
;
2931 if (baseInfo
->device
) {
2933 iopl
.fFlags
= kIOPLOnDevice
;
2939 iopl
.fIOMDOffset
= mdOffset
;
2940 iopl
.fPageInfo
= pageIndex
;
2941 if (mapper
&& pageIndex
&& (page_mask
& (mdOffset
+ iopl
.fPageOffset
))) dataP
->fDiscontig
= true;
2944 // used to remove the upl for auto prepares here, for some errant code
2945 // that freed memory before the descriptor pointing at it
2946 if ((_flags
& kIOMemoryAutoPrepare
) && iopl
.fIOPL
)
2948 upl_commit(iopl
.fIOPL
, 0, 0);
2949 upl_deallocate(iopl
.fIOPL
);
2954 if (!_memoryEntries
->appendBytes(&iopl
, sizeof(iopl
))) {
2955 // Clean up partial created and unsaved iopl
2957 upl_abort(iopl
.fIOPL
, 0);
2958 upl_deallocate(iopl
.fIOPL
);
2964 // Check for a multiple iopl's in one virtual range
2965 pageIndex
+= numPageInfo
;
2966 mdOffset
-= iopl
.fPageOffset
;
2967 if (ioplSize
< numBytes
) {
2968 numBytes
-= ioplSize
;
2969 startPage
+= ioplSize
;
2970 mdOffset
+= ioplSize
;
2971 iopl
.fPageOffset
= 0;
2972 if (mapper
) iopl
.fMappedPage
= mapBase
+ pageIndex
;
2975 mdOffset
+= numBytes
;
2981 _highestPage
= highestPage
;
2983 if (UPL_COPYOUT_FROM
& uplFlags
) _flags
|= kIOMemoryPreparedReadOnly
;
2985 if ((kIOTracking
& gIOKitDebug
)
2986 //&& !(_flags & kIOMemoryAutoPrepare)
2989 dataP
= getDataP(_memoryEntries
);
2991 IOTrackingAdd(gIOWireTracking
, &dataP
->fWireTracking
, ptoa(_pages
), false);
2995 return kIOReturnSuccess
;
2999 dataP
= getDataP(_memoryEntries
);
3000 UInt done
= getNumIOPL(_memoryEntries
, dataP
);
3001 ioPLBlock
*ioplList
= getIOPLList(dataP
);
3003 for (UInt range
= 0; range
< done
; range
++)
3005 if (ioplList
[range
].fIOPL
) {
3006 upl_abort(ioplList
[range
].fIOPL
, 0);
3007 upl_deallocate(ioplList
[range
].fIOPL
);
3010 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
3013 if (error
== KERN_FAILURE
)
3014 error
= kIOReturnCannotWire
;
3015 else if (error
== KERN_MEMORY_ERROR
)
3016 error
= kIOReturnNoResources
;
3021 bool IOGeneralMemoryDescriptor::initMemoryEntries(size_t size
, IOMapper
* mapper
)
3024 unsigned dataSize
= size
;
3026 if (!_memoryEntries
) {
3027 _memoryEntries
= OSData::withCapacity(dataSize
);
3028 if (!_memoryEntries
)
3031 else if (!_memoryEntries
->initWithCapacity(dataSize
))
3034 _memoryEntries
->appendBytes(0, computeDataSize(0, 0));
3035 dataP
= getDataP(_memoryEntries
);
3037 if (mapper
== kIOMapperWaitSystem
) {
3038 IOMapper::checkForSystemMapper();
3039 mapper
= IOMapper::gSystem
;
3041 dataP
->fMapper
= mapper
;
3042 dataP
->fPageCnt
= 0;
3043 dataP
->fMappedBase
= 0;
3044 dataP
->fDMAMapNumAddressBits
= 64;
3045 dataP
->fDMAMapAlignment
= 0;
3046 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
3047 dataP
->fDiscontig
= false;
3048 dataP
->fCompletionError
= false;
3053 IOReturn
IOMemoryDescriptor::dmaMap(
3055 IODMACommand
* command
,
3056 const IODMAMapSpecification
* mapSpec
,
3059 uint64_t * mapAddress
,
3060 uint64_t * mapLength
)
3063 uint32_t mapOptions
;
3066 mapOptions
|= kIODMAMapReadAccess
;
3067 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
3069 ret
= mapper
->iovmMapMemory(this, offset
, length
, mapOptions
,
3070 mapSpec
, command
, NULL
, mapAddress
, mapLength
);
3075 IOReturn
IOGeneralMemoryDescriptor::dmaMap(
3077 IODMACommand
* command
,
3078 const IODMAMapSpecification
* mapSpec
,
3081 uint64_t * mapAddress
,
3082 uint64_t * mapLength
)
3084 IOReturn err
= kIOReturnSuccess
;
3086 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3089 if (kIOMemoryHostOnly
& _flags
) return (kIOReturnSuccess
);
3091 if ((type
== kIOMemoryTypePhysical
) || (type
== kIOMemoryTypePhysical64
)
3092 || offset
|| (length
!= _length
))
3094 err
= super::dmaMap(mapper
, command
, mapSpec
, offset
, length
, mapAddress
, mapLength
);
3096 else if (_memoryEntries
&& _pages
&& (dataP
= getDataP(_memoryEntries
)))
3098 const ioPLBlock
* ioplList
= getIOPLList(dataP
);
3099 upl_page_info_t
* pageList
;
3100 uint32_t mapOptions
= 0;
3102 IODMAMapSpecification mapSpec
;
3103 bzero(&mapSpec
, sizeof(mapSpec
));
3104 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
3105 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
3107 // For external UPLs the fPageInfo field points directly to
3108 // the upl's upl_page_info_t array.
3109 if (ioplList
->fFlags
& kIOPLExternUPL
)
3111 pageList
= (upl_page_info_t
*) ioplList
->fPageInfo
;
3112 mapOptions
|= kIODMAMapPagingPath
;
3114 else pageList
= getPageList(dataP
);
3116 if ((_length
== ptoa_64(_pages
)) && !(page_mask
& ioplList
->fPageOffset
))
3118 mapOptions
|= kIODMAMapPageListFullyOccupied
;
3121 mapOptions
|= kIODMAMapReadAccess
;
3122 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
3124 // Check for direct device non-paged memory
3125 if (ioplList
->fFlags
& kIOPLOnDevice
) mapOptions
|= kIODMAMapPhysicallyContiguous
;
3127 IODMAMapPageList dmaPageList
=
3129 .pageOffset
= ioplList
->fPageOffset
& page_mask
,
3130 .pageListCount
= _pages
,
3131 .pageList
= &pageList
[0]
3133 err
= mapper
->iovmMapMemory(this, offset
, length
, mapOptions
, &mapSpec
,
3134 command
, &dmaPageList
, mapAddress
, mapLength
);
3143 * Prepare the memory for an I/O transfer. This involves paging in
3144 * the memory, if necessary, and wiring it down for the duration of
3145 * the transfer. The complete() method completes the processing of
3146 * the memory after the I/O transfer finishes. This method needn't
3147 * called for non-pageable memory.
3150 IOReturn
IOGeneralMemoryDescriptor::prepare(IODirection forDirection
)
3152 IOReturn error
= kIOReturnSuccess
;
3153 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3155 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
3156 return kIOReturnSuccess
;
3159 IOLockLock(_prepareLock
);
3161 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
)
3163 error
= wireVirtual(forDirection
);
3166 if (kIOReturnSuccess
== error
)
3168 if (1 == ++_wireCount
)
3170 if (kIOMemoryClearEncrypt
& _flags
)
3172 performOperation(kIOMemoryClearEncrypted
, 0, _length
);
3178 IOLockUnlock(_prepareLock
);
3186 * Complete processing of the memory after an I/O transfer finishes.
3187 * This method should not be called unless a prepare was previously
3188 * issued; the prepare() and complete() must occur in pairs, before
3189 * before and after an I/O transfer involving pageable memory.
3192 IOReturn
IOGeneralMemoryDescriptor::complete(IODirection forDirection
)
3194 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3197 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
3198 return kIOReturnSuccess
;
3201 IOLockLock(_prepareLock
);
3205 if ((kIODirectionCompleteWithError
& forDirection
)
3206 && (dataP
= getDataP(_memoryEntries
)))
3207 dataP
->fCompletionError
= true;
3211 if ((kIOMemoryClearEncrypt
& _flags
) && (1 == _wireCount
))
3213 performOperation(kIOMemorySetEncrypted
, 0, _length
);
3217 if (!_wireCount
|| (kIODirectionCompleteWithDataValid
& forDirection
))
3219 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3220 dataP
= getDataP(_memoryEntries
);
3221 ioPLBlock
*ioplList
= getIOPLList(dataP
);
3222 UInt ind
, count
= getNumIOPL(_memoryEntries
, dataP
);
3226 // kIODirectionCompleteWithDataValid & forDirection
3227 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
)
3229 for (ind
= 0; ind
< count
; ind
++)
3231 if (ioplList
[ind
].fIOPL
) iopl_valid_data(ioplList
[ind
].fIOPL
);
3237 #if IOMD_DEBUG_DMAACTIVE
3238 if (__iomd_reservedA
) panic("complete() while dma active");
3239 #endif /* IOMD_DEBUG_DMAACTIVE */
3241 if (dataP
->fMappedBase
) {
3242 dataP
->fMapper
->iovmUnmapMemory(this, NULL
, dataP
->fMappedBase
, dataP
->fMappedLength
);
3243 dataP
->fMappedBase
= 0;
3245 // Only complete iopls that we created which are for TypeVirtual
3246 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) {
3248 if ((kIOTracking
& gIOKitDebug
)
3249 //&& !(_flags & kIOMemoryAutoPrepare)
3252 IOTrackingRemove(gIOWireTracking
, &dataP
->fWireTracking
, ptoa(_pages
));
3255 for (ind
= 0; ind
< count
; ind
++)
3256 if (ioplList
[ind
].fIOPL
) {
3257 if (dataP
->fCompletionError
)
3258 upl_abort(ioplList
[ind
].fIOPL
, 0 /*!UPL_ABORT_DUMP_PAGES*/);
3260 upl_commit(ioplList
[ind
].fIOPL
, 0, 0);
3261 upl_deallocate(ioplList
[ind
].fIOPL
);
3263 } else if (kIOMemoryTypeUPL
== type
) {
3264 upl_set_referenced(ioplList
[0].fIOPL
, false);
3267 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
3269 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
3275 IOLockUnlock(_prepareLock
);
3277 return kIOReturnSuccess
;
3280 IOReturn
IOGeneralMemoryDescriptor::doMap(
3281 vm_map_t __addressMap
,
3282 IOVirtualAddress
* __address
,
3283 IOOptionBits options
,
3284 IOByteCount __offset
,
3285 IOByteCount __length
)
3288 if (!(kIOMap64Bit
& options
)) panic("IOGeneralMemoryDescriptor::doMap !64bit");
3289 #endif /* !__LP64__ */
3293 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
3294 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3295 mach_vm_size_t length
= mapping
->fLength
;
3297 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3298 Ranges vec
= _ranges
;
3300 mach_vm_address_t range0Addr
= 0;
3301 mach_vm_size_t range0Len
= 0;
3303 if ((offset
>= _length
) || ((offset
+ length
) > _length
))
3304 return( kIOReturnBadArgument
);
3307 getAddrLenForInd(range0Addr
, range0Len
, type
, vec
, 0);
3309 // mapping source == dest? (could be much better)
3311 && (mapping
->fAddressTask
== _task
)
3312 && (mapping
->fAddressMap
== get_task_map(_task
))
3313 && (options
& kIOMapAnywhere
)
3314 && (1 == _rangesCount
)
3317 && (length
<= range0Len
))
3319 mapping
->fAddress
= range0Addr
;
3320 mapping
->fOptions
|= kIOMapStatic
;
3322 return( kIOReturnSuccess
);
3327 IOOptionBits createOptions
= 0;
3328 if (!(kIOMapReadOnly
& options
))
3330 createOptions
|= kIOMemoryReferenceWrite
;
3331 #if DEVELOPMENT || DEBUG
3332 if (kIODirectionOut
== (kIODirectionOutIn
& _flags
))
3334 OSReportWithBacktrace("warning: creating writable mapping from IOMemoryDescriptor(kIODirectionOut) - use kIOMapReadOnly or change direction");
3338 err
= memoryReferenceCreate(createOptions
, &_memRef
);
3339 if (kIOReturnSuccess
!= err
) return (err
);
3342 memory_object_t pager
;
3343 pager
= (memory_object_t
) (reserved
? reserved
->dp
.devicePager
: 0);
3345 // <upl_transpose //
3346 if ((kIOMapReference
|kIOMapUnique
) == ((kIOMapReference
|kIOMapUnique
) & options
))
3352 upl_control_flags_t flags
;
3353 unsigned int lock_count
;
3355 if (!_memRef
|| (1 != _memRef
->count
))
3357 err
= kIOReturnNotReadable
;
3361 size
= round_page(mapping
->fLength
);
3362 flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3363 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
3364 | UPL_MEMORY_TAG_MAKE(IOMemoryTag(kernel_map
));
3366 if (KERN_SUCCESS
!= memory_object_iopl_request(_memRef
->entries
[0].entry
, 0, &size
, &redirUPL2
,
3371 for (lock_count
= 0;
3372 IORecursiveLockHaveLock(gIOMemoryLock
);
3376 err
= upl_transpose(redirUPL2
, mapping
->fRedirUPL
);
3383 if (kIOReturnSuccess
!= err
)
3385 IOLog("upl_transpose(%x)\n", err
);
3386 err
= kIOReturnSuccess
;
3391 upl_commit(redirUPL2
, NULL
, 0);
3392 upl_deallocate(redirUPL2
);
3396 // swap the memEntries since they now refer to different vm_objects
3397 IOMemoryReference
* me
= _memRef
;
3398 _memRef
= mapping
->fMemory
->_memRef
;
3399 mapping
->fMemory
->_memRef
= me
;
3402 err
= populateDevicePager( pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
3406 // upl_transpose> //
3409 err
= memoryReferenceMap(_memRef
, mapping
->fAddressMap
, offset
, length
, options
, &mapping
->fAddress
);
3411 if (err
== KERN_SUCCESS
) IOTrackingAdd(gIOMapTracking
, &mapping
->fTracking
, length
, false);
3413 if ((err
== KERN_SUCCESS
) && pager
)
3415 err
= populateDevicePager(pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
3417 if (err
!= KERN_SUCCESS
) doUnmap(mapping
->fAddressMap
, (IOVirtualAddress
) mapping
, 0);
3418 else if (kIOMapDefaultCache
== (options
& kIOMapCacheMask
))
3420 mapping
->fOptions
|= ((_flags
& kIOMemoryBufferCacheMask
) >> kIOMemoryBufferCacheShift
);
3428 IOReturn
IOGeneralMemoryDescriptor::doUnmap(
3429 vm_map_t addressMap
,
3430 IOVirtualAddress __address
,
3431 IOByteCount __length
)
3433 return (super::doUnmap(addressMap
, __address
, __length
));
3436 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3439 #define super OSObject
3441 OSDefineMetaClassAndStructors( IOMemoryMap
, OSObject
)
3443 OSMetaClassDefineReservedUnused(IOMemoryMap
, 0);
3444 OSMetaClassDefineReservedUnused(IOMemoryMap
, 1);
3445 OSMetaClassDefineReservedUnused(IOMemoryMap
, 2);
3446 OSMetaClassDefineReservedUnused(IOMemoryMap
, 3);
3447 OSMetaClassDefineReservedUnused(IOMemoryMap
, 4);
3448 OSMetaClassDefineReservedUnused(IOMemoryMap
, 5);
3449 OSMetaClassDefineReservedUnused(IOMemoryMap
, 6);
3450 OSMetaClassDefineReservedUnused(IOMemoryMap
, 7);
3452 /* ex-inline function implementation */
3453 IOPhysicalAddress
IOMemoryMap::getPhysicalAddress()
3454 { return( getPhysicalSegment( 0, 0 )); }
3456 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3458 bool IOMemoryMap::init(
3460 mach_vm_address_t toAddress
,
3461 IOOptionBits _options
,
3462 mach_vm_size_t _offset
,
3463 mach_vm_size_t _length
)
3471 fAddressMap
= get_task_map(intoTask
);
3474 vm_map_reference(fAddressMap
);
3476 fAddressTask
= intoTask
;
3477 fOptions
= _options
;
3480 fAddress
= toAddress
;
3485 bool IOMemoryMap::setMemoryDescriptor(IOMemoryDescriptor
* _memory
, mach_vm_size_t _offset
)
3492 if( (_offset
+ fLength
) > _memory
->getLength())
3500 if (fMemory
!= _memory
)
3501 fMemory
->removeMapping(this);
3509 IOReturn
IOMemoryDescriptor::doMap(
3510 vm_map_t __addressMap
,
3511 IOVirtualAddress
* __address
,
3512 IOOptionBits options
,
3513 IOByteCount __offset
,
3514 IOByteCount __length
)
3516 return (kIOReturnUnsupported
);
3519 IOReturn
IOMemoryDescriptor::handleFault(
3521 mach_vm_size_t sourceOffset
,
3522 mach_vm_size_t length
)
3524 if( kIOMemoryRedirected
& _flags
)
3527 IOLog("sleep mem redirect %p, %qx\n", this, sourceOffset
);
3531 } while( kIOMemoryRedirected
& _flags
);
3533 return (kIOReturnSuccess
);
3536 IOReturn
IOMemoryDescriptor::populateDevicePager(
3538 vm_map_t addressMap
,
3539 mach_vm_address_t address
,
3540 mach_vm_size_t sourceOffset
,
3541 mach_vm_size_t length
,
3542 IOOptionBits options
)
3544 IOReturn err
= kIOReturnSuccess
;
3545 memory_object_t pager
= (memory_object_t
) _pager
;
3546 mach_vm_size_t size
;
3547 mach_vm_size_t bytes
;
3548 mach_vm_size_t page
;
3549 mach_vm_size_t pageOffset
;
3550 mach_vm_size_t pagerOffset
;
3551 IOPhysicalLength segLen
, chunk
;
3555 type
= _flags
& kIOMemoryTypeMask
;
3557 if (reserved
->dp
.pagerContig
)
3563 physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
);
3565 pageOffset
= physAddr
- trunc_page_64( physAddr
);
3566 pagerOffset
= sourceOffset
;
3568 size
= length
+ pageOffset
;
3569 physAddr
-= pageOffset
;
3571 segLen
+= pageOffset
;
3575 // in the middle of the loop only map whole pages
3576 if( segLen
>= bytes
) segLen
= bytes
;
3577 else if (segLen
!= trunc_page(segLen
)) err
= kIOReturnVMError
;
3578 if (physAddr
!= trunc_page_64(physAddr
)) err
= kIOReturnBadArgument
;
3580 if (kIOReturnSuccess
!= err
) break;
3582 #if DEBUG || DEVELOPMENT
3583 if ((kIOMemoryTypeUPL
!= type
)
3584 && pmap_has_managed_page(atop_64(physAddr
), atop_64(physAddr
+ segLen
- 1)))
3586 OSReportWithBacktrace("IOMemoryDescriptor physical with managed page 0x%qx:0x%qx", physAddr
, segLen
);
3588 #endif /* DEBUG || DEVELOPMENT */
3590 chunk
= (reserved
->dp
.pagerContig
? round_page(segLen
) : page_size
);
3592 (page
< segLen
) && (KERN_SUCCESS
== err
);
3595 err
= device_pager_populate_object(pager
, pagerOffset
,
3596 (ppnum_t
)(atop_64(physAddr
+ page
)), chunk
);
3597 pagerOffset
+= chunk
;
3600 assert (KERN_SUCCESS
== err
);
3603 // This call to vm_fault causes an early pmap level resolution
3604 // of the mappings created above for kernel mappings, since
3605 // faulting in later can't take place from interrupt level.
3606 if ((addressMap
== kernel_map
) && !(kIOMemoryRedirected
& _flags
))
3608 vm_fault(addressMap
,
3609 (vm_map_offset_t
)trunc_page_64(address
),
3610 VM_PROT_READ
|VM_PROT_WRITE
,
3611 FALSE
, THREAD_UNINT
, NULL
,
3612 (vm_map_offset_t
)0);
3615 sourceOffset
+= segLen
- pageOffset
;
3620 while (bytes
&& (physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
)));
3623 err
= kIOReturnBadArgument
;
3628 IOReturn
IOMemoryDescriptor::doUnmap(
3629 vm_map_t addressMap
,
3630 IOVirtualAddress __address
,
3631 IOByteCount __length
)
3634 IOMemoryMap
* mapping
;
3635 mach_vm_address_t address
;
3636 mach_vm_size_t length
;
3638 if (__length
) panic("doUnmap");
3640 mapping
= (IOMemoryMap
*) __address
;
3641 addressMap
= mapping
->fAddressMap
;
3642 address
= mapping
->fAddress
;
3643 length
= mapping
->fLength
;
3645 if (kIOMapOverwrite
& mapping
->fOptions
) err
= KERN_SUCCESS
;
3648 if ((addressMap
== kernel_map
) && (kIOMemoryBufferPageable
& _flags
))
3649 addressMap
= IOPageableMapForAddress( address
);
3651 if( kIOLogMapping
& gIOKitDebug
) IOLog("IOMemoryDescriptor::doUnmap map %p, 0x%qx:0x%qx\n",
3652 addressMap
, address
, length
);
3654 err
= mach_vm_deallocate( addressMap
, address
, length
);
3658 IOTrackingRemove(gIOMapTracking
, &mapping
->fTracking
, length
);
3664 IOReturn
IOMemoryDescriptor::redirect( task_t safeTask
, bool doRedirect
)
3666 IOReturn err
= kIOReturnSuccess
;
3667 IOMemoryMap
* mapping
= 0;
3673 _flags
|= kIOMemoryRedirected
;
3675 _flags
&= ~kIOMemoryRedirected
;
3678 if( (iter
= OSCollectionIterator::withCollection( _mappings
))) {
3680 memory_object_t pager
;
3683 pager
= (memory_object_t
) reserved
->dp
.devicePager
;
3685 pager
= MACH_PORT_NULL
;
3687 while( (mapping
= (IOMemoryMap
*) iter
->getNextObject()))
3689 mapping
->redirect( safeTask
, doRedirect
);
3690 if (!doRedirect
&& !safeTask
&& pager
&& (kernel_map
== mapping
->fAddressMap
))
3692 err
= populateDevicePager(pager
, mapping
->fAddressMap
, mapping
->fAddress
, mapping
->fOffset
, mapping
->fLength
, kIOMapDefaultCache
);
3708 // temporary binary compatibility
3709 IOSubMemoryDescriptor
* subMem
;
3710 if( (subMem
= OSDynamicCast( IOSubMemoryDescriptor
, this)))
3711 err
= subMem
->redirect( safeTask
, doRedirect
);
3713 err
= kIOReturnSuccess
;
3714 #endif /* !__LP64__ */
3719 IOReturn
IOMemoryMap::redirect( task_t safeTask
, bool doRedirect
)
3721 IOReturn err
= kIOReturnSuccess
;
3724 // err = ((IOMemoryMap *)superMap)->redirect( safeTask, doRedirect );
3736 if ((!safeTask
|| (get_task_map(safeTask
) != fAddressMap
))
3737 && (0 == (fOptions
& kIOMapStatic
)))
3739 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3740 err
= kIOReturnSuccess
;
3742 IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect
, this, fAddress
, fLength
, fAddressMap
);
3745 else if (kIOMapWriteCombineCache
== (fOptions
& kIOMapCacheMask
))
3747 IOOptionBits newMode
;
3748 newMode
= (fOptions
& ~kIOMapCacheMask
) | (doRedirect
? kIOMapInhibitCache
: kIOMapWriteCombineCache
);
3749 IOProtectCacheMode(fAddressMap
, fAddress
, fLength
, newMode
);
3756 if ((((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3757 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3759 && (doRedirect
!= (0 != (fMemory
->_flags
& kIOMemoryRedirected
))))
3760 fMemory
->redirect(safeTask
, doRedirect
);
3765 IOReturn
IOMemoryMap::unmap( void )
3771 if( fAddress
&& fAddressMap
&& (0 == fSuperMap
) && fMemory
3772 && (0 == (kIOMapStatic
& fOptions
))) {
3774 err
= fMemory
->doUnmap(fAddressMap
, (IOVirtualAddress
) this, 0);
3777 err
= kIOReturnSuccess
;
3781 vm_map_deallocate(fAddressMap
);
3792 void IOMemoryMap::taskDied( void )
3795 if (fUserClientUnmap
) unmap();
3797 else IOTrackingRemove(gIOMapTracking
, &fTracking
, fLength
);
3801 vm_map_deallocate(fAddressMap
);
3809 IOReturn
IOMemoryMap::userClientUnmap( void )
3811 fUserClientUnmap
= true;
3812 return (kIOReturnSuccess
);
3815 // Overload the release mechanism. All mappings must be a member
3816 // of a memory descriptors _mappings set. This means that we
3817 // always have 2 references on a mapping. When either of these mappings
3818 // are released we need to free ourselves.
3819 void IOMemoryMap::taggedRelease(const void *tag
) const
3822 super::taggedRelease(tag
, 2);
3826 void IOMemoryMap::free()
3833 fMemory
->removeMapping(this);
3838 if (fOwner
&& (fOwner
!= fMemory
))
3841 fOwner
->removeMapping(this);
3846 fSuperMap
->release();
3849 upl_commit(fRedirUPL
, NULL
, 0);
3850 upl_deallocate(fRedirUPL
);
3856 IOByteCount
IOMemoryMap::getLength()
3861 IOVirtualAddress
IOMemoryMap::getVirtualAddress()
3865 fSuperMap
->getVirtualAddress();
3866 else if (fAddressMap
3867 && vm_map_is_64bit(fAddressMap
)
3868 && (sizeof(IOVirtualAddress
) < 8))
3870 OSReportWithBacktrace("IOMemoryMap::getVirtualAddress(0x%qx) called on 64b map; use ::getAddress()", fAddress
);
3872 #endif /* !__LP64__ */
3878 mach_vm_address_t
IOMemoryMap::getAddress()
3883 mach_vm_size_t
IOMemoryMap::getSize()
3887 #endif /* !__LP64__ */
3890 task_t
IOMemoryMap::getAddressTask()
3893 return( fSuperMap
->getAddressTask());
3895 return( fAddressTask
);
3898 IOOptionBits
IOMemoryMap::getMapOptions()
3903 IOMemoryDescriptor
* IOMemoryMap::getMemoryDescriptor()
3908 IOMemoryMap
* IOMemoryMap::copyCompatible(
3909 IOMemoryMap
* newMapping
)
3911 task_t task
= newMapping
->getAddressTask();
3912 mach_vm_address_t toAddress
= newMapping
->fAddress
;
3913 IOOptionBits _options
= newMapping
->fOptions
;
3914 mach_vm_size_t _offset
= newMapping
->fOffset
;
3915 mach_vm_size_t _length
= newMapping
->fLength
;
3917 if( (!task
) || (!fAddressMap
) || (fAddressMap
!= get_task_map(task
)))
3919 if( (fOptions
^ _options
) & kIOMapReadOnly
)
3921 if( (kIOMapDefaultCache
!= (_options
& kIOMapCacheMask
))
3922 && ((fOptions
^ _options
) & kIOMapCacheMask
))
3925 if( (0 == (_options
& kIOMapAnywhere
)) && (fAddress
!= toAddress
))
3928 if( _offset
< fOffset
)
3933 if( (_offset
+ _length
) > fLength
)
3937 if( (fLength
== _length
) && (!_offset
))
3943 newMapping
->fSuperMap
= this;
3944 newMapping
->fOffset
= fOffset
+ _offset
;
3945 newMapping
->fAddress
= fAddress
+ _offset
;
3948 return( newMapping
);
3951 IOReturn
IOMemoryMap::wireRange(
3953 mach_vm_size_t offset
,
3954 mach_vm_size_t length
)
3957 mach_vm_address_t start
= trunc_page_64(fAddress
+ offset
);
3958 mach_vm_address_t end
= round_page_64(fAddress
+ offset
+ length
);
3961 prot
= (kIODirectionOutIn
& options
);
3964 prot
|= VM_PROT_MEMORY_TAG_MAKE(IOMemoryTag(kernel_map
));
3965 kr
= vm_map_wire(fAddressMap
, start
, end
, prot
, FALSE
);
3969 kr
= vm_map_unwire(fAddressMap
, start
, end
, FALSE
);
3978 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
, IOOptionBits _options
)
3979 #else /* !__LP64__ */
3980 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
)
3981 #endif /* !__LP64__ */
3983 IOPhysicalAddress address
;
3987 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
, _options
);
3988 #else /* !__LP64__ */
3989 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
);
3990 #endif /* !__LP64__ */
3996 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3999 #define super OSObject
4001 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4003 void IOMemoryDescriptor::initialize( void )
4005 if( 0 == gIOMemoryLock
)
4006 gIOMemoryLock
= IORecursiveLockAlloc();
4008 gIOLastPage
= IOGetLastPageNumber();
4011 void IOMemoryDescriptor::free( void )
4013 if( _mappings
) _mappings
->release();
4017 IODelete(reserved
, IOMemoryDescriptorReserved
, 1);
4023 IOMemoryMap
* IOMemoryDescriptor::setMapping(
4025 IOVirtualAddress mapAddress
,
4026 IOOptionBits options
)
4028 return (createMappingInTask( intoTask
, mapAddress
,
4029 options
| kIOMapStatic
,
4033 IOMemoryMap
* IOMemoryDescriptor::map(
4034 IOOptionBits options
)
4036 return (createMappingInTask( kernel_task
, 0,
4037 options
| kIOMapAnywhere
,
4042 IOMemoryMap
* IOMemoryDescriptor::map(
4044 IOVirtualAddress atAddress
,
4045 IOOptionBits options
,
4047 IOByteCount length
)
4049 if ((!(kIOMapAnywhere
& options
)) && vm_map_is_64bit(get_task_map(intoTask
)))
4051 OSReportWithBacktrace("IOMemoryDescriptor::map() in 64b task, use ::createMappingInTask()");
4055 return (createMappingInTask(intoTask
, atAddress
,
4056 options
, offset
, length
));
4058 #endif /* !__LP64__ */
4060 IOMemoryMap
* IOMemoryDescriptor::createMappingInTask(
4062 mach_vm_address_t atAddress
,
4063 IOOptionBits options
,
4064 mach_vm_size_t offset
,
4065 mach_vm_size_t length
)
4067 IOMemoryMap
* result
;
4068 IOMemoryMap
* mapping
;
4071 length
= getLength();
4073 mapping
= new IOMemoryMap
;
4076 && !mapping
->init( intoTask
, atAddress
,
4077 options
, offset
, length
)) {
4083 result
= makeMapping(this, intoTask
, (IOVirtualAddress
) mapping
, options
| kIOMap64Bit
, 0, 0);
4089 IOLog("createMappingInTask failed desc %p, addr %qx, options %x, offset %qx, length %llx\n",
4090 this, atAddress
, (uint32_t) options
, offset
, length
);
4096 #ifndef __LP64__ // there is only a 64 bit version for LP64
4097 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
4098 IOOptionBits options
,
4101 return (redirect(newBackingMemory
, options
, (mach_vm_size_t
)offset
));
4105 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
4106 IOOptionBits options
,
4107 mach_vm_size_t offset
)
4109 IOReturn err
= kIOReturnSuccess
;
4110 IOMemoryDescriptor
* physMem
= 0;
4114 if (fAddress
&& fAddressMap
) do
4116 if (((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
4117 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
4123 if (!fRedirUPL
&& fMemory
->_memRef
&& (1 == fMemory
->_memRef
->count
))
4125 upl_size_t size
= round_page(fLength
);
4126 upl_control_flags_t flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
4127 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
4128 | UPL_MEMORY_TAG_MAKE(IOMemoryTag(kernel_map
));
4129 if (KERN_SUCCESS
!= memory_object_iopl_request(fMemory
->_memRef
->entries
[0].entry
, 0, &size
, &fRedirUPL
,
4136 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
4138 physMem
->redirect(0, true);
4142 if (newBackingMemory
)
4144 if (newBackingMemory
!= fMemory
)
4147 if (this != newBackingMemory
->makeMapping(newBackingMemory
, fAddressTask
, (IOVirtualAddress
) this,
4148 options
| kIOMapUnique
| kIOMapReference
| kIOMap64Bit
,
4150 err
= kIOReturnError
;
4154 upl_commit(fRedirUPL
, NULL
, 0);
4155 upl_deallocate(fRedirUPL
);
4158 if ((false) && physMem
)
4159 physMem
->redirect(0, false);
4172 IOMemoryMap
* IOMemoryDescriptor::makeMapping(
4173 IOMemoryDescriptor
* owner
,
4175 IOVirtualAddress __address
,
4176 IOOptionBits options
,
4177 IOByteCount __offset
,
4178 IOByteCount __length
)
4181 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::makeMapping !64bit");
4182 #endif /* !__LP64__ */
4184 IOMemoryDescriptor
* mapDesc
= 0;
4185 IOMemoryMap
* result
= 0;
4188 IOMemoryMap
* mapping
= (IOMemoryMap
*) __address
;
4189 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
4190 mach_vm_size_t length
= mapping
->fLength
;
4192 mapping
->fOffset
= offset
;
4198 if (kIOMapStatic
& options
)
4201 addMapping(mapping
);
4202 mapping
->setMemoryDescriptor(this, 0);
4206 if (kIOMapUnique
& options
)
4209 IOByteCount physLen
;
4211 // if (owner != this) continue;
4213 if (((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
4214 || ((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
4216 phys
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
4217 if (!phys
|| (physLen
< length
))
4220 mapDesc
= IOMemoryDescriptor::withAddressRange(
4221 phys
, length
, getDirection() | kIOMemoryMapperNone
, NULL
);
4225 mapping
->fOffset
= offset
;
4230 // look for a compatible existing mapping
4231 if( (iter
= OSCollectionIterator::withCollection(_mappings
)))
4233 IOMemoryMap
* lookMapping
;
4234 while ((lookMapping
= (IOMemoryMap
*) iter
->getNextObject()))
4236 if ((result
= lookMapping
->copyCompatible(mapping
)))
4239 result
->setMemoryDescriptor(this, offset
);
4245 if (result
|| (options
& kIOMapReference
))
4247 if (result
!= mapping
)
4262 kr
= mapDesc
->doMap( 0, (IOVirtualAddress
*) &mapping
, options
, 0, 0 );
4263 if (kIOReturnSuccess
== kr
)
4266 mapDesc
->addMapping(result
);
4267 result
->setMemoryDescriptor(mapDesc
, offset
);
4285 void IOMemoryDescriptor::addMapping(
4286 IOMemoryMap
* mapping
)
4291 _mappings
= OSSet::withCapacity(1);
4293 _mappings
->setObject( mapping
);
4297 void IOMemoryDescriptor::removeMapping(
4298 IOMemoryMap
* mapping
)
4301 _mappings
->removeObject( mapping
);
4305 // obsolete initializers
4306 // - initWithOptions is the designated initializer
4308 IOMemoryDescriptor::initWithAddress(void * address
,
4310 IODirection direction
)
4316 IOMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
4318 IODirection direction
,
4325 IOMemoryDescriptor::initWithPhysicalAddress(
4326 IOPhysicalAddress address
,
4328 IODirection direction
)
4334 IOMemoryDescriptor::initWithRanges(
4335 IOVirtualRange
* ranges
,
4337 IODirection direction
,
4345 IOMemoryDescriptor::initWithPhysicalRanges( IOPhysicalRange
* ranges
,
4347 IODirection direction
,
4353 void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
4354 IOByteCount
* lengthOfSegment
)
4358 #endif /* !__LP64__ */
4360 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4362 bool IOGeneralMemoryDescriptor::serialize(OSSerialize
* s
) const
4364 OSSymbol
const *keys
[2];
4365 OSObject
*values
[2];
4369 user_addr_t address
;
4372 unsigned int index
, nRanges
;
4375 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
4377 if (s
== NULL
) return false;
4379 array
= OSArray::withCapacity(4);
4380 if (!array
) return (false);
4382 nRanges
= _rangesCount
;
4383 vcopy
= (SerData
*) IOMalloc(sizeof(SerData
) * nRanges
);
4384 if (vcopy
== 0) return false;
4386 keys
[0] = OSSymbol::withCString("address");
4387 keys
[1] = OSSymbol::withCString("length");
4390 values
[0] = values
[1] = 0;
4392 // From this point on we can go to bail.
4394 // Copy the volatile data so we don't have to allocate memory
4395 // while the lock is held.
4397 if (nRanges
== _rangesCount
) {
4398 Ranges vec
= _ranges
;
4399 for (index
= 0; index
< nRanges
; index
++) {
4400 mach_vm_address_t addr
; mach_vm_size_t len
;
4401 getAddrLenForInd(addr
, len
, type
, vec
, index
);
4402 vcopy
[index
].address
= addr
;
4403 vcopy
[index
].length
= len
;
4406 // The descriptor changed out from under us. Give up.
4413 for (index
= 0; index
< nRanges
; index
++)
4415 user_addr_t addr
= vcopy
[index
].address
;
4416 IOByteCount len
= (IOByteCount
) vcopy
[index
].length
;
4417 values
[0] = OSNumber::withNumber(addr
, sizeof(addr
) * 8);
4418 if (values
[0] == 0) {
4422 values
[1] = OSNumber::withNumber(len
, sizeof(len
) * 8);
4423 if (values
[1] == 0) {
4427 OSDictionary
*dict
= OSDictionary::withObjects((const OSObject
**)values
, (const OSSymbol
**)keys
, 2);
4432 array
->setObject(dict
);
4434 values
[0]->release();
4435 values
[1]->release();
4436 values
[0] = values
[1] = 0;
4439 result
= array
->serialize(s
);
4445 values
[0]->release();
4447 values
[1]->release();
4453 IOFree(vcopy
, sizeof(SerData
) * nRanges
);
4458 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4460 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 0);
4462 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 1);
4463 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 2);
4464 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 3);
4465 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 4);
4466 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 5);
4467 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 6);
4468 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 7);
4469 #else /* !__LP64__ */
4470 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 1);
4471 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 2);
4472 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 3);
4473 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 4);
4474 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 5);
4475 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 6);
4476 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 7);
4477 #endif /* !__LP64__ */
4478 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 8);
4479 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 9);
4480 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 10);
4481 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 11);
4482 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 12);
4483 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 13);
4484 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 14);
4485 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 15);
4487 /* ex-inline function implementation */
4489 IOMemoryDescriptor::getPhysicalAddress()
4490 { return( getPhysicalSegment( 0, 0 )); }