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 */
1608 if (_pages
> atop_64(max_mem
)) return false;
1610 dataSize
= computeDataSize(_pages
, /* upls */ count
* 2);
1611 if (!initMemoryEntries(dataSize
, mapper
)) return false;
1612 dataP
= getDataP(_memoryEntries
);
1613 dataP
->fPageCnt
= _pages
;
1615 if ( (kIOMemoryPersistent
& _flags
) && !_memRef
)
1618 err
= memoryReferenceCreate(0, &_memRef
);
1619 if (kIOReturnSuccess
!= err
) return false;
1622 if ((_flags
& kIOMemoryAutoPrepare
)
1623 && prepare() != kIOReturnSuccess
)
1636 void IOGeneralMemoryDescriptor::free()
1638 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1643 reserved
->dp
.memory
= 0;
1646 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
1649 if (_memoryEntries
&& (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
1651 dataP
->fMapper
->iovmUnmapMemory(this, NULL
, dataP
->fMappedBase
, dataP
->fMappedLength
);
1652 dataP
->fMappedBase
= 0;
1657 while (_wireCount
) complete();
1660 if (_memoryEntries
) _memoryEntries
->release();
1662 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
1664 if (kIOMemoryTypeUIO
== type
)
1665 uio_free((uio_t
) _ranges
.v
);
1667 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
1668 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
1669 #endif /* !__LP64__ */
1671 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
1678 if (reserved
->dp
.devicePager
)
1680 // memEntry holds a ref on the device pager which owns reserved
1681 // (IOMemoryDescriptorReserved) so no reserved access after this point
1682 device_pager_deallocate( (memory_object_t
) reserved
->dp
.devicePager
);
1685 IODelete(reserved
, IOMemoryDescriptorReserved
, 1);
1689 if (_memRef
) memoryReferenceRelease(_memRef
);
1690 if (_prepareLock
) IOLockFree(_prepareLock
);
1696 void IOGeneralMemoryDescriptor::unmapFromKernel()
1698 panic("IOGMD::unmapFromKernel deprecated");
1701 void IOGeneralMemoryDescriptor::mapIntoKernel(unsigned rangeIndex
)
1703 panic("IOGMD::mapIntoKernel deprecated");
1705 #endif /* !__LP64__ */
1710 * Get the direction of the transfer.
1712 IODirection
IOMemoryDescriptor::getDirection() const
1717 #endif /* !__LP64__ */
1718 return (IODirection
) (_flags
& kIOMemoryDirectionMask
);
1724 * Get the length of the transfer (over all ranges).
1726 IOByteCount
IOMemoryDescriptor::getLength() const
1731 void IOMemoryDescriptor::setTag( IOOptionBits tag
)
1736 IOOptionBits
IOMemoryDescriptor::getTag( void )
1742 // @@@ gvdl: who is using this API? Seems like a wierd thing to implement.
1744 IOMemoryDescriptor::getSourceSegment( IOByteCount offset
, IOByteCount
* length
)
1746 addr64_t physAddr
= 0;
1748 if( prepare() == kIOReturnSuccess
) {
1749 physAddr
= getPhysicalSegment64( offset
, length
);
1753 return( (IOPhysicalAddress
) physAddr
); // truncated but only page offset is used
1755 #endif /* !__LP64__ */
1757 IOByteCount
IOMemoryDescriptor::readBytes
1758 (IOByteCount offset
, void *bytes
, IOByteCount length
)
1760 addr64_t dstAddr
= CAST_DOWN(addr64_t
, bytes
);
1761 IOByteCount remaining
;
1763 // Assert that this entire I/O is withing the available range
1764 assert(offset
<= _length
);
1765 assert(offset
+ length
<= _length
);
1766 if ((offset
>= _length
)
1767 || ((offset
+ length
) > _length
)) {
1771 if (kIOMemoryThreadSafe
& _flags
)
1774 remaining
= length
= min(length
, _length
- offset
);
1775 while (remaining
) { // (process another target segment?)
1779 srcAddr64
= getPhysicalSegment(offset
, &srcLen
, kIOMemoryMapperNone
);
1783 // Clip segment length to remaining
1784 if (srcLen
> remaining
)
1787 copypv(srcAddr64
, dstAddr
, srcLen
,
1788 cppvPsrc
| cppvNoRefSrc
| cppvFsnk
| cppvKmap
);
1792 remaining
-= srcLen
;
1795 if (kIOMemoryThreadSafe
& _flags
)
1800 return length
- remaining
;
1803 IOByteCount
IOMemoryDescriptor::writeBytes
1804 (IOByteCount inoffset
, const void *bytes
, IOByteCount length
)
1806 addr64_t srcAddr
= CAST_DOWN(addr64_t
, bytes
);
1807 IOByteCount remaining
;
1808 IOByteCount offset
= inoffset
;
1810 // Assert that this entire I/O is withing the available range
1811 assert(offset
<= _length
);
1812 assert(offset
+ length
<= _length
);
1814 assert( !(kIOMemoryPreparedReadOnly
& _flags
) );
1816 if ( (kIOMemoryPreparedReadOnly
& _flags
)
1817 || (offset
>= _length
)
1818 || ((offset
+ length
) > _length
)) {
1822 if (kIOMemoryThreadSafe
& _flags
)
1825 remaining
= length
= min(length
, _length
- offset
);
1826 while (remaining
) { // (process another target segment?)
1830 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1834 // Clip segment length to remaining
1835 if (dstLen
> remaining
)
1838 if (!srcAddr
) bzero_phys(dstAddr64
, dstLen
);
1841 copypv(srcAddr
, (addr64_t
) dstAddr64
, dstLen
,
1842 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
1846 remaining
-= dstLen
;
1849 if (kIOMemoryThreadSafe
& _flags
)
1854 if (!srcAddr
) performOperation(kIOMemoryIncoherentIOFlush
, inoffset
, length
);
1856 return length
- remaining
;
1860 void IOGeneralMemoryDescriptor::setPosition(IOByteCount position
)
1862 panic("IOGMD::setPosition deprecated");
1864 #endif /* !__LP64__ */
1866 static volatile SInt64 gIOMDPreparationID
__attribute__((aligned(8))) = (1ULL << 32);
1869 IOGeneralMemoryDescriptor::getPreparationID( void )
1874 return (kIOPreparationIDUnprepared
);
1876 if (((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical
)
1877 || ((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical64
))
1879 IOMemoryDescriptor::setPreparationID();
1880 return (IOMemoryDescriptor::getPreparationID());
1883 if (!_memoryEntries
|| !(dataP
= getDataP(_memoryEntries
)))
1884 return (kIOPreparationIDUnprepared
);
1886 if (kIOPreparationIDUnprepared
== dataP
->fPreparationID
)
1888 dataP
->fPreparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1890 return (dataP
->fPreparationID
);
1893 IOMemoryDescriptorReserved
* IOMemoryDescriptor::getKernelReserved( void )
1897 reserved
= IONew(IOMemoryDescriptorReserved
, 1);
1899 bzero(reserved
, sizeof(IOMemoryDescriptorReserved
));
1904 void IOMemoryDescriptor::setPreparationID( void )
1906 if (getKernelReserved() && (kIOPreparationIDUnprepared
== reserved
->preparationID
))
1908 #if defined(__ppc__ )
1909 reserved
->preparationID
= gIOMDPreparationID
++;
1911 reserved
->preparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1916 uint64_t IOMemoryDescriptor::getPreparationID( void )
1919 return (reserved
->preparationID
);
1921 return (kIOPreparationIDUnsupported
);
1924 IOReturn
IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1926 IOReturn err
= kIOReturnSuccess
;
1927 DMACommandOps params
;
1928 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
1931 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
1932 op
&= kIOMDDMACommandOperationMask
;
1934 if (kIOMDDMAMap
== op
)
1936 if (dataSize
< sizeof(IOMDDMAMapArgs
))
1937 return kIOReturnUnderrun
;
1939 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
1942 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1944 if (_memoryEntries
&& data
->fMapper
)
1946 bool remap
, keepMap
;
1947 dataP
= getDataP(_memoryEntries
);
1949 if (data
->fMapSpec
.numAddressBits
< dataP
->fDMAMapNumAddressBits
) dataP
->fDMAMapNumAddressBits
= data
->fMapSpec
.numAddressBits
;
1950 if (data
->fMapSpec
.alignment
> dataP
->fDMAMapAlignment
) dataP
->fDMAMapAlignment
= data
->fMapSpec
.alignment
;
1952 keepMap
= (data
->fMapper
== gIOSystemMapper
);
1953 keepMap
&= ((data
->fOffset
== 0) && (data
->fLength
== _length
));
1956 remap
|= (dataP
->fDMAMapNumAddressBits
< 64)
1957 && ((dataP
->fMappedBase
+ _length
) > (1ULL << dataP
->fDMAMapNumAddressBits
));
1958 remap
|= (dataP
->fDMAMapAlignment
> page_size
);
1960 if (remap
|| !dataP
->fMappedBase
)
1962 // if (dataP->fMappedBase) OSReportWithBacktrace("kIOMDDMAMap whole %d remap %d params %d\n", whole, remap, params);
1963 err
= md
->dmaMap(data
->fMapper
, data
->fCommand
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocLength
);
1964 if (keepMap
&& (kIOReturnSuccess
== err
) && !dataP
->fMappedBase
)
1966 dataP
->fMappedBase
= data
->fAlloc
;
1967 dataP
->fMappedLength
= data
->fAllocLength
;
1968 data
->fAllocLength
= 0; // IOMD owns the alloc now
1973 data
->fAlloc
= dataP
->fMappedBase
;
1974 data
->fAllocLength
= 0; // give out IOMD map
1976 data
->fMapContig
= !dataP
->fDiscontig
;
1982 if (kIOMDAddDMAMapSpec
== op
)
1984 if (dataSize
< sizeof(IODMAMapSpecification
))
1985 return kIOReturnUnderrun
;
1987 IODMAMapSpecification
* data
= (IODMAMapSpecification
*) vData
;
1990 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1994 dataP
= getDataP(_memoryEntries
);
1995 if (data
->numAddressBits
< dataP
->fDMAMapNumAddressBits
)
1996 dataP
->fDMAMapNumAddressBits
= data
->numAddressBits
;
1997 if (data
->alignment
> dataP
->fDMAMapAlignment
)
1998 dataP
->fDMAMapAlignment
= data
->alignment
;
2000 return kIOReturnSuccess
;
2003 if (kIOMDGetCharacteristics
== op
) {
2005 if (dataSize
< sizeof(IOMDDMACharacteristics
))
2006 return kIOReturnUnderrun
;
2008 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
2009 data
->fLength
= _length
;
2010 data
->fSGCount
= _rangesCount
;
2011 data
->fPages
= _pages
;
2012 data
->fDirection
= getDirection();
2014 data
->fIsPrepared
= false;
2016 data
->fIsPrepared
= true;
2017 data
->fHighestPage
= _highestPage
;
2020 dataP
= getDataP(_memoryEntries
);
2021 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2022 UInt count
= getNumIOPL(_memoryEntries
, dataP
);
2024 data
->fPageAlign
= (ioplList
[0].fPageOffset
& PAGE_MASK
) | ~PAGE_MASK
;
2028 return kIOReturnSuccess
;
2030 #if IOMD_DEBUG_DMAACTIVE
2031 } else if (kIOMDDMAActive
== op
) {
2032 if (params
) OSIncrementAtomic(&md
->__iomd_reservedA
);
2034 if (md
->__iomd_reservedA
)
2035 OSDecrementAtomic(&md
->__iomd_reservedA
);
2037 panic("kIOMDSetDMAInactive");
2039 #endif /* IOMD_DEBUG_DMAACTIVE */
2041 } else if (kIOMDWalkSegments
!= op
)
2042 return kIOReturnBadArgument
;
2044 // Get the next segment
2045 struct InternalState
{
2046 IOMDDMAWalkSegmentArgs fIO
;
2052 // Find the next segment
2053 if (dataSize
< sizeof(*isP
))
2054 return kIOReturnUnderrun
;
2056 isP
= (InternalState
*) vData
;
2057 UInt offset
= isP
->fIO
.fOffset
;
2058 bool mapped
= isP
->fIO
.fMapped
;
2060 if (IOMapper::gSystem
&& mapped
2061 && (!(kIOMemoryHostOnly
& _flags
))
2062 && (!_memoryEntries
|| !getDataP(_memoryEntries
)->fMappedBase
))
2063 // && (_memoryEntries && !getDataP(_memoryEntries)->fMappedBase))
2066 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
2068 dataP
= getDataP(_memoryEntries
);
2071 IODMAMapSpecification mapSpec
;
2072 bzero(&mapSpec
, sizeof(mapSpec
));
2073 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
2074 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
2075 err
= md
->dmaMap(dataP
->fMapper
, NULL
, &mapSpec
, 0, _length
, &dataP
->fMappedBase
, &dataP
->fMappedLength
);
2076 if (kIOReturnSuccess
!= err
) return (err
);
2080 if (offset
>= _length
)
2081 return (offset
== _length
)? kIOReturnOverrun
: kIOReturnInternalError
;
2083 // Validate the previous offset
2084 UInt ind
, off2Ind
= isP
->fOffset2Index
;
2087 && (offset
== isP
->fNextOffset
|| off2Ind
<= offset
))
2090 ind
= off2Ind
= 0; // Start from beginning
2096 if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
) {
2098 // Physical address based memory descriptor
2099 const IOPhysicalRange
*physP
= (IOPhysicalRange
*) &_ranges
.p
[0];
2101 // Find the range after the one that contains the offset
2103 for (len
= 0; off2Ind
<= offset
; ind
++) {
2104 len
= physP
[ind
].length
;
2108 // Calculate length within range and starting address
2109 length
= off2Ind
- offset
;
2110 address
= physP
[ind
- 1].address
+ len
- length
;
2112 if (true && mapped
&& _memoryEntries
2113 && (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
2115 address
= dataP
->fMappedBase
+ offset
;
2119 // see how far we can coalesce ranges
2120 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
2121 len
= physP
[ind
].length
;
2128 // correct contiguous check overshoot
2133 else if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
) {
2135 // Physical address based memory descriptor
2136 const IOAddressRange
*physP
= (IOAddressRange
*) &_ranges
.v64
[0];
2138 // Find the range after the one that contains the offset
2140 for (len
= 0; off2Ind
<= offset
; ind
++) {
2141 len
= physP
[ind
].length
;
2145 // Calculate length within range and starting address
2146 length
= off2Ind
- offset
;
2147 address
= physP
[ind
- 1].address
+ len
- length
;
2149 if (true && mapped
&& _memoryEntries
2150 && (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
2152 address
= dataP
->fMappedBase
+ offset
;
2156 // see how far we can coalesce ranges
2157 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
2158 len
= physP
[ind
].length
;
2164 // correct contiguous check overshoot
2168 #endif /* !__LP64__ */
2171 panic("IOGMD: not wired for the IODMACommand");
2173 assert(_memoryEntries
);
2175 dataP
= getDataP(_memoryEntries
);
2176 const ioPLBlock
*ioplList
= getIOPLList(dataP
);
2177 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
2178 upl_page_info_t
*pageList
= getPageList(dataP
);
2180 assert(numIOPLs
> 0);
2182 // Scan through iopl info blocks looking for block containing offset
2183 while (ind
< numIOPLs
&& offset
>= ioplList
[ind
].fIOMDOffset
)
2186 // Go back to actual range as search goes past it
2187 ioPLBlock ioplInfo
= ioplList
[ind
- 1];
2188 off2Ind
= ioplInfo
.fIOMDOffset
;
2191 length
= ioplList
[ind
].fIOMDOffset
;
2194 length
-= offset
; // Remainder within iopl
2196 // Subtract offset till this iopl in total list
2199 // If a mapped address is requested and this is a pre-mapped IOPL
2200 // then just need to compute an offset relative to the mapped base.
2201 if (mapped
&& dataP
->fMappedBase
) {
2202 offset
+= (ioplInfo
.fPageOffset
& PAGE_MASK
);
2203 address
= trunc_page_64(dataP
->fMappedBase
) + ptoa_64(ioplInfo
.fMappedPage
) + offset
;
2204 continue; // Done leave do/while(false) now
2207 // The offset is rebased into the current iopl.
2208 // Now add the iopl 1st page offset.
2209 offset
+= ioplInfo
.fPageOffset
;
2211 // For external UPLs the fPageInfo field points directly to
2212 // the upl's upl_page_info_t array.
2213 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
2214 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
2216 pageList
= &pageList
[ioplInfo
.fPageInfo
];
2218 // Check for direct device non-paged memory
2219 if ( ioplInfo
.fFlags
& kIOPLOnDevice
) {
2220 address
= ptoa_64(pageList
->phys_addr
) + offset
;
2221 continue; // Done leave do/while(false) now
2224 // Now we need compute the index into the pageList
2225 UInt pageInd
= atop_32(offset
);
2226 offset
&= PAGE_MASK
;
2228 // Compute the starting address of this segment
2229 IOPhysicalAddress pageAddr
= pageList
[pageInd
].phys_addr
;
2231 panic("!pageList phys_addr");
2234 address
= ptoa_64(pageAddr
) + offset
;
2236 // length is currently set to the length of the remainider of the iopl.
2237 // We need to check that the remainder of the iopl is contiguous.
2238 // This is indicated by pageList[ind].phys_addr being sequential.
2239 IOByteCount contigLength
= PAGE_SIZE
- offset
;
2240 while (contigLength
< length
2241 && ++pageAddr
== pageList
[++pageInd
].phys_addr
)
2243 contigLength
+= PAGE_SIZE
;
2246 if (contigLength
< length
)
2247 length
= contigLength
;
2255 // Update return values and state
2256 isP
->fIO
.fIOVMAddr
= address
;
2257 isP
->fIO
.fLength
= length
;
2259 isP
->fOffset2Index
= off2Ind
;
2260 isP
->fNextOffset
= isP
->fIO
.fOffset
+ length
;
2262 return kIOReturnSuccess
;
2266 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
2269 mach_vm_address_t address
= 0;
2270 mach_vm_size_t length
= 0;
2271 IOMapper
* mapper
= gIOSystemMapper
;
2272 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2274 if (lengthOfSegment
)
2275 *lengthOfSegment
= 0;
2277 if (offset
>= _length
)
2280 // IOMemoryDescriptor::doMap() cannot use getPhysicalSegment() to obtain the page offset, since it must
2281 // support the unwired memory case in IOGeneralMemoryDescriptor, and hibernate_write_image() cannot use
2282 // map()->getVirtualAddress() to obtain the kernel pointer, since it must prevent the memory allocation
2283 // due to IOMemoryMap, so _kIOMemorySourceSegment is a necessary evil until all of this gets cleaned up
2285 if ((options
& _kIOMemorySourceSegment
) && (kIOMemoryTypeUPL
!= type
))
2287 unsigned rangesIndex
= 0;
2288 Ranges vec
= _ranges
;
2289 mach_vm_address_t addr
;
2291 // Find starting address within the vector of ranges
2293 getAddrLenForInd(addr
, length
, type
, vec
, rangesIndex
);
2294 if (offset
< length
)
2296 offset
-= length
; // (make offset relative)
2300 // Now that we have the starting range,
2301 // lets find the last contiguous range
2305 for ( ++rangesIndex
; rangesIndex
< _rangesCount
; rangesIndex
++ ) {
2306 mach_vm_address_t newAddr
;
2307 mach_vm_size_t newLen
;
2309 getAddrLenForInd(newAddr
, newLen
, type
, vec
, rangesIndex
);
2310 if (addr
+ length
!= newAddr
)
2315 address
= (IOPhysicalAddress
) addr
; // Truncate address to 32bit
2319 IOMDDMAWalkSegmentState _state
;
2320 IOMDDMAWalkSegmentArgs
* state
= (IOMDDMAWalkSegmentArgs
*) (void *)&_state
;
2322 state
->fOffset
= offset
;
2323 state
->fLength
= _length
- offset
;
2324 state
->fMapped
= (0 == (options
& kIOMemoryMapperNone
)) && !(_flags
& kIOMemoryHostOnly
);
2326 ret
= dmaCommandOperation(kIOMDFirstSegment
, _state
, sizeof(_state
));
2328 if ((kIOReturnSuccess
!= ret
) && (kIOReturnOverrun
!= ret
))
2329 DEBG("getPhysicalSegment dmaCommandOperation(%lx), %p, offset %qx, addr %qx, len %qx\n",
2330 ret
, this, state
->fOffset
,
2331 state
->fIOVMAddr
, state
->fLength
);
2332 if (kIOReturnSuccess
== ret
)
2334 address
= state
->fIOVMAddr
;
2335 length
= state
->fLength
;
2338 // dmaCommandOperation() does not distinguish between "mapped" and "unmapped" physical memory, even
2339 // with fMapped set correctly, so we must handle the transformation here until this gets cleaned up
2341 if (mapper
&& ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
)))
2343 if ((options
& kIOMemoryMapperNone
) && !(_flags
& kIOMemoryMapperNone
))
2345 addr64_t origAddr
= address
;
2346 IOByteCount origLen
= length
;
2348 address
= mapper
->mapToPhysicalAddress(origAddr
);
2349 length
= page_size
- (address
& (page_size
- 1));
2350 while ((length
< origLen
)
2351 && ((address
+ length
) == mapper
->mapToPhysicalAddress(origAddr
+ length
)))
2352 length
+= page_size
;
2353 if (length
> origLen
)
2362 if (lengthOfSegment
)
2363 *lengthOfSegment
= length
;
2370 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
2372 addr64_t address
= 0;
2374 if (options
& _kIOMemorySourceSegment
)
2376 address
= getSourceSegment(offset
, lengthOfSegment
);
2378 else if (options
& kIOMemoryMapperNone
)
2380 address
= getPhysicalSegment64(offset
, lengthOfSegment
);
2384 address
= getPhysicalSegment(offset
, lengthOfSegment
);
2391 IOGeneralMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2393 return (getPhysicalSegment(offset
, lengthOfSegment
, kIOMemoryMapperNone
));
2397 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2399 addr64_t address
= 0;
2400 IOByteCount length
= 0;
2402 address
= getPhysicalSegment(offset
, lengthOfSegment
, 0);
2404 if (lengthOfSegment
)
2405 length
= *lengthOfSegment
;
2407 if ((address
+ length
) > 0x100000000ULL
)
2409 panic("getPhysicalSegment() out of 32b range 0x%qx, len 0x%lx, class %s",
2410 address
, (long) length
, (getMetaClass())->getClassName());
2413 return ((IOPhysicalAddress
) address
);
2417 IOMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2419 IOPhysicalAddress phys32
;
2422 IOMapper
* mapper
= 0;
2424 phys32
= getPhysicalSegment(offset
, lengthOfSegment
);
2428 if (gIOSystemMapper
)
2429 mapper
= gIOSystemMapper
;
2433 IOByteCount origLen
;
2435 phys64
= mapper
->mapToPhysicalAddress(phys32
);
2436 origLen
= *lengthOfSegment
;
2437 length
= page_size
- (phys64
& (page_size
- 1));
2438 while ((length
< origLen
)
2439 && ((phys64
+ length
) == mapper
->mapToPhysicalAddress(phys32
+ length
)))
2440 length
+= page_size
;
2441 if (length
> origLen
)
2444 *lengthOfSegment
= length
;
2447 phys64
= (addr64_t
) phys32
;
2453 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2455 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, 0));
2459 IOGeneralMemoryDescriptor::getSourceSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2461 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, _kIOMemorySourceSegment
));
2464 void * IOGeneralMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
2465 IOByteCount
* lengthOfSegment
)
2467 if (_task
== kernel_task
)
2468 return (void *) getSourceSegment(offset
, lengthOfSegment
);
2470 panic("IOGMD::getVirtualSegment deprecated");
2474 #endif /* !__LP64__ */
2477 IOMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
2479 IOMemoryDescriptor
*md
= const_cast<IOMemoryDescriptor
*>(this);
2480 DMACommandOps params
;
2483 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
2484 op
&= kIOMDDMACommandOperationMask
;
2486 if (kIOMDGetCharacteristics
== op
) {
2487 if (dataSize
< sizeof(IOMDDMACharacteristics
))
2488 return kIOReturnUnderrun
;
2490 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
2491 data
->fLength
= getLength();
2493 data
->fDirection
= getDirection();
2494 data
->fIsPrepared
= true; // Assume prepared - fails safe
2496 else if (kIOMDWalkSegments
== op
) {
2497 if (dataSize
< sizeof(IOMDDMAWalkSegmentArgs
))
2498 return kIOReturnUnderrun
;
2500 IOMDDMAWalkSegmentArgs
*data
= (IOMDDMAWalkSegmentArgs
*) vData
;
2501 IOByteCount offset
= (IOByteCount
) data
->fOffset
;
2503 IOPhysicalLength length
;
2504 if (data
->fMapped
&& IOMapper::gSystem
)
2505 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
);
2507 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
, kIOMemoryMapperNone
);
2508 data
->fLength
= length
;
2510 else if (kIOMDAddDMAMapSpec
== op
) return kIOReturnUnsupported
;
2511 else if (kIOMDDMAMap
== op
)
2513 if (dataSize
< sizeof(IOMDDMAMapArgs
))
2514 return kIOReturnUnderrun
;
2515 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
2517 if (params
) panic("class %s does not support IODMACommand::kIterateOnly", getMetaClass()->getClassName());
2519 data
->fMapContig
= true;
2520 err
= md
->dmaMap(data
->fMapper
, data
->fCommand
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocLength
);
2523 else return kIOReturnBadArgument
;
2525 return kIOReturnSuccess
;
2529 IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState
,
2530 IOOptionBits
* oldState
)
2532 IOReturn err
= kIOReturnSuccess
;
2534 vm_purgable_t control
;
2539 err
= super::setPurgeable(newState
, oldState
);
2543 if (kIOMemoryThreadSafe
& _flags
)
2547 // Find the appropriate vm_map for the given task
2549 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
2551 err
= kIOReturnNotReady
;
2556 err
= kIOReturnUnsupported
;
2560 curMap
= get_task_map(_task
);
2562 // can only do one range
2563 Ranges vec
= _ranges
;
2564 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2565 mach_vm_address_t addr
;
2567 getAddrLenForInd(addr
, len
, type
, vec
, 0);
2569 err
= purgeableControlBits(newState
, &control
, &state
);
2570 if (kIOReturnSuccess
!= err
)
2572 err
= mach_vm_purgable_control(curMap
, addr
, control
, &state
);
2575 if (kIOReturnSuccess
== err
)
2577 err
= purgeableStateBits(&state
);
2583 if (kIOMemoryThreadSafe
& _flags
)
2590 IOReturn
IOMemoryDescriptor::setPurgeable( IOOptionBits newState
,
2591 IOOptionBits
* oldState
)
2593 IOReturn err
= kIOReturnNotReady
;
2595 if (kIOMemoryThreadSafe
& _flags
) LOCK
;
2596 if (_memRef
) err
= IOGeneralMemoryDescriptor::memoryReferenceSetPurgeable(_memRef
, newState
, oldState
);
2597 if (kIOMemoryThreadSafe
& _flags
) UNLOCK
;
2602 IOReturn
IOMemoryDescriptor::getPageCounts( IOByteCount
* residentPageCount
,
2603 IOByteCount
* dirtyPageCount
)
2605 IOReturn err
= kIOReturnNotReady
;
2607 if (kIOMemoryThreadSafe
& _flags
) LOCK
;
2608 if (_memRef
) err
= IOGeneralMemoryDescriptor::memoryReferenceGetPageCounts(_memRef
, residentPageCount
, dirtyPageCount
);
2611 IOMultiMemoryDescriptor
* mmd
;
2612 IOSubMemoryDescriptor
* smd
;
2613 if ((smd
= OSDynamicCast(IOSubMemoryDescriptor
, this)))
2615 err
= smd
->getPageCounts(residentPageCount
, dirtyPageCount
);
2617 else if ((mmd
= OSDynamicCast(IOMultiMemoryDescriptor
, this)))
2619 err
= mmd
->getPageCounts(residentPageCount
, dirtyPageCount
);
2622 if (kIOMemoryThreadSafe
& _flags
) UNLOCK
;
2628 extern "C" void dcache_incoherent_io_flush64(addr64_t pa
, unsigned int count
);
2629 extern "C" void dcache_incoherent_io_store64(addr64_t pa
, unsigned int count
);
2631 static void SetEncryptOp(addr64_t pa
, unsigned int count
)
2635 page
= atop_64(round_page_64(pa
));
2636 end
= atop_64(trunc_page_64(pa
+ count
));
2637 for (; page
< end
; page
++)
2639 pmap_clear_noencrypt(page
);
2643 static void ClearEncryptOp(addr64_t pa
, unsigned int count
)
2647 page
= atop_64(round_page_64(pa
));
2648 end
= atop_64(trunc_page_64(pa
+ count
));
2649 for (; page
< end
; page
++)
2651 pmap_set_noencrypt(page
);
2655 IOReturn
IOMemoryDescriptor::performOperation( IOOptionBits options
,
2656 IOByteCount offset
, IOByteCount length
)
2658 IOByteCount remaining
;
2660 void (*func
)(addr64_t pa
, unsigned int count
) = 0;
2664 case kIOMemoryIncoherentIOFlush
:
2665 func
= &dcache_incoherent_io_flush64
;
2667 case kIOMemoryIncoherentIOStore
:
2668 func
= &dcache_incoherent_io_store64
;
2671 case kIOMemorySetEncrypted
:
2672 func
= &SetEncryptOp
;
2674 case kIOMemoryClearEncrypted
:
2675 func
= &ClearEncryptOp
;
2680 return (kIOReturnUnsupported
);
2682 if (kIOMemoryThreadSafe
& _flags
)
2686 remaining
= length
= min(length
, getLength() - offset
);
2688 // (process another target segment?)
2693 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
2697 // Clip segment length to remaining
2698 if (dstLen
> remaining
)
2701 (*func
)(dstAddr64
, dstLen
);
2704 remaining
-= dstLen
;
2707 if (kIOMemoryThreadSafe
& _flags
)
2710 return (remaining
? kIOReturnUnderrun
: kIOReturnSuccess
);
2713 #if defined(__i386__) || defined(__x86_64__)
2715 #define io_kernel_static_start vm_kernel_stext
2716 #define io_kernel_static_end vm_kernel_etext
2719 #error io_kernel_static_end is undefined for this architecture
2722 static kern_return_t
2723 io_get_kernel_static_upl(
2726 upl_size_t
*upl_size
,
2728 upl_page_info_array_t page_list
,
2729 unsigned int *count
,
2730 ppnum_t
*highest_page
)
2732 unsigned int pageCount
, page
;
2734 ppnum_t highestPage
= 0;
2736 pageCount
= atop_32(*upl_size
);
2737 if (pageCount
> *count
)
2742 for (page
= 0; page
< pageCount
; page
++)
2744 phys
= pmap_find_phys(kernel_pmap
, ((addr64_t
)offset
) + ptoa_64(page
));
2747 page_list
[page
].phys_addr
= phys
;
2748 page_list
[page
].pageout
= 0;
2749 page_list
[page
].absent
= 0;
2750 page_list
[page
].dirty
= 0;
2751 page_list
[page
].precious
= 0;
2752 page_list
[page
].device
= 0;
2753 if (phys
> highestPage
)
2757 *highest_page
= highestPage
;
2759 return ((page
>= pageCount
) ? kIOReturnSuccess
: kIOReturnVMError
);
2762 IOReturn
IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection
)
2764 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2765 IOReturn error
= kIOReturnCannotWire
;
2767 upl_page_info_array_t pageInfo
;
2770 assert(kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
);
2772 if ((kIODirectionOutIn
& forDirection
) == kIODirectionNone
)
2773 forDirection
= (IODirection
) (forDirection
| getDirection());
2775 upl_control_flags_t uplFlags
; // This Mem Desc's default flags for upl creation
2776 switch (kIODirectionOutIn
& forDirection
)
2778 case kIODirectionOut
:
2779 // Pages do not need to be marked as dirty on commit
2780 uplFlags
= UPL_COPYOUT_FROM
;
2783 case kIODirectionIn
:
2785 uplFlags
= 0; // i.e. ~UPL_COPYOUT_FROM
2791 if ((kIOMemoryPreparedReadOnly
& _flags
) && !(UPL_COPYOUT_FROM
& uplFlags
))
2793 OSReportWithBacktrace("IOMemoryDescriptor 0x%lx prepared read only", VM_KERNEL_ADDRPERM(this));
2794 error
= kIOReturnNotWritable
;
2796 else error
= kIOReturnSuccess
;
2800 dataP
= getDataP(_memoryEntries
);
2802 mapper
= dataP
->fMapper
;
2803 dataP
->fMappedBase
= 0;
2805 uplFlags
|= UPL_SET_IO_WIRE
| UPL_SET_LITE
;
2806 uplFlags
|= UPL_MEMORY_TAG_MAKE(IOMemoryTag(kernel_map
));
2808 if (kIODirectionPrepareToPhys32
& forDirection
)
2810 if (!mapper
) uplFlags
|= UPL_NEED_32BIT_ADDR
;
2811 if (dataP
->fDMAMapNumAddressBits
> 32) dataP
->fDMAMapNumAddressBits
= 32;
2813 if (kIODirectionPrepareNoFault
& forDirection
) uplFlags
|= UPL_REQUEST_NO_FAULT
;
2814 if (kIODirectionPrepareNoZeroFill
& forDirection
) uplFlags
|= UPL_NOZEROFILLIO
;
2815 if (kIODirectionPrepareNonCoherent
& forDirection
) uplFlags
|= UPL_REQUEST_FORCE_COHERENCY
;
2819 // Note that appendBytes(NULL) zeros the data up to the desired length
2820 // and the length parameter is an unsigned int
2821 size_t uplPageSize
= dataP
->fPageCnt
* sizeof(upl_page_info_t
);
2822 if (uplPageSize
> ((unsigned int)uplPageSize
)) return (kIOReturnNoMemory
);
2823 if (!_memoryEntries
->appendBytes(0, uplPageSize
)) return (kIOReturnNoMemory
);
2826 // Find the appropriate vm_map for the given task
2828 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
)) curMap
= 0;
2829 else curMap
= get_task_map(_task
);
2831 // Iterate over the vector of virtual ranges
2832 Ranges vec
= _ranges
;
2833 unsigned int pageIndex
= 0;
2834 IOByteCount mdOffset
= 0;
2835 ppnum_t highestPage
= 0;
2837 IOMemoryEntry
* memRefEntry
= 0;
2838 if (_memRef
) memRefEntry
= &_memRef
->entries
[0];
2840 for (UInt range
= 0; range
< _rangesCount
; range
++) {
2842 mach_vm_address_t startPage
;
2843 mach_vm_size_t numBytes
;
2844 ppnum_t highPage
= 0;
2846 // Get the startPage address and length of vec[range]
2847 getAddrLenForInd(startPage
, numBytes
, type
, vec
, range
);
2848 iopl
.fPageOffset
= startPage
& PAGE_MASK
;
2849 numBytes
+= iopl
.fPageOffset
;
2850 startPage
= trunc_page_64(startPage
);
2853 iopl
.fMappedPage
= mapBase
+ pageIndex
;
2855 iopl
.fMappedPage
= 0;
2857 // Iterate over the current range, creating UPLs
2859 vm_address_t kernelStart
= (vm_address_t
) startPage
;
2861 if (curMap
) theMap
= curMap
;
2868 assert(_task
== kernel_task
);
2869 theMap
= IOPageableMapForAddress(kernelStart
);
2872 // ioplFlags is an in/out parameter
2873 upl_control_flags_t ioplFlags
= uplFlags
;
2874 dataP
= getDataP(_memoryEntries
);
2875 pageInfo
= getPageList(dataP
);
2876 upl_page_list_ptr_t baseInfo
= &pageInfo
[pageIndex
];
2878 upl_size_t ioplSize
= round_page(numBytes
);
2879 unsigned int numPageInfo
= atop_32(ioplSize
);
2881 if ((theMap
== kernel_map
)
2882 && (kernelStart
>= io_kernel_static_start
)
2883 && (kernelStart
< io_kernel_static_end
)) {
2884 error
= io_get_kernel_static_upl(theMap
,
2893 memory_object_offset_t entryOffset
;
2895 entryOffset
= mdOffset
;
2896 entryOffset
= (entryOffset
- iopl
.fPageOffset
- memRefEntry
->offset
);
2897 if (entryOffset
>= memRefEntry
->size
) {
2899 if (memRefEntry
>= &_memRef
->entries
[_memRef
->count
]) panic("memRefEntry");
2902 if (ioplSize
> (memRefEntry
->size
- entryOffset
)) ioplSize
= (memRefEntry
->size
- entryOffset
);
2903 error
= memory_object_iopl_request(memRefEntry
->entry
,
2913 error
= vm_map_create_upl(theMap
,
2915 (upl_size_t
*)&ioplSize
,
2923 if (error
!= KERN_SUCCESS
)
2927 highPage
= upl_get_highest_page(iopl
.fIOPL
);
2928 if (highPage
> highestPage
)
2929 highestPage
= highPage
;
2931 error
= kIOReturnCannotWire
;
2933 if (baseInfo
->device
) {
2935 iopl
.fFlags
= kIOPLOnDevice
;
2941 iopl
.fIOMDOffset
= mdOffset
;
2942 iopl
.fPageInfo
= pageIndex
;
2943 if (mapper
&& pageIndex
&& (page_mask
& (mdOffset
+ iopl
.fPageOffset
))) dataP
->fDiscontig
= true;
2946 // used to remove the upl for auto prepares here, for some errant code
2947 // that freed memory before the descriptor pointing at it
2948 if ((_flags
& kIOMemoryAutoPrepare
) && iopl
.fIOPL
)
2950 upl_commit(iopl
.fIOPL
, 0, 0);
2951 upl_deallocate(iopl
.fIOPL
);
2956 if (!_memoryEntries
->appendBytes(&iopl
, sizeof(iopl
))) {
2957 // Clean up partial created and unsaved iopl
2959 upl_abort(iopl
.fIOPL
, 0);
2960 upl_deallocate(iopl
.fIOPL
);
2966 // Check for a multiple iopl's in one virtual range
2967 pageIndex
+= numPageInfo
;
2968 mdOffset
-= iopl
.fPageOffset
;
2969 if (ioplSize
< numBytes
) {
2970 numBytes
-= ioplSize
;
2971 startPage
+= ioplSize
;
2972 mdOffset
+= ioplSize
;
2973 iopl
.fPageOffset
= 0;
2974 if (mapper
) iopl
.fMappedPage
= mapBase
+ pageIndex
;
2977 mdOffset
+= numBytes
;
2983 _highestPage
= highestPage
;
2985 if (UPL_COPYOUT_FROM
& uplFlags
) _flags
|= kIOMemoryPreparedReadOnly
;
2987 if ((kIOTracking
& gIOKitDebug
)
2988 //&& !(_flags & kIOMemoryAutoPrepare)
2991 dataP
= getDataP(_memoryEntries
);
2993 IOTrackingAdd(gIOWireTracking
, &dataP
->fWireTracking
, ptoa(_pages
), false);
2997 return kIOReturnSuccess
;
3001 dataP
= getDataP(_memoryEntries
);
3002 UInt done
= getNumIOPL(_memoryEntries
, dataP
);
3003 ioPLBlock
*ioplList
= getIOPLList(dataP
);
3005 for (UInt range
= 0; range
< done
; range
++)
3007 if (ioplList
[range
].fIOPL
) {
3008 upl_abort(ioplList
[range
].fIOPL
, 0);
3009 upl_deallocate(ioplList
[range
].fIOPL
);
3012 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
3015 if (error
== KERN_FAILURE
)
3016 error
= kIOReturnCannotWire
;
3017 else if (error
== KERN_MEMORY_ERROR
)
3018 error
= kIOReturnNoResources
;
3023 bool IOGeneralMemoryDescriptor::initMemoryEntries(size_t size
, IOMapper
* mapper
)
3026 unsigned dataSize
= size
;
3028 if (!_memoryEntries
) {
3029 _memoryEntries
= OSData::withCapacity(dataSize
);
3030 if (!_memoryEntries
)
3033 else if (!_memoryEntries
->initWithCapacity(dataSize
))
3036 _memoryEntries
->appendBytes(0, computeDataSize(0, 0));
3037 dataP
= getDataP(_memoryEntries
);
3039 if (mapper
== kIOMapperWaitSystem
) {
3040 IOMapper::checkForSystemMapper();
3041 mapper
= IOMapper::gSystem
;
3043 dataP
->fMapper
= mapper
;
3044 dataP
->fPageCnt
= 0;
3045 dataP
->fMappedBase
= 0;
3046 dataP
->fDMAMapNumAddressBits
= 64;
3047 dataP
->fDMAMapAlignment
= 0;
3048 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
3049 dataP
->fDiscontig
= false;
3050 dataP
->fCompletionError
= false;
3055 IOReturn
IOMemoryDescriptor::dmaMap(
3057 IODMACommand
* command
,
3058 const IODMAMapSpecification
* mapSpec
,
3061 uint64_t * mapAddress
,
3062 uint64_t * mapLength
)
3065 uint32_t mapOptions
;
3068 mapOptions
|= kIODMAMapReadAccess
;
3069 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
3071 ret
= mapper
->iovmMapMemory(this, offset
, length
, mapOptions
,
3072 mapSpec
, command
, NULL
, mapAddress
, mapLength
);
3077 IOReturn
IOGeneralMemoryDescriptor::dmaMap(
3079 IODMACommand
* command
,
3080 const IODMAMapSpecification
* mapSpec
,
3083 uint64_t * mapAddress
,
3084 uint64_t * mapLength
)
3086 IOReturn err
= kIOReturnSuccess
;
3088 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3091 if (kIOMemoryHostOnly
& _flags
) return (kIOReturnSuccess
);
3093 if ((type
== kIOMemoryTypePhysical
) || (type
== kIOMemoryTypePhysical64
)
3094 || offset
|| (length
!= _length
))
3096 err
= super::dmaMap(mapper
, command
, mapSpec
, offset
, length
, mapAddress
, mapLength
);
3098 else if (_memoryEntries
&& _pages
&& (dataP
= getDataP(_memoryEntries
)))
3100 const ioPLBlock
* ioplList
= getIOPLList(dataP
);
3101 upl_page_info_t
* pageList
;
3102 uint32_t mapOptions
= 0;
3104 IODMAMapSpecification mapSpec
;
3105 bzero(&mapSpec
, sizeof(mapSpec
));
3106 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
3107 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
3109 // For external UPLs the fPageInfo field points directly to
3110 // the upl's upl_page_info_t array.
3111 if (ioplList
->fFlags
& kIOPLExternUPL
)
3113 pageList
= (upl_page_info_t
*) ioplList
->fPageInfo
;
3114 mapOptions
|= kIODMAMapPagingPath
;
3116 else pageList
= getPageList(dataP
);
3118 if ((_length
== ptoa_64(_pages
)) && !(page_mask
& ioplList
->fPageOffset
))
3120 mapOptions
|= kIODMAMapPageListFullyOccupied
;
3123 mapOptions
|= kIODMAMapReadAccess
;
3124 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
3126 // Check for direct device non-paged memory
3127 if (ioplList
->fFlags
& kIOPLOnDevice
) mapOptions
|= kIODMAMapPhysicallyContiguous
;
3129 IODMAMapPageList dmaPageList
=
3131 .pageOffset
= ioplList
->fPageOffset
& page_mask
,
3132 .pageListCount
= _pages
,
3133 .pageList
= &pageList
[0]
3135 err
= mapper
->iovmMapMemory(this, offset
, length
, mapOptions
, &mapSpec
,
3136 command
, &dmaPageList
, mapAddress
, mapLength
);
3145 * Prepare the memory for an I/O transfer. This involves paging in
3146 * the memory, if necessary, and wiring it down for the duration of
3147 * the transfer. The complete() method completes the processing of
3148 * the memory after the I/O transfer finishes. This method needn't
3149 * called for non-pageable memory.
3152 IOReturn
IOGeneralMemoryDescriptor::prepare(IODirection forDirection
)
3154 IOReturn error
= kIOReturnSuccess
;
3155 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3157 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
3158 return kIOReturnSuccess
;
3161 IOLockLock(_prepareLock
);
3163 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
)
3165 error
= wireVirtual(forDirection
);
3168 if (kIOReturnSuccess
== error
)
3170 if (1 == ++_wireCount
)
3172 if (kIOMemoryClearEncrypt
& _flags
)
3174 performOperation(kIOMemoryClearEncrypted
, 0, _length
);
3180 IOLockUnlock(_prepareLock
);
3188 * Complete processing of the memory after an I/O transfer finishes.
3189 * This method should not be called unless a prepare was previously
3190 * issued; the prepare() and complete() must occur in pairs, before
3191 * before and after an I/O transfer involving pageable memory.
3194 IOReturn
IOGeneralMemoryDescriptor::complete(IODirection forDirection
)
3196 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3199 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
3200 return kIOReturnSuccess
;
3203 IOLockLock(_prepareLock
);
3207 if ((kIODirectionCompleteWithError
& forDirection
)
3208 && (dataP
= getDataP(_memoryEntries
)))
3209 dataP
->fCompletionError
= true;
3213 if ((kIOMemoryClearEncrypt
& _flags
) && (1 == _wireCount
))
3215 performOperation(kIOMemorySetEncrypted
, 0, _length
);
3219 if (!_wireCount
|| (kIODirectionCompleteWithDataValid
& forDirection
))
3221 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3222 dataP
= getDataP(_memoryEntries
);
3223 ioPLBlock
*ioplList
= getIOPLList(dataP
);
3224 UInt ind
, count
= getNumIOPL(_memoryEntries
, dataP
);
3228 // kIODirectionCompleteWithDataValid & forDirection
3229 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
)
3231 for (ind
= 0; ind
< count
; ind
++)
3233 if (ioplList
[ind
].fIOPL
) iopl_valid_data(ioplList
[ind
].fIOPL
);
3239 #if IOMD_DEBUG_DMAACTIVE
3240 if (__iomd_reservedA
) panic("complete() while dma active");
3241 #endif /* IOMD_DEBUG_DMAACTIVE */
3243 if (dataP
->fMappedBase
) {
3244 dataP
->fMapper
->iovmUnmapMemory(this, NULL
, dataP
->fMappedBase
, dataP
->fMappedLength
);
3245 dataP
->fMappedBase
= 0;
3247 // Only complete iopls that we created which are for TypeVirtual
3248 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) {
3250 if ((kIOTracking
& gIOKitDebug
)
3251 //&& !(_flags & kIOMemoryAutoPrepare)
3254 IOTrackingRemove(gIOWireTracking
, &dataP
->fWireTracking
, ptoa(_pages
));
3257 for (ind
= 0; ind
< count
; ind
++)
3258 if (ioplList
[ind
].fIOPL
) {
3259 if (dataP
->fCompletionError
)
3260 upl_abort(ioplList
[ind
].fIOPL
, 0 /*!UPL_ABORT_DUMP_PAGES*/);
3262 upl_commit(ioplList
[ind
].fIOPL
, 0, 0);
3263 upl_deallocate(ioplList
[ind
].fIOPL
);
3265 } else if (kIOMemoryTypeUPL
== type
) {
3266 upl_set_referenced(ioplList
[0].fIOPL
, false);
3269 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
3271 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
3277 IOLockUnlock(_prepareLock
);
3279 return kIOReturnSuccess
;
3282 IOReturn
IOGeneralMemoryDescriptor::doMap(
3283 vm_map_t __addressMap
,
3284 IOVirtualAddress
* __address
,
3285 IOOptionBits options
,
3286 IOByteCount __offset
,
3287 IOByteCount __length
)
3290 if (!(kIOMap64Bit
& options
)) panic("IOGeneralMemoryDescriptor::doMap !64bit");
3291 #endif /* !__LP64__ */
3295 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
3296 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3297 mach_vm_size_t length
= mapping
->fLength
;
3299 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3300 Ranges vec
= _ranges
;
3302 mach_vm_address_t range0Addr
= 0;
3303 mach_vm_size_t range0Len
= 0;
3305 if ((offset
>= _length
) || ((offset
+ length
) > _length
))
3306 return( kIOReturnBadArgument
);
3309 getAddrLenForInd(range0Addr
, range0Len
, type
, vec
, 0);
3311 // mapping source == dest? (could be much better)
3313 && (mapping
->fAddressTask
== _task
)
3314 && (mapping
->fAddressMap
== get_task_map(_task
))
3315 && (options
& kIOMapAnywhere
)
3316 && (1 == _rangesCount
)
3319 && (length
<= range0Len
))
3321 mapping
->fAddress
= range0Addr
;
3322 mapping
->fOptions
|= kIOMapStatic
;
3324 return( kIOReturnSuccess
);
3329 IOOptionBits createOptions
= 0;
3330 if (!(kIOMapReadOnly
& options
))
3332 createOptions
|= kIOMemoryReferenceWrite
;
3333 #if DEVELOPMENT || DEBUG
3334 if (kIODirectionOut
== (kIODirectionOutIn
& _flags
))
3336 OSReportWithBacktrace("warning: creating writable mapping from IOMemoryDescriptor(kIODirectionOut) - use kIOMapReadOnly or change direction");
3340 err
= memoryReferenceCreate(createOptions
, &_memRef
);
3341 if (kIOReturnSuccess
!= err
) return (err
);
3344 memory_object_t pager
;
3345 pager
= (memory_object_t
) (reserved
? reserved
->dp
.devicePager
: 0);
3347 // <upl_transpose //
3348 if ((kIOMapReference
|kIOMapUnique
) == ((kIOMapReference
|kIOMapUnique
) & options
))
3354 upl_control_flags_t flags
;
3355 unsigned int lock_count
;
3357 if (!_memRef
|| (1 != _memRef
->count
))
3359 err
= kIOReturnNotReadable
;
3363 size
= round_page(mapping
->fLength
);
3364 flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3365 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
3366 | UPL_MEMORY_TAG_MAKE(IOMemoryTag(kernel_map
));
3368 if (KERN_SUCCESS
!= memory_object_iopl_request(_memRef
->entries
[0].entry
, 0, &size
, &redirUPL2
,
3373 for (lock_count
= 0;
3374 IORecursiveLockHaveLock(gIOMemoryLock
);
3378 err
= upl_transpose(redirUPL2
, mapping
->fRedirUPL
);
3385 if (kIOReturnSuccess
!= err
)
3387 IOLog("upl_transpose(%x)\n", err
);
3388 err
= kIOReturnSuccess
;
3393 upl_commit(redirUPL2
, NULL
, 0);
3394 upl_deallocate(redirUPL2
);
3398 // swap the memEntries since they now refer to different vm_objects
3399 IOMemoryReference
* me
= _memRef
;
3400 _memRef
= mapping
->fMemory
->_memRef
;
3401 mapping
->fMemory
->_memRef
= me
;
3404 err
= populateDevicePager( pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
3408 // upl_transpose> //
3411 err
= memoryReferenceMap(_memRef
, mapping
->fAddressMap
, offset
, length
, options
, &mapping
->fAddress
);
3413 if (err
== KERN_SUCCESS
) IOTrackingAdd(gIOMapTracking
, &mapping
->fTracking
, length
, false);
3415 if ((err
== KERN_SUCCESS
) && pager
)
3417 err
= populateDevicePager(pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
3419 if (err
!= KERN_SUCCESS
) doUnmap(mapping
->fAddressMap
, (IOVirtualAddress
) mapping
, 0);
3420 else if (kIOMapDefaultCache
== (options
& kIOMapCacheMask
))
3422 mapping
->fOptions
|= ((_flags
& kIOMemoryBufferCacheMask
) >> kIOMemoryBufferCacheShift
);
3430 IOReturn
IOGeneralMemoryDescriptor::doUnmap(
3431 vm_map_t addressMap
,
3432 IOVirtualAddress __address
,
3433 IOByteCount __length
)
3435 return (super::doUnmap(addressMap
, __address
, __length
));
3438 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3441 #define super OSObject
3443 OSDefineMetaClassAndStructors( IOMemoryMap
, OSObject
)
3445 OSMetaClassDefineReservedUnused(IOMemoryMap
, 0);
3446 OSMetaClassDefineReservedUnused(IOMemoryMap
, 1);
3447 OSMetaClassDefineReservedUnused(IOMemoryMap
, 2);
3448 OSMetaClassDefineReservedUnused(IOMemoryMap
, 3);
3449 OSMetaClassDefineReservedUnused(IOMemoryMap
, 4);
3450 OSMetaClassDefineReservedUnused(IOMemoryMap
, 5);
3451 OSMetaClassDefineReservedUnused(IOMemoryMap
, 6);
3452 OSMetaClassDefineReservedUnused(IOMemoryMap
, 7);
3454 /* ex-inline function implementation */
3455 IOPhysicalAddress
IOMemoryMap::getPhysicalAddress()
3456 { return( getPhysicalSegment( 0, 0 )); }
3458 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3460 bool IOMemoryMap::init(
3462 mach_vm_address_t toAddress
,
3463 IOOptionBits _options
,
3464 mach_vm_size_t _offset
,
3465 mach_vm_size_t _length
)
3473 fAddressMap
= get_task_map(intoTask
);
3476 vm_map_reference(fAddressMap
);
3478 fAddressTask
= intoTask
;
3479 fOptions
= _options
;
3482 fAddress
= toAddress
;
3487 bool IOMemoryMap::setMemoryDescriptor(IOMemoryDescriptor
* _memory
, mach_vm_size_t _offset
)
3494 if( (_offset
+ fLength
) > _memory
->getLength())
3502 if (fMemory
!= _memory
)
3503 fMemory
->removeMapping(this);
3511 IOReturn
IOMemoryDescriptor::doMap(
3512 vm_map_t __addressMap
,
3513 IOVirtualAddress
* __address
,
3514 IOOptionBits options
,
3515 IOByteCount __offset
,
3516 IOByteCount __length
)
3518 return (kIOReturnUnsupported
);
3521 IOReturn
IOMemoryDescriptor::handleFault(
3523 mach_vm_size_t sourceOffset
,
3524 mach_vm_size_t length
)
3526 if( kIOMemoryRedirected
& _flags
)
3529 IOLog("sleep mem redirect %p, %qx\n", this, sourceOffset
);
3533 } while( kIOMemoryRedirected
& _flags
);
3535 return (kIOReturnSuccess
);
3538 IOReturn
IOMemoryDescriptor::populateDevicePager(
3540 vm_map_t addressMap
,
3541 mach_vm_address_t address
,
3542 mach_vm_size_t sourceOffset
,
3543 mach_vm_size_t length
,
3544 IOOptionBits options
)
3546 IOReturn err
= kIOReturnSuccess
;
3547 memory_object_t pager
= (memory_object_t
) _pager
;
3548 mach_vm_size_t size
;
3549 mach_vm_size_t bytes
;
3550 mach_vm_size_t page
;
3551 mach_vm_size_t pageOffset
;
3552 mach_vm_size_t pagerOffset
;
3553 IOPhysicalLength segLen
, chunk
;
3557 type
= _flags
& kIOMemoryTypeMask
;
3559 if (reserved
->dp
.pagerContig
)
3565 physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
);
3567 pageOffset
= physAddr
- trunc_page_64( physAddr
);
3568 pagerOffset
= sourceOffset
;
3570 size
= length
+ pageOffset
;
3571 physAddr
-= pageOffset
;
3573 segLen
+= pageOffset
;
3577 // in the middle of the loop only map whole pages
3578 if( segLen
>= bytes
) segLen
= bytes
;
3579 else if (segLen
!= trunc_page(segLen
)) err
= kIOReturnVMError
;
3580 if (physAddr
!= trunc_page_64(physAddr
)) err
= kIOReturnBadArgument
;
3582 if (kIOReturnSuccess
!= err
) break;
3584 #if DEBUG || DEVELOPMENT
3585 if ((kIOMemoryTypeUPL
!= type
)
3586 && pmap_has_managed_page(atop_64(physAddr
), atop_64(physAddr
+ segLen
- 1)))
3588 OSReportWithBacktrace("IOMemoryDescriptor physical with managed page 0x%qx:0x%qx", physAddr
, segLen
);
3590 #endif /* DEBUG || DEVELOPMENT */
3592 chunk
= (reserved
->dp
.pagerContig
? round_page(segLen
) : page_size
);
3594 (page
< segLen
) && (KERN_SUCCESS
== err
);
3597 err
= device_pager_populate_object(pager
, pagerOffset
,
3598 (ppnum_t
)(atop_64(physAddr
+ page
)), chunk
);
3599 pagerOffset
+= chunk
;
3602 assert (KERN_SUCCESS
== err
);
3605 // This call to vm_fault causes an early pmap level resolution
3606 // of the mappings created above for kernel mappings, since
3607 // faulting in later can't take place from interrupt level.
3608 if ((addressMap
== kernel_map
) && !(kIOMemoryRedirected
& _flags
))
3610 vm_fault(addressMap
,
3611 (vm_map_offset_t
)trunc_page_64(address
),
3612 VM_PROT_READ
|VM_PROT_WRITE
,
3613 FALSE
, THREAD_UNINT
, NULL
,
3614 (vm_map_offset_t
)0);
3617 sourceOffset
+= segLen
- pageOffset
;
3622 while (bytes
&& (physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
)));
3625 err
= kIOReturnBadArgument
;
3630 IOReturn
IOMemoryDescriptor::doUnmap(
3631 vm_map_t addressMap
,
3632 IOVirtualAddress __address
,
3633 IOByteCount __length
)
3636 IOMemoryMap
* mapping
;
3637 mach_vm_address_t address
;
3638 mach_vm_size_t length
;
3640 if (__length
) panic("doUnmap");
3642 mapping
= (IOMemoryMap
*) __address
;
3643 addressMap
= mapping
->fAddressMap
;
3644 address
= mapping
->fAddress
;
3645 length
= mapping
->fLength
;
3647 if (kIOMapOverwrite
& mapping
->fOptions
) err
= KERN_SUCCESS
;
3650 if ((addressMap
== kernel_map
) && (kIOMemoryBufferPageable
& _flags
))
3651 addressMap
= IOPageableMapForAddress( address
);
3653 if( kIOLogMapping
& gIOKitDebug
) IOLog("IOMemoryDescriptor::doUnmap map %p, 0x%qx:0x%qx\n",
3654 addressMap
, address
, length
);
3656 err
= mach_vm_deallocate( addressMap
, address
, length
);
3660 IOTrackingRemove(gIOMapTracking
, &mapping
->fTracking
, length
);
3666 IOReturn
IOMemoryDescriptor::redirect( task_t safeTask
, bool doRedirect
)
3668 IOReturn err
= kIOReturnSuccess
;
3669 IOMemoryMap
* mapping
= 0;
3675 _flags
|= kIOMemoryRedirected
;
3677 _flags
&= ~kIOMemoryRedirected
;
3680 if( (iter
= OSCollectionIterator::withCollection( _mappings
))) {
3682 memory_object_t pager
;
3685 pager
= (memory_object_t
) reserved
->dp
.devicePager
;
3687 pager
= MACH_PORT_NULL
;
3689 while( (mapping
= (IOMemoryMap
*) iter
->getNextObject()))
3691 mapping
->redirect( safeTask
, doRedirect
);
3692 if (!doRedirect
&& !safeTask
&& pager
&& (kernel_map
== mapping
->fAddressMap
))
3694 err
= populateDevicePager(pager
, mapping
->fAddressMap
, mapping
->fAddress
, mapping
->fOffset
, mapping
->fLength
, kIOMapDefaultCache
);
3710 // temporary binary compatibility
3711 IOSubMemoryDescriptor
* subMem
;
3712 if( (subMem
= OSDynamicCast( IOSubMemoryDescriptor
, this)))
3713 err
= subMem
->redirect( safeTask
, doRedirect
);
3715 err
= kIOReturnSuccess
;
3716 #endif /* !__LP64__ */
3721 IOReturn
IOMemoryMap::redirect( task_t safeTask
, bool doRedirect
)
3723 IOReturn err
= kIOReturnSuccess
;
3726 // err = ((IOMemoryMap *)superMap)->redirect( safeTask, doRedirect );
3738 if ((!safeTask
|| (get_task_map(safeTask
) != fAddressMap
))
3739 && (0 == (fOptions
& kIOMapStatic
)))
3741 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3742 err
= kIOReturnSuccess
;
3744 IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect
, this, fAddress
, fLength
, fAddressMap
);
3747 else if (kIOMapWriteCombineCache
== (fOptions
& kIOMapCacheMask
))
3749 IOOptionBits newMode
;
3750 newMode
= (fOptions
& ~kIOMapCacheMask
) | (doRedirect
? kIOMapInhibitCache
: kIOMapWriteCombineCache
);
3751 IOProtectCacheMode(fAddressMap
, fAddress
, fLength
, newMode
);
3758 if ((((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3759 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3761 && (doRedirect
!= (0 != (fMemory
->_flags
& kIOMemoryRedirected
))))
3762 fMemory
->redirect(safeTask
, doRedirect
);
3767 IOReturn
IOMemoryMap::unmap( void )
3773 if( fAddress
&& fAddressMap
&& (0 == fSuperMap
) && fMemory
3774 && (0 == (kIOMapStatic
& fOptions
))) {
3776 err
= fMemory
->doUnmap(fAddressMap
, (IOVirtualAddress
) this, 0);
3779 err
= kIOReturnSuccess
;
3783 vm_map_deallocate(fAddressMap
);
3794 void IOMemoryMap::taskDied( void )
3797 if (fUserClientUnmap
) unmap();
3799 else IOTrackingRemove(gIOMapTracking
, &fTracking
, fLength
);
3803 vm_map_deallocate(fAddressMap
);
3811 IOReturn
IOMemoryMap::userClientUnmap( void )
3813 fUserClientUnmap
= true;
3814 return (kIOReturnSuccess
);
3817 // Overload the release mechanism. All mappings must be a member
3818 // of a memory descriptors _mappings set. This means that we
3819 // always have 2 references on a mapping. When either of these mappings
3820 // are released we need to free ourselves.
3821 void IOMemoryMap::taggedRelease(const void *tag
) const
3824 super::taggedRelease(tag
, 2);
3828 void IOMemoryMap::free()
3835 fMemory
->removeMapping(this);
3840 if (fOwner
&& (fOwner
!= fMemory
))
3843 fOwner
->removeMapping(this);
3848 fSuperMap
->release();
3851 upl_commit(fRedirUPL
, NULL
, 0);
3852 upl_deallocate(fRedirUPL
);
3858 IOByteCount
IOMemoryMap::getLength()
3863 IOVirtualAddress
IOMemoryMap::getVirtualAddress()
3867 fSuperMap
->getVirtualAddress();
3868 else if (fAddressMap
3869 && vm_map_is_64bit(fAddressMap
)
3870 && (sizeof(IOVirtualAddress
) < 8))
3872 OSReportWithBacktrace("IOMemoryMap::getVirtualAddress(0x%qx) called on 64b map; use ::getAddress()", fAddress
);
3874 #endif /* !__LP64__ */
3880 mach_vm_address_t
IOMemoryMap::getAddress()
3885 mach_vm_size_t
IOMemoryMap::getSize()
3889 #endif /* !__LP64__ */
3892 task_t
IOMemoryMap::getAddressTask()
3895 return( fSuperMap
->getAddressTask());
3897 return( fAddressTask
);
3900 IOOptionBits
IOMemoryMap::getMapOptions()
3905 IOMemoryDescriptor
* IOMemoryMap::getMemoryDescriptor()
3910 IOMemoryMap
* IOMemoryMap::copyCompatible(
3911 IOMemoryMap
* newMapping
)
3913 task_t task
= newMapping
->getAddressTask();
3914 mach_vm_address_t toAddress
= newMapping
->fAddress
;
3915 IOOptionBits _options
= newMapping
->fOptions
;
3916 mach_vm_size_t _offset
= newMapping
->fOffset
;
3917 mach_vm_size_t _length
= newMapping
->fLength
;
3919 if( (!task
) || (!fAddressMap
) || (fAddressMap
!= get_task_map(task
)))
3921 if( (fOptions
^ _options
) & kIOMapReadOnly
)
3923 if( (kIOMapDefaultCache
!= (_options
& kIOMapCacheMask
))
3924 && ((fOptions
^ _options
) & kIOMapCacheMask
))
3927 if( (0 == (_options
& kIOMapAnywhere
)) && (fAddress
!= toAddress
))
3930 if( _offset
< fOffset
)
3935 if( (_offset
+ _length
) > fLength
)
3939 if( (fLength
== _length
) && (!_offset
))
3945 newMapping
->fSuperMap
= this;
3946 newMapping
->fOffset
= fOffset
+ _offset
;
3947 newMapping
->fAddress
= fAddress
+ _offset
;
3950 return( newMapping
);
3953 IOReturn
IOMemoryMap::wireRange(
3955 mach_vm_size_t offset
,
3956 mach_vm_size_t length
)
3959 mach_vm_address_t start
= trunc_page_64(fAddress
+ offset
);
3960 mach_vm_address_t end
= round_page_64(fAddress
+ offset
+ length
);
3963 prot
= (kIODirectionOutIn
& options
);
3966 prot
|= VM_PROT_MEMORY_TAG_MAKE(IOMemoryTag(kernel_map
));
3967 kr
= vm_map_wire(fAddressMap
, start
, end
, prot
, FALSE
);
3971 kr
= vm_map_unwire(fAddressMap
, start
, end
, FALSE
);
3980 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
, IOOptionBits _options
)
3981 #else /* !__LP64__ */
3982 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
)
3983 #endif /* !__LP64__ */
3985 IOPhysicalAddress address
;
3989 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
, _options
);
3990 #else /* !__LP64__ */
3991 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
);
3992 #endif /* !__LP64__ */
3998 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4001 #define super OSObject
4003 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4005 void IOMemoryDescriptor::initialize( void )
4007 if( 0 == gIOMemoryLock
)
4008 gIOMemoryLock
= IORecursiveLockAlloc();
4010 gIOLastPage
= IOGetLastPageNumber();
4013 void IOMemoryDescriptor::free( void )
4015 if( _mappings
) _mappings
->release();
4019 IODelete(reserved
, IOMemoryDescriptorReserved
, 1);
4025 IOMemoryMap
* IOMemoryDescriptor::setMapping(
4027 IOVirtualAddress mapAddress
,
4028 IOOptionBits options
)
4030 return (createMappingInTask( intoTask
, mapAddress
,
4031 options
| kIOMapStatic
,
4035 IOMemoryMap
* IOMemoryDescriptor::map(
4036 IOOptionBits options
)
4038 return (createMappingInTask( kernel_task
, 0,
4039 options
| kIOMapAnywhere
,
4044 IOMemoryMap
* IOMemoryDescriptor::map(
4046 IOVirtualAddress atAddress
,
4047 IOOptionBits options
,
4049 IOByteCount length
)
4051 if ((!(kIOMapAnywhere
& options
)) && vm_map_is_64bit(get_task_map(intoTask
)))
4053 OSReportWithBacktrace("IOMemoryDescriptor::map() in 64b task, use ::createMappingInTask()");
4057 return (createMappingInTask(intoTask
, atAddress
,
4058 options
, offset
, length
));
4060 #endif /* !__LP64__ */
4062 IOMemoryMap
* IOMemoryDescriptor::createMappingInTask(
4064 mach_vm_address_t atAddress
,
4065 IOOptionBits options
,
4066 mach_vm_size_t offset
,
4067 mach_vm_size_t length
)
4069 IOMemoryMap
* result
;
4070 IOMemoryMap
* mapping
;
4073 length
= getLength();
4075 mapping
= new IOMemoryMap
;
4078 && !mapping
->init( intoTask
, atAddress
,
4079 options
, offset
, length
)) {
4085 result
= makeMapping(this, intoTask
, (IOVirtualAddress
) mapping
, options
| kIOMap64Bit
, 0, 0);
4091 IOLog("createMappingInTask failed desc %p, addr %qx, options %x, offset %qx, length %llx\n",
4092 this, atAddress
, (uint32_t) options
, offset
, length
);
4098 #ifndef __LP64__ // there is only a 64 bit version for LP64
4099 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
4100 IOOptionBits options
,
4103 return (redirect(newBackingMemory
, options
, (mach_vm_size_t
)offset
));
4107 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
4108 IOOptionBits options
,
4109 mach_vm_size_t offset
)
4111 IOReturn err
= kIOReturnSuccess
;
4112 IOMemoryDescriptor
* physMem
= 0;
4116 if (fAddress
&& fAddressMap
) do
4118 if (((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
4119 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
4125 if (!fRedirUPL
&& fMemory
->_memRef
&& (1 == fMemory
->_memRef
->count
))
4127 upl_size_t size
= round_page(fLength
);
4128 upl_control_flags_t flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
4129 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
4130 | UPL_MEMORY_TAG_MAKE(IOMemoryTag(kernel_map
));
4131 if (KERN_SUCCESS
!= memory_object_iopl_request(fMemory
->_memRef
->entries
[0].entry
, 0, &size
, &fRedirUPL
,
4138 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
4140 physMem
->redirect(0, true);
4144 if (newBackingMemory
)
4146 if (newBackingMemory
!= fMemory
)
4149 if (this != newBackingMemory
->makeMapping(newBackingMemory
, fAddressTask
, (IOVirtualAddress
) this,
4150 options
| kIOMapUnique
| kIOMapReference
| kIOMap64Bit
,
4152 err
= kIOReturnError
;
4156 upl_commit(fRedirUPL
, NULL
, 0);
4157 upl_deallocate(fRedirUPL
);
4160 if ((false) && physMem
)
4161 physMem
->redirect(0, false);
4174 IOMemoryMap
* IOMemoryDescriptor::makeMapping(
4175 IOMemoryDescriptor
* owner
,
4177 IOVirtualAddress __address
,
4178 IOOptionBits options
,
4179 IOByteCount __offset
,
4180 IOByteCount __length
)
4183 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::makeMapping !64bit");
4184 #endif /* !__LP64__ */
4186 IOMemoryDescriptor
* mapDesc
= 0;
4187 IOMemoryMap
* result
= 0;
4190 IOMemoryMap
* mapping
= (IOMemoryMap
*) __address
;
4191 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
4192 mach_vm_size_t length
= mapping
->fLength
;
4194 mapping
->fOffset
= offset
;
4200 if (kIOMapStatic
& options
)
4203 addMapping(mapping
);
4204 mapping
->setMemoryDescriptor(this, 0);
4208 if (kIOMapUnique
& options
)
4211 IOByteCount physLen
;
4213 // if (owner != this) continue;
4215 if (((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
4216 || ((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
4218 phys
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
4219 if (!phys
|| (physLen
< length
))
4222 mapDesc
= IOMemoryDescriptor::withAddressRange(
4223 phys
, length
, getDirection() | kIOMemoryMapperNone
, NULL
);
4227 mapping
->fOffset
= offset
;
4232 // look for a compatible existing mapping
4233 if( (iter
= OSCollectionIterator::withCollection(_mappings
)))
4235 IOMemoryMap
* lookMapping
;
4236 while ((lookMapping
= (IOMemoryMap
*) iter
->getNextObject()))
4238 if ((result
= lookMapping
->copyCompatible(mapping
)))
4241 result
->setMemoryDescriptor(this, offset
);
4247 if (result
|| (options
& kIOMapReference
))
4249 if (result
!= mapping
)
4264 kr
= mapDesc
->doMap( 0, (IOVirtualAddress
*) &mapping
, options
, 0, 0 );
4265 if (kIOReturnSuccess
== kr
)
4268 mapDesc
->addMapping(result
);
4269 result
->setMemoryDescriptor(mapDesc
, offset
);
4287 void IOMemoryDescriptor::addMapping(
4288 IOMemoryMap
* mapping
)
4293 _mappings
= OSSet::withCapacity(1);
4295 _mappings
->setObject( mapping
);
4299 void IOMemoryDescriptor::removeMapping(
4300 IOMemoryMap
* mapping
)
4303 _mappings
->removeObject( mapping
);
4307 // obsolete initializers
4308 // - initWithOptions is the designated initializer
4310 IOMemoryDescriptor::initWithAddress(void * address
,
4312 IODirection direction
)
4318 IOMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
4320 IODirection direction
,
4327 IOMemoryDescriptor::initWithPhysicalAddress(
4328 IOPhysicalAddress address
,
4330 IODirection direction
)
4336 IOMemoryDescriptor::initWithRanges(
4337 IOVirtualRange
* ranges
,
4339 IODirection direction
,
4347 IOMemoryDescriptor::initWithPhysicalRanges( IOPhysicalRange
* ranges
,
4349 IODirection direction
,
4355 void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
4356 IOByteCount
* lengthOfSegment
)
4360 #endif /* !__LP64__ */
4362 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4364 bool IOGeneralMemoryDescriptor::serialize(OSSerialize
* s
) const
4366 OSSymbol
const *keys
[2];
4367 OSObject
*values
[2];
4371 user_addr_t address
;
4374 unsigned int index
, nRanges
;
4377 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
4379 if (s
== NULL
) return false;
4381 array
= OSArray::withCapacity(4);
4382 if (!array
) return (false);
4384 nRanges
= _rangesCount
;
4385 vcopy
= (SerData
*) IOMalloc(sizeof(SerData
) * nRanges
);
4386 if (vcopy
== 0) return false;
4388 keys
[0] = OSSymbol::withCString("address");
4389 keys
[1] = OSSymbol::withCString("length");
4392 values
[0] = values
[1] = 0;
4394 // From this point on we can go to bail.
4396 // Copy the volatile data so we don't have to allocate memory
4397 // while the lock is held.
4399 if (nRanges
== _rangesCount
) {
4400 Ranges vec
= _ranges
;
4401 for (index
= 0; index
< nRanges
; index
++) {
4402 mach_vm_address_t addr
; mach_vm_size_t len
;
4403 getAddrLenForInd(addr
, len
, type
, vec
, index
);
4404 vcopy
[index
].address
= addr
;
4405 vcopy
[index
].length
= len
;
4408 // The descriptor changed out from under us. Give up.
4415 for (index
= 0; index
< nRanges
; index
++)
4417 user_addr_t addr
= vcopy
[index
].address
;
4418 IOByteCount len
= (IOByteCount
) vcopy
[index
].length
;
4419 values
[0] = OSNumber::withNumber(addr
, sizeof(addr
) * 8);
4420 if (values
[0] == 0) {
4424 values
[1] = OSNumber::withNumber(len
, sizeof(len
) * 8);
4425 if (values
[1] == 0) {
4429 OSDictionary
*dict
= OSDictionary::withObjects((const OSObject
**)values
, (const OSSymbol
**)keys
, 2);
4434 array
->setObject(dict
);
4436 values
[0]->release();
4437 values
[1]->release();
4438 values
[0] = values
[1] = 0;
4441 result
= array
->serialize(s
);
4447 values
[0]->release();
4449 values
[1]->release();
4455 IOFree(vcopy
, sizeof(SerData
) * nRanges
);
4460 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4462 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 0);
4464 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 1);
4465 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 2);
4466 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 3);
4467 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 4);
4468 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 5);
4469 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 6);
4470 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 7);
4471 #else /* !__LP64__ */
4472 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 1);
4473 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 2);
4474 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 3);
4475 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 4);
4476 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 5);
4477 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 6);
4478 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 7);
4479 #endif /* !__LP64__ */
4480 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 8);
4481 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 9);
4482 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 10);
4483 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 11);
4484 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 12);
4485 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 13);
4486 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 14);
4487 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 15);
4489 /* ex-inline function implementation */
4491 IOMemoryDescriptor::getPhysicalAddress()
4492 { return( getPhysicalSegment( 0, 0 )); }