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@
29 * Copyright (c) 1998 Apple Computer, Inc. All rights reserved.
36 #include <sys/cdefs.h>
38 #include <IOKit/assert.h>
39 #include <IOKit/system.h>
40 #include <IOKit/IOLib.h>
41 #include <IOKit/IOMemoryDescriptor.h>
42 #include <IOKit/IOMapper.h>
43 #include <IOKit/IODMACommand.h>
44 #include <IOKit/IOKitKeysPrivate.h>
47 #include <IOKit/IOSubMemoryDescriptor.h>
48 #endif /* !__LP64__ */
50 #include <IOKit/IOKitDebug.h>
51 #include <libkern/OSDebug.h>
53 #include "IOKitKernelInternal.h"
55 #include <libkern/c++/OSContainers.h>
56 #include <libkern/c++/OSDictionary.h>
57 #include <libkern/c++/OSArray.h>
58 #include <libkern/c++/OSSymbol.h>
59 #include <libkern/c++/OSNumber.h>
65 #include <vm/vm_pageout.h>
66 #include <mach/memory_object_types.h>
67 #include <device/device_port.h>
69 #include <mach/vm_prot.h>
70 #include <mach/mach_vm.h>
71 #include <vm/vm_fault.h>
72 #include <vm/vm_protos.h>
74 extern ppnum_t
pmap_find_phys(pmap_t pmap
, addr64_t va
);
75 extern void ipc_port_release_send(ipc_port_t port
);
78 memory_object_iopl_request(
80 memory_object_offset_t offset
,
83 upl_page_info_array_t user_page_list
,
84 unsigned int *page_list_count
,
87 // osfmk/device/iokit_rpc.c
88 unsigned int IODefaultCacheBits(addr64_t pa
);
89 unsigned int IOTranslateCacheBits(struct phys_entry
*pp
);
93 #define kIOMapperWaitSystem ((IOMapper *) 1)
95 static IOMapper
* gIOSystemMapper
= NULL
;
99 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
101 OSDefineMetaClassAndAbstractStructors( IOMemoryDescriptor
, OSObject
)
103 #define super IOMemoryDescriptor
105 OSDefineMetaClassAndStructors(IOGeneralMemoryDescriptor
, IOMemoryDescriptor
)
107 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
109 static IORecursiveLock
* gIOMemoryLock
;
111 #define LOCK IORecursiveLockLock( gIOMemoryLock)
112 #define UNLOCK IORecursiveLockUnlock( gIOMemoryLock)
113 #define SLEEP IORecursiveLockSleep( gIOMemoryLock, (void *)this, THREAD_UNINT)
115 IORecursiveLockWakeup( gIOMemoryLock, (void *)this, /* one-thread */ false)
118 #define DEBG(fmt, args...) { kprintf(fmt, ## args); }
120 #define DEBG(fmt, args...) {}
123 #define IOMD_DEBUG_DMAACTIVE 1
125 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
127 // Some data structures and accessor macros used by the initWithOptions
130 enum ioPLBlockFlags
{
131 kIOPLOnDevice
= 0x00000001,
132 kIOPLExternUPL
= 0x00000002,
135 struct IOMDPersistentInitData
137 const IOGeneralMemoryDescriptor
* fMD
;
138 IOMemoryReference
* fMemRef
;
143 vm_address_t fPageInfo
; // Pointer to page list or index into it
144 uint32_t fIOMDOffset
; // The offset of this iopl in descriptor
145 ppnum_t fMappedPage
; // Page number of first page in this iopl
146 unsigned int fPageOffset
; // Offset within first page of iopl
147 unsigned int fFlags
; // Flags
152 uint8_t fDMAMapNumAddressBits
;
153 uint64_t fDMAMapAlignment
;
154 addr64_t fMappedBase
;
155 uint64_t fPreparationID
;
156 unsigned int fPageCnt
;
157 unsigned char fDiscontig
:1;
158 unsigned char fCompletionError
:1;
159 unsigned char _resv
:6;
161 // align arrays to 8 bytes so following macros work
162 unsigned char fPad
[3];
164 upl_page_info_t fPageList
[1]; /* variable length */
165 ioPLBlock fBlocks
[1]; /* variable length */
168 #define getDataP(osd) ((ioGMDData *) (osd)->getBytesNoCopy())
169 #define getIOPLList(d) ((ioPLBlock *) (void *)&(d->fPageList[d->fPageCnt]))
170 #define getNumIOPL(osd, d) \
171 (((osd)->getLength() - ((char *) getIOPLList(d) - (char *) d)) / sizeof(ioPLBlock))
172 #define getPageList(d) (&(d->fPageList[0]))
173 #define computeDataSize(p, u) \
174 (offsetof(ioGMDData, fPageList) + p * sizeof(upl_page_info_t) + u * sizeof(ioPLBlock))
176 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
178 #define next_page(a) ( trunc_page(a) + PAGE_SIZE )
182 kern_return_t
device_data_action(
183 uintptr_t device_handle
,
184 ipc_port_t device_pager
,
185 vm_prot_t protection
,
186 vm_object_offset_t offset
,
190 IOMemoryDescriptorReserved
* ref
= (IOMemoryDescriptorReserved
*) device_handle
;
191 IOMemoryDescriptor
* memDesc
;
194 memDesc
= ref
->dp
.memory
;
198 kr
= memDesc
->handleFault(device_pager
, offset
, size
);
208 kern_return_t
device_close(
209 uintptr_t device_handle
)
211 IOMemoryDescriptorReserved
* ref
= (IOMemoryDescriptorReserved
*) device_handle
;
213 IODelete( ref
, IOMemoryDescriptorReserved
, 1 );
215 return( kIOReturnSuccess
);
219 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
221 // Note this inline function uses C++ reference arguments to return values
222 // This means that pointers are not passed and NULLs don't have to be
223 // checked for as a NULL reference is illegal.
225 getAddrLenForInd(mach_vm_address_t
&addr
, mach_vm_size_t
&len
, // Output variables
226 UInt32 type
, IOGeneralMemoryDescriptor::Ranges r
, UInt32 ind
)
228 assert(kIOMemoryTypeUIO
== type
229 || kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
230 || kIOMemoryTypePhysical
== type
|| kIOMemoryTypePhysical64
== type
);
231 if (kIOMemoryTypeUIO
== type
) {
234 uio_getiov((uio_t
) r
.uio
, ind
, &ad
, &us
); addr
= ad
; len
= us
;
237 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
)) {
238 IOAddressRange cur
= r
.v64
[ind
];
242 #endif /* !__LP64__ */
244 IOVirtualRange cur
= r
.v
[ind
];
250 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
253 purgeableControlBits(IOOptionBits newState
, vm_purgable_t
* control
, int * state
)
255 IOReturn err
= kIOReturnSuccess
;
257 *control
= VM_PURGABLE_SET_STATE
;
259 enum { kIOMemoryPurgeableControlMask
= 15 };
261 switch (kIOMemoryPurgeableControlMask
& newState
)
263 case kIOMemoryPurgeableKeepCurrent
:
264 *control
= VM_PURGABLE_GET_STATE
;
267 case kIOMemoryPurgeableNonVolatile
:
268 *state
= VM_PURGABLE_NONVOLATILE
;
270 case kIOMemoryPurgeableVolatile
:
271 *state
= VM_PURGABLE_VOLATILE
| (newState
& ~kIOMemoryPurgeableControlMask
);
273 case kIOMemoryPurgeableEmpty
:
274 *state
= VM_PURGABLE_EMPTY
;
277 err
= kIOReturnBadArgument
;
284 purgeableStateBits(int * state
)
286 IOReturn err
= kIOReturnSuccess
;
288 switch (VM_PURGABLE_STATE_MASK
& *state
)
290 case VM_PURGABLE_NONVOLATILE
:
291 *state
= kIOMemoryPurgeableNonVolatile
;
293 case VM_PURGABLE_VOLATILE
:
294 *state
= kIOMemoryPurgeableVolatile
;
296 case VM_PURGABLE_EMPTY
:
297 *state
= kIOMemoryPurgeableEmpty
;
300 *state
= kIOMemoryPurgeableNonVolatile
;
301 err
= kIOReturnNotReady
;
309 vmProtForCacheMode(IOOptionBits cacheMode
)
314 case kIOInhibitCache
:
315 SET_MAP_MEM(MAP_MEM_IO
, prot
);
318 case kIOWriteThruCache
:
319 SET_MAP_MEM(MAP_MEM_WTHRU
, prot
);
322 case kIOWriteCombineCache
:
323 SET_MAP_MEM(MAP_MEM_WCOMB
, prot
);
326 case kIOCopybackCache
:
327 SET_MAP_MEM(MAP_MEM_COPYBACK
, prot
);
330 case kIOCopybackInnerCache
:
331 SET_MAP_MEM(MAP_MEM_INNERWBACK
, prot
);
334 case kIODefaultCache
:
336 SET_MAP_MEM(MAP_MEM_NOOP
, prot
);
344 pagerFlagsForCacheMode(IOOptionBits cacheMode
)
346 unsigned int pagerFlags
= 0;
349 case kIOInhibitCache
:
350 pagerFlags
= DEVICE_PAGER_CACHE_INHIB
| DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
353 case kIOWriteThruCache
:
354 pagerFlags
= DEVICE_PAGER_WRITE_THROUGH
| DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
357 case kIOWriteCombineCache
:
358 pagerFlags
= DEVICE_PAGER_CACHE_INHIB
| DEVICE_PAGER_COHERENT
;
361 case kIOCopybackCache
:
362 pagerFlags
= DEVICE_PAGER_COHERENT
;
365 case kIOCopybackInnerCache
:
366 pagerFlags
= DEVICE_PAGER_COHERENT
;
369 case kIODefaultCache
:
377 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
378 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
387 struct IOMemoryReference
389 volatile SInt32 refCount
;
393 IOMemoryEntry entries
[0];
398 kIOMemoryReferenceReuse
= 0x00000001,
399 kIOMemoryReferenceWrite
= 0x00000002,
402 SInt32 gIOMemoryReferenceCount
;
405 IOGeneralMemoryDescriptor::memoryReferenceAlloc(uint32_t capacity
, IOMemoryReference
* realloc
)
407 IOMemoryReference
* ref
;
408 size_t newSize
, oldSize
, copySize
;
410 newSize
= (sizeof(IOMemoryReference
)
411 - sizeof(ref
->entries
)
412 + capacity
* sizeof(ref
->entries
[0]));
413 ref
= (typeof(ref
)) IOMalloc(newSize
);
416 oldSize
= (sizeof(IOMemoryReference
)
417 - sizeof(realloc
->entries
)
418 + realloc
->capacity
* sizeof(realloc
->entries
[0]));
420 if (copySize
> newSize
) copySize
= newSize
;
421 if (ref
) bcopy(realloc
, ref
, copySize
);
422 IOFree(realloc
, oldSize
);
426 bzero(ref
, sizeof(*ref
));
428 OSIncrementAtomic(&gIOMemoryReferenceCount
);
430 if (!ref
) return (0);
431 ref
->capacity
= capacity
;
436 IOGeneralMemoryDescriptor::memoryReferenceFree(IOMemoryReference
* ref
)
438 IOMemoryEntry
* entries
;
441 entries
= ref
->entries
+ ref
->count
;
442 while (entries
> &ref
->entries
[0])
445 ipc_port_release_send(entries
->entry
);
447 size
= (sizeof(IOMemoryReference
)
448 - sizeof(ref
->entries
)
449 + ref
->capacity
* sizeof(ref
->entries
[0]));
452 OSDecrementAtomic(&gIOMemoryReferenceCount
);
456 IOGeneralMemoryDescriptor::memoryReferenceRelease(IOMemoryReference
* ref
)
458 if (1 == OSDecrementAtomic(&ref
->refCount
)) memoryReferenceFree(ref
);
463 IOGeneralMemoryDescriptor::memoryReferenceCreate(
464 IOOptionBits options
,
465 IOMemoryReference
** reference
)
467 enum { kCapacity
= 4, kCapacityInc
= 4 };
470 IOMemoryReference
* ref
;
471 IOMemoryEntry
* entries
;
472 IOMemoryEntry
* cloneEntries
;
474 ipc_port_t entry
, cloneEntry
;
476 memory_object_size_t actualSize
;
479 mach_vm_address_t entryAddr
, endAddr
, entrySize
;
480 mach_vm_size_t srcAddr
, srcLen
;
481 mach_vm_size_t nextAddr
, nextLen
;
482 mach_vm_size_t offset
, remain
;
484 IOOptionBits type
= (_flags
& kIOMemoryTypeMask
);
485 IOOptionBits cacheMode
;
486 unsigned int pagerFlags
;
488 ref
= memoryReferenceAlloc(kCapacity
, NULL
);
489 if (!ref
) return (kIOReturnNoMemory
);
490 entries
= &ref
->entries
[0];
495 if (_task
) getAddrLenForInd(nextAddr
, nextLen
, type
, _ranges
, rangeIdx
);
498 nextAddr
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
500 // default cache mode for physical
501 if (kIODefaultCache
== ((_flags
& kIOMemoryBufferCacheMask
) >> kIOMemoryBufferCacheShift
))
504 pagerFlags
= IODefaultCacheBits(nextAddr
);
505 if (DEVICE_PAGER_CACHE_INHIB
& pagerFlags
)
507 if (DEVICE_PAGER_GUARDED
& pagerFlags
)
508 mode
= kIOInhibitCache
;
510 mode
= kIOWriteCombineCache
;
512 else if (DEVICE_PAGER_WRITE_THROUGH
& pagerFlags
)
513 mode
= kIOWriteThruCache
;
515 mode
= kIOCopybackCache
;
516 _flags
|= (mode
<< kIOMemoryBufferCacheShift
);
520 // cache mode & vm_prot
522 cacheMode
= ((_flags
& kIOMemoryBufferCacheMask
) >> kIOMemoryBufferCacheShift
);
523 prot
|= vmProtForCacheMode(cacheMode
);
524 // VM system requires write access to change cache mode
525 if (kIODefaultCache
!= cacheMode
) prot
|= VM_PROT_WRITE
;
526 if (kIODirectionOut
!= (kIODirectionOutIn
& _flags
)) prot
|= VM_PROT_WRITE
;
527 if (kIOMemoryReferenceWrite
& options
) prot
|= VM_PROT_WRITE
;
529 if ((kIOMemoryReferenceReuse
& options
) && _memRef
)
531 cloneEntries
= &_memRef
->entries
[0];
532 prot
|= MAP_MEM_NAMED_REUSE
;
539 if (kIOMemoryBufferPageable
& _flags
)
541 // IOBufferMemoryDescriptor alloc - set flags for entry + object create
542 prot
|= MAP_MEM_NAMED_CREATE
;
543 if (kIOMemoryBufferPurgeable
& _flags
) prot
|= MAP_MEM_PURGABLE
;
544 prot
|= VM_PROT_WRITE
;
547 else map
= get_task_map(_task
);
556 // coalesce addr range
557 for (++rangeIdx
; rangeIdx
< _rangesCount
; rangeIdx
++)
559 getAddrLenForInd(nextAddr
, nextLen
, type
, _ranges
, rangeIdx
);
560 if ((srcAddr
+ srcLen
) != nextAddr
) break;
563 entryAddr
= trunc_page_64(srcAddr
);
564 endAddr
= round_page_64(srcAddr
+ srcLen
);
567 entrySize
= (endAddr
- entryAddr
);
568 if (!entrySize
) break;
569 actualSize
= entrySize
;
571 cloneEntry
= MACH_PORT_NULL
;
572 if (MAP_MEM_NAMED_REUSE
& prot
)
574 if (cloneEntries
< &_memRef
->entries
[_memRef
->count
]) cloneEntry
= cloneEntries
->entry
;
575 else prot
&= ~MAP_MEM_NAMED_REUSE
;
578 err
= mach_make_memory_entry_64(map
,
579 &actualSize
, entryAddr
, prot
, &entry
, cloneEntry
);
581 if (KERN_SUCCESS
!= err
) break;
582 if (actualSize
> entrySize
) panic("mach_make_memory_entry_64 actualSize");
584 if (count
>= ref
->capacity
)
586 ref
= memoryReferenceAlloc(ref
->capacity
+ kCapacityInc
, ref
);
587 entries
= &ref
->entries
[count
];
589 entries
->entry
= entry
;
590 entries
->size
= actualSize
;
591 entries
->offset
= offset
+ (entryAddr
- srcAddr
);
592 entryAddr
+= actualSize
;
593 if (MAP_MEM_NAMED_REUSE
& prot
)
595 if ((cloneEntries
->entry
== entries
->entry
)
596 && (cloneEntries
->size
== entries
->size
)
597 && (cloneEntries
->offset
== entries
->offset
)) cloneEntries
++;
598 else prot
&= ~MAP_MEM_NAMED_REUSE
;
610 // _task == 0, physical
611 memory_object_t pager
;
612 vm_size_t size
= ptoa_32(_pages
);
614 if (!getKernelReserved()) panic("getKernelReserved");
616 reserved
->dp
.pagerContig
= (1 == _rangesCount
);
617 reserved
->dp
.memory
= this;
619 pagerFlags
= pagerFlagsForCacheMode(cacheMode
);
620 if (-1U == pagerFlags
) panic("phys is kIODefaultCache");
621 if (reserved
->dp
.pagerContig
) pagerFlags
|= DEVICE_PAGER_CONTIGUOUS
;
623 pager
= device_pager_setup((memory_object_t
) 0, (uintptr_t) reserved
,
626 if (!pager
) err
= kIOReturnVMError
;
630 entryAddr
= trunc_page_64(srcAddr
);
631 err
= mach_memory_object_memory_entry_64((host_t
) 1, false /*internal*/,
632 size
, VM_PROT_READ
| VM_PROT_WRITE
, pager
, &entry
);
633 assert (KERN_SUCCESS
== err
);
634 if (KERN_SUCCESS
!= err
) device_pager_deallocate(pager
);
637 reserved
->dp
.devicePager
= pager
;
638 entries
->entry
= entry
;
639 entries
->size
= size
;
640 entries
->offset
= offset
+ (entryAddr
- srcAddr
);
650 if (KERN_SUCCESS
== err
)
652 if (MAP_MEM_NAMED_REUSE
& prot
)
654 memoryReferenceFree(ref
);
655 OSIncrementAtomic(&_memRef
->refCount
);
661 memoryReferenceFree(ref
);
670 struct IOMemoryDescriptorMapAllocRef
673 mach_vm_address_t mapped
;
676 IOOptionBits options
;
680 IOMemoryDescriptorMapAlloc(vm_map_t map
, void * _ref
)
682 IOMemoryDescriptorMapAllocRef
* ref
= (typeof(ref
))_ref
;
684 vm_map_offset_t addr
;
687 err
= vm_map_enter_mem_object(map
, &addr
, ref
->size
,
689 (((ref
->options
& kIOMapAnywhere
)
692 | VM_MAKE_TAG(VM_MEMORY_IOKIT
)
693 | VM_FLAGS_IOKIT_ACCT
), /* iokit accounting */
695 (memory_object_offset_t
) 0,
700 if (KERN_SUCCESS
== err
)
702 ref
->mapped
= (mach_vm_address_t
) addr
;
710 IOGeneralMemoryDescriptor::memoryReferenceMap(
711 IOMemoryReference
* ref
,
713 mach_vm_size_t inoffset
,
715 IOOptionBits options
,
716 mach_vm_address_t
* inaddr
)
719 int64_t offset
= inoffset
;
720 uint32_t rangeIdx
, entryIdx
;
721 vm_map_offset_t addr
, mapAddr
;
722 vm_map_offset_t pageOffset
, entryOffset
, remain
, chunk
;
724 mach_vm_address_t srcAddr
, nextAddr
;
725 mach_vm_size_t srcLen
, nextLen
;
727 IOMemoryEntry
* entry
;
728 vm_prot_t prot
, memEntryCacheMode
;
730 IOOptionBits cacheMode
;
733 * For the kIOMapPrefault option.
735 upl_page_info_t
*pageList
= NULL
;
736 UInt currentPageIndex
= 0;
738 type
= _flags
& kIOMemoryTypeMask
;
740 if (!(kIOMapReadOnly
& options
)) prot
|= VM_PROT_WRITE
;
743 cacheMode
= ((options
& kIOMapCacheMask
) >> kIOMapCacheShift
);
744 if (kIODefaultCache
!= cacheMode
)
746 // VM system requires write access to update named entry cache mode
747 memEntryCacheMode
= (MAP_MEM_ONLY
| VM_PROT_WRITE
| prot
| vmProtForCacheMode(cacheMode
));
752 // Find first range for offset
753 for (remain
= offset
, rangeIdx
= 0; rangeIdx
< _rangesCount
; rangeIdx
++)
755 getAddrLenForInd(nextAddr
, nextLen
, type
, _ranges
, rangeIdx
);
756 if (remain
< nextLen
) break;
764 nextAddr
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
768 assert(remain
< nextLen
);
769 if (remain
>= nextLen
) return (kIOReturnBadArgument
);
773 pageOffset
= (page_mask
& nextAddr
);
775 if (!(options
& kIOMapAnywhere
))
778 if (pageOffset
!= (page_mask
& addr
)) return (kIOReturnNotAligned
);
782 // find first entry for offset
784 (entryIdx
< ref
->count
) && (offset
>= ref
->entries
[entryIdx
].offset
);
787 entry
= &ref
->entries
[entryIdx
];
790 size
= round_page_64(size
+ pageOffset
);
792 IOMemoryDescriptorMapAllocRef ref
;
794 ref
.options
= options
;
797 if (options
& kIOMapAnywhere
)
798 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
803 if ((ref
.map
== kernel_map
) && (kIOMemoryBufferPageable
& _flags
))
804 err
= IOIteratePageableMaps( ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
806 err
= IOMemoryDescriptorMapAlloc(ref
.map
, &ref
);
807 if (KERN_SUCCESS
== err
)
815 * Prefaulting is only possible if we wired the memory earlier. Check the
816 * memory type, and the underlying data.
818 if (options
& kIOMapPrefault
) {
820 * The memory must have been wired by calling ::prepare(), otherwise
821 * we don't have the UPL. Without UPLs, pages cannot be pre-faulted
823 assert(map
!= kernel_map
);
824 assert(_wireCount
!= 0);
825 assert(_memoryEntries
!= NULL
);
826 if ((map
== kernel_map
) ||
828 (_memoryEntries
== NULL
))
830 return kIOReturnBadArgument
;
833 // Get the page list.
834 ioGMDData
* dataP
= getDataP(_memoryEntries
);
835 ioPLBlock
const* ioplList
= getIOPLList(dataP
);
836 pageList
= getPageList(dataP
);
838 // Get the number of IOPLs.
839 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
842 * Scan through the IOPL Info Blocks, looking for the first block containing
843 * the offset. The research will go past it, so we'll need to go back to the
844 * right range at the end.
847 while (ioplIndex
< numIOPLs
&& offset
>= ioplList
[ioplIndex
].fIOMDOffset
)
851 // Retrieve the IOPL info block.
852 ioPLBlock ioplInfo
= ioplList
[ioplIndex
];
855 * For external UPLs, the fPageInfo points directly to the UPL's page_info_t
858 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
859 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
861 pageList
= &pageList
[ioplInfo
.fPageInfo
];
863 // Rebase [offset] into the IOPL in order to looks for the first page index.
864 mach_vm_size_t offsetInIOPL
= offset
- ioplInfo
.fIOMDOffset
+ ioplInfo
.fPageOffset
;
866 // Retrieve the index of the first page corresponding to the offset.
867 currentPageIndex
= atop_32(offsetInIOPL
);
874 while (remain
&& nextLen
&& (KERN_SUCCESS
== err
))
880 // coalesce addr range
881 for (++rangeIdx
; rangeIdx
< _rangesCount
; rangeIdx
++)
883 getAddrLenForInd(nextAddr
, nextLen
, type
, _ranges
, rangeIdx
);
884 if ((srcAddr
+ srcLen
) != nextAddr
) break;
888 while (srcLen
&& (KERN_SUCCESS
== err
))
890 entryOffset
= offset
- entry
->offset
;
891 if ((page_mask
& entryOffset
) != pageOffset
)
893 err
= kIOReturnNotAligned
;
897 if (kIODefaultCache
!= cacheMode
)
899 vm_size_t unused
= 0;
900 err
= mach_make_memory_entry(NULL
/*unused*/, &unused
, 0 /*unused*/,
901 memEntryCacheMode
, NULL
, entry
->entry
);
902 assert (KERN_SUCCESS
== err
);
905 entryOffset
-= pageOffset
;
906 if (entryOffset
>= entry
->size
) panic("entryOffset");
907 chunk
= entry
->size
- entryOffset
;
910 if (chunk
> remain
) chunk
= remain
;
912 if (options
& kIOMapPrefault
) {
913 UInt nb_pages
= round_page(chunk
) / PAGE_SIZE
;
914 err
= vm_map_enter_mem_object_prefault(map
,
919 | VM_MAKE_TAG(VM_MEMORY_IOKIT
)
920 | VM_FLAGS_IOKIT_ACCT
), /* iokit accounting */
925 &pageList
[currentPageIndex
],
928 // Compute the next index in the page list.
929 currentPageIndex
+= nb_pages
;
930 assert(currentPageIndex
<= _pages
);
932 err
= vm_map_enter_mem_object(map
,
937 | VM_MAKE_TAG(VM_MEMORY_IOKIT
)
938 | VM_FLAGS_IOKIT_ACCT
), /* iokit accounting */
947 if (KERN_SUCCESS
!= err
) break;
951 offset
+= chunk
- pageOffset
;
956 if (entryIdx
>= ref
->count
)
958 err
= kIOReturnOverrun
;
964 if ((KERN_SUCCESS
!= err
) && addr
)
966 (void) mach_vm_deallocate(map
, trunc_page_64(addr
), size
);
975 IOGeneralMemoryDescriptor::memoryReferenceGetPageCounts(
976 IOMemoryReference
* ref
,
977 IOByteCount
* residentPageCount
,
978 IOByteCount
* dirtyPageCount
)
981 IOMemoryEntry
* entries
;
982 unsigned int resident
, dirty
;
983 unsigned int totalResident
, totalDirty
;
985 totalResident
= totalDirty
= 0;
986 entries
= ref
->entries
+ ref
->count
;
987 while (entries
> &ref
->entries
[0])
990 err
= mach_memory_entry_get_page_counts(entries
->entry
, &resident
, &dirty
);
991 if (KERN_SUCCESS
!= err
) break;
992 totalResident
+= resident
;
996 if (residentPageCount
) *residentPageCount
= totalResident
;
997 if (dirtyPageCount
) *dirtyPageCount
= totalDirty
;
1002 IOGeneralMemoryDescriptor::memoryReferenceSetPurgeable(
1003 IOMemoryReference
* ref
,
1004 IOOptionBits newState
,
1005 IOOptionBits
* oldState
)
1008 IOMemoryEntry
* entries
;
1009 vm_purgable_t control
;
1010 int totalState
, state
;
1012 entries
= ref
->entries
+ ref
->count
;
1013 totalState
= kIOMemoryPurgeableNonVolatile
;
1014 while (entries
> &ref
->entries
[0])
1018 err
= purgeableControlBits(newState
, &control
, &state
);
1019 if (KERN_SUCCESS
!= err
) break;
1020 err
= mach_memory_entry_purgable_control(entries
->entry
, control
, &state
);
1021 if (KERN_SUCCESS
!= err
) break;
1022 err
= purgeableStateBits(&state
);
1023 if (KERN_SUCCESS
!= err
) break;
1025 if (kIOMemoryPurgeableEmpty
== state
) totalState
= kIOMemoryPurgeableEmpty
;
1026 else if (kIOMemoryPurgeableEmpty
== totalState
) continue;
1027 else if (kIOMemoryPurgeableVolatile
== totalState
) continue;
1028 else if (kIOMemoryPurgeableVolatile
== state
) totalState
= kIOMemoryPurgeableVolatile
;
1029 else totalState
= kIOMemoryPurgeableNonVolatile
;
1032 if (oldState
) *oldState
= totalState
;
1036 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1038 IOMemoryDescriptor
*
1039 IOMemoryDescriptor::withAddress(void * address
,
1041 IODirection direction
)
1043 return IOMemoryDescriptor::
1044 withAddressRange((IOVirtualAddress
) address
, length
, direction
| kIOMemoryAutoPrepare
, kernel_task
);
1048 IOMemoryDescriptor
*
1049 IOMemoryDescriptor::withAddress(IOVirtualAddress address
,
1051 IODirection direction
,
1054 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1057 if (that
->initWithAddress(address
, length
, direction
, task
))
1064 #endif /* !__LP64__ */
1066 IOMemoryDescriptor
*
1067 IOMemoryDescriptor::withPhysicalAddress(
1068 IOPhysicalAddress address
,
1070 IODirection direction
)
1072 return (IOMemoryDescriptor::withAddressRange(address
, length
, direction
, TASK_NULL
));
1076 IOMemoryDescriptor
*
1077 IOMemoryDescriptor::withRanges( IOVirtualRange
* ranges
,
1079 IODirection direction
,
1083 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1086 if (that
->initWithRanges(ranges
, withCount
, direction
, task
, asReference
))
1093 #endif /* !__LP64__ */
1095 IOMemoryDescriptor
*
1096 IOMemoryDescriptor::withAddressRange(mach_vm_address_t address
,
1097 mach_vm_size_t length
,
1098 IOOptionBits options
,
1101 IOAddressRange range
= { address
, length
};
1102 return (IOMemoryDescriptor::withAddressRanges(&range
, 1, options
, task
));
1105 IOMemoryDescriptor
*
1106 IOMemoryDescriptor::withAddressRanges(IOAddressRange
* ranges
,
1108 IOOptionBits options
,
1111 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1115 options
|= kIOMemoryTypeVirtual64
;
1117 options
|= kIOMemoryTypePhysical64
;
1119 if (that
->initWithOptions(ranges
, rangeCount
, 0, task
, options
, /* mapper */ 0))
1132 * Create a new IOMemoryDescriptor. The buffer is made up of several
1133 * virtual address ranges, from a given task.
1135 * Passing the ranges as a reference will avoid an extra allocation.
1137 IOMemoryDescriptor
*
1138 IOMemoryDescriptor::withOptions(void * buffers
,
1145 IOGeneralMemoryDescriptor
*self
= new IOGeneralMemoryDescriptor
;
1148 && !self
->initWithOptions(buffers
, count
, offset
, task
, opts
, mapper
))
1157 bool IOMemoryDescriptor::initWithOptions(void * buffers
,
1161 IOOptionBits options
,
1168 IOMemoryDescriptor
*
1169 IOMemoryDescriptor::withPhysicalRanges( IOPhysicalRange
* ranges
,
1171 IODirection direction
,
1174 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1177 if (that
->initWithPhysicalRanges(ranges
, withCount
, direction
, asReference
))
1185 IOMemoryDescriptor
*
1186 IOMemoryDescriptor::withSubRange(IOMemoryDescriptor
* of
,
1189 IODirection direction
)
1191 return (IOSubMemoryDescriptor::withSubRange(of
, offset
, length
, direction
| kIOMemoryThreadSafe
));
1193 #endif /* !__LP64__ */
1195 IOMemoryDescriptor
*
1196 IOMemoryDescriptor::withPersistentMemoryDescriptor(IOMemoryDescriptor
*originalMD
)
1198 IOGeneralMemoryDescriptor
*origGenMD
=
1199 OSDynamicCast(IOGeneralMemoryDescriptor
, originalMD
);
1202 return IOGeneralMemoryDescriptor::
1203 withPersistentMemoryDescriptor(origGenMD
);
1208 IOMemoryDescriptor
*
1209 IOGeneralMemoryDescriptor::withPersistentMemoryDescriptor(IOGeneralMemoryDescriptor
*originalMD
)
1211 IOMemoryReference
* memRef
;
1213 if (kIOReturnSuccess
!= originalMD
->memoryReferenceCreate(kIOMemoryReferenceReuse
, &memRef
)) return (0);
1215 if (memRef
== originalMD
->_memRef
)
1217 originalMD
->retain(); // Add a new reference to ourselves
1218 originalMD
->memoryReferenceRelease(memRef
);
1222 IOGeneralMemoryDescriptor
* self
= new IOGeneralMemoryDescriptor
;
1223 IOMDPersistentInitData initData
= { originalMD
, memRef
};
1226 && !self
->initWithOptions(&initData
, 1, 0, 0, kIOMemoryTypePersistentMD
, 0)) {
1235 IOGeneralMemoryDescriptor::initWithAddress(void * address
,
1236 IOByteCount withLength
,
1237 IODirection withDirection
)
1239 _singleRange
.v
.address
= (vm_offset_t
) address
;
1240 _singleRange
.v
.length
= withLength
;
1242 return initWithRanges(&_singleRange
.v
, 1, withDirection
, kernel_task
, true);
1246 IOGeneralMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
1247 IOByteCount withLength
,
1248 IODirection withDirection
,
1251 _singleRange
.v
.address
= address
;
1252 _singleRange
.v
.length
= withLength
;
1254 return initWithRanges(&_singleRange
.v
, 1, withDirection
, withTask
, true);
1258 IOGeneralMemoryDescriptor::initWithPhysicalAddress(
1259 IOPhysicalAddress address
,
1260 IOByteCount withLength
,
1261 IODirection withDirection
)
1263 _singleRange
.p
.address
= address
;
1264 _singleRange
.p
.length
= withLength
;
1266 return initWithPhysicalRanges( &_singleRange
.p
, 1, withDirection
, true);
1270 IOGeneralMemoryDescriptor::initWithPhysicalRanges(
1271 IOPhysicalRange
* ranges
,
1273 IODirection direction
,
1276 IOOptionBits mdOpts
= direction
| kIOMemoryTypePhysical
;
1279 mdOpts
|= kIOMemoryAsReference
;
1281 return initWithOptions(ranges
, count
, 0, 0, mdOpts
, /* mapper */ 0);
1285 IOGeneralMemoryDescriptor::initWithRanges(
1286 IOVirtualRange
* ranges
,
1288 IODirection direction
,
1292 IOOptionBits mdOpts
= direction
;
1295 mdOpts
|= kIOMemoryAsReference
;
1298 mdOpts
|= kIOMemoryTypeVirtual
;
1300 // Auto-prepare if this is a kernel memory descriptor as very few
1301 // clients bother to prepare() kernel memory.
1302 // But it was not enforced so what are you going to do?
1303 if (task
== kernel_task
)
1304 mdOpts
|= kIOMemoryAutoPrepare
;
1307 mdOpts
|= kIOMemoryTypePhysical
;
1309 return initWithOptions(ranges
, count
, 0, task
, mdOpts
, /* mapper */ 0);
1311 #endif /* !__LP64__ */
1316 * IOMemoryDescriptor. The buffer is made up of several virtual address ranges,
1317 * from a given task, several physical ranges, an UPL from the ubc
1318 * system or a uio (may be 64bit) from the BSD subsystem.
1320 * Passing the ranges as a reference will avoid an extra allocation.
1322 * An IOMemoryDescriptor can be re-used by calling initWithOptions again on an
1323 * existing instance -- note this behavior is not commonly supported in other
1324 * I/O Kit classes, although it is supported here.
1328 IOGeneralMemoryDescriptor::initWithOptions(void * buffers
,
1332 IOOptionBits options
,
1335 IOOptionBits type
= options
& kIOMemoryTypeMask
;
1339 && (kIOMemoryTypeVirtual
== type
)
1340 && vm_map_is_64bit(get_task_map(task
))
1341 && ((IOVirtualRange
*) buffers
)->address
)
1343 OSReportWithBacktrace("IOMemoryDescriptor: attempt to create 32b virtual in 64b task, use ::withAddressRange()");
1346 #endif /* !__LP64__ */
1348 // Grab the original MD's configuation data to initialse the
1349 // arguments to this function.
1350 if (kIOMemoryTypePersistentMD
== type
) {
1352 IOMDPersistentInitData
*initData
= (typeof(initData
)) buffers
;
1353 const IOGeneralMemoryDescriptor
*orig
= initData
->fMD
;
1354 ioGMDData
*dataP
= getDataP(orig
->_memoryEntries
);
1356 // Only accept persistent memory descriptors with valid dataP data.
1357 assert(orig
->_rangesCount
== 1);
1358 if ( !(orig
->_flags
& kIOMemoryPersistent
) || !dataP
)
1361 _memRef
= initData
->fMemRef
; // Grab the new named entry
1362 options
= orig
->_flags
& ~kIOMemoryAsReference
;
1363 type
= options
& kIOMemoryTypeMask
;
1364 buffers
= orig
->_ranges
.v
;
1365 count
= orig
->_rangesCount
;
1367 // Now grab the original task and whatever mapper was previously used
1369 mapper
= dataP
->fMapper
;
1371 // We are ready to go through the original initialisation now
1375 case kIOMemoryTypeUIO
:
1376 case kIOMemoryTypeVirtual
:
1378 case kIOMemoryTypeVirtual64
:
1379 #endif /* !__LP64__ */
1385 case kIOMemoryTypePhysical
: // Neither Physical nor UPL should have a task
1387 case kIOMemoryTypePhysical64
:
1388 #endif /* !__LP64__ */
1389 case kIOMemoryTypeUPL
:
1393 return false; /* bad argument */
1400 * We can check the _initialized instance variable before having ever set
1401 * it to an initial value because I/O Kit guarantees that all our instance
1402 * variables are zeroed on an object's allocation.
1407 * An existing memory descriptor is being retargeted to point to
1408 * somewhere else. Clean up our present state.
1410 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1411 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
1416 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
1418 if (kIOMemoryTypeUIO
== type
)
1419 uio_free((uio_t
) _ranges
.v
);
1421 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
1422 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
1423 #endif /* !__LP64__ */
1425 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
1428 options
|= (kIOMemoryRedirected
& _flags
);
1429 if (!(kIOMemoryRedirected
& options
))
1433 memoryReferenceRelease(_memRef
);
1437 _mappings
->flushCollection();
1443 _initialized
= true;
1446 // Grab the appropriate mapper
1447 if (kIOMemoryHostOnly
& options
) options
|= kIOMemoryMapperNone
;
1448 if (kIOMemoryMapperNone
& options
)
1449 mapper
= 0; // No Mapper
1450 else if (mapper
== kIOMapperSystem
) {
1451 IOMapper::checkForSystemMapper();
1452 gIOSystemMapper
= mapper
= IOMapper::gSystem
;
1455 // Temp binary compatibility for kIOMemoryThreadSafe
1456 if (kIOMemoryReserved6156215
& options
)
1458 options
&= ~kIOMemoryReserved6156215
;
1459 options
|= kIOMemoryThreadSafe
;
1461 // Remove the dynamic internal use flags from the initial setting
1462 options
&= ~(kIOMemoryPreparedReadOnly
);
1467 _direction
= (IODirection
) (_flags
& kIOMemoryDirectionMask
);
1468 #endif /* !__LP64__ */
1470 __iomd_reservedA
= 0;
1471 __iomd_reservedB
= 0;
1474 if (kIOMemoryThreadSafe
& options
)
1477 _prepareLock
= IOLockAlloc();
1479 else if (_prepareLock
)
1481 IOLockFree(_prepareLock
);
1482 _prepareLock
= NULL
;
1485 if (kIOMemoryTypeUPL
== type
) {
1488 unsigned int dataSize
= computeDataSize(/* pages */ 0, /* upls */ 1);
1490 if (!initMemoryEntries(dataSize
, mapper
)) return (false);
1491 dataP
= getDataP(_memoryEntries
);
1492 dataP
->fPageCnt
= 0;
1494 // _wireCount++; // UPLs start out life wired
1497 _pages
+= atop_32(offset
+ count
+ PAGE_MASK
) - atop_32(offset
);
1500 iopl
.fIOPL
= (upl_t
) buffers
;
1501 upl_set_referenced(iopl
.fIOPL
, true);
1502 upl_page_info_t
*pageList
= UPL_GET_INTERNAL_PAGE_LIST(iopl
.fIOPL
);
1504 if (upl_get_size(iopl
.fIOPL
) < (count
+ offset
))
1505 panic("short external upl");
1507 _highestPage
= upl_get_highest_page(iopl
.fIOPL
);
1509 // Set the flag kIOPLOnDevice convieniently equal to 1
1510 iopl
.fFlags
= pageList
->device
| kIOPLExternUPL
;
1511 if (!pageList
->device
) {
1512 // Pre-compute the offset into the UPL's page list
1513 pageList
= &pageList
[atop_32(offset
)];
1514 offset
&= PAGE_MASK
;
1516 iopl
.fIOMDOffset
= 0;
1517 iopl
.fMappedPage
= 0;
1518 iopl
.fPageInfo
= (vm_address_t
) pageList
;
1519 iopl
.fPageOffset
= offset
;
1520 _memoryEntries
->appendBytes(&iopl
, sizeof(iopl
));
1523 // kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO
1524 // kIOMemoryTypePhysical | kIOMemoryTypePhysical64
1526 // Initialize the memory descriptor
1527 if (options
& kIOMemoryAsReference
) {
1529 _rangesIsAllocated
= false;
1530 #endif /* !__LP64__ */
1532 // Hack assignment to get the buffer arg into _ranges.
1533 // I'd prefer to do _ranges = (Ranges) buffers, but that doesn't
1535 // This also initialises the uio & physical ranges.
1536 _ranges
.v
= (IOVirtualRange
*) buffers
;
1540 _rangesIsAllocated
= true;
1541 #endif /* !__LP64__ */
1544 case kIOMemoryTypeUIO
:
1545 _ranges
.v
= (IOVirtualRange
*) uio_duplicate((uio_t
) buffers
);
1549 case kIOMemoryTypeVirtual64
:
1550 case kIOMemoryTypePhysical64
:
1552 && (((IOAddressRange
*) buffers
)->address
+ ((IOAddressRange
*) buffers
)->length
) <= 0x100000000ULL
1554 if (kIOMemoryTypeVirtual64
== type
)
1555 type
= kIOMemoryTypeVirtual
;
1557 type
= kIOMemoryTypePhysical
;
1558 _flags
= (_flags
& ~kIOMemoryTypeMask
) | type
| kIOMemoryAsReference
;
1559 _rangesIsAllocated
= false;
1560 _ranges
.v
= &_singleRange
.v
;
1561 _singleRange
.v
.address
= ((IOAddressRange
*) buffers
)->address
;
1562 _singleRange
.v
.length
= ((IOAddressRange
*) buffers
)->length
;
1565 _ranges
.v64
= IONew(IOAddressRange
, count
);
1568 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOAddressRange
));
1570 #endif /* !__LP64__ */
1571 case kIOMemoryTypeVirtual
:
1572 case kIOMemoryTypePhysical
:
1574 _flags
|= kIOMemoryAsReference
;
1576 _rangesIsAllocated
= false;
1577 #endif /* !__LP64__ */
1578 _ranges
.v
= &_singleRange
.v
;
1580 _ranges
.v
= IONew(IOVirtualRange
, count
);
1584 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOVirtualRange
));
1589 // Find starting address within the vector of ranges
1590 Ranges vec
= _ranges
;
1593 for (unsigned ind
= 0; ind
< count
; ind
++) {
1594 mach_vm_address_t addr
;
1597 // addr & len are returned by this function
1598 getAddrLenForInd(addr
, len
, type
, vec
, ind
);
1599 pages
+= (atop_64(addr
+ len
+ PAGE_MASK
) - atop_64(addr
));
1601 assert(len
>= length
); // Check for 32 bit wrap around
1604 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
1606 ppnum_t highPage
= atop_64(addr
+ len
- 1);
1607 if (highPage
> _highestPage
)
1608 _highestPage
= highPage
;
1613 _rangesCount
= count
;
1615 // Auto-prepare memory at creation time.
1616 // Implied completion when descriptor is free-ed
1617 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
1618 _wireCount
++; // Physical MDs are, by definition, wired
1619 else { /* kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO */
1621 unsigned dataSize
= computeDataSize(_pages
, /* upls */ count
* 2);
1623 if (!initMemoryEntries(dataSize
, mapper
)) return false;
1624 dataP
= getDataP(_memoryEntries
);
1625 dataP
->fPageCnt
= _pages
;
1627 if ( (kIOMemoryPersistent
& _flags
) && !_memRef
)
1630 err
= memoryReferenceCreate(0, &_memRef
);
1631 if (kIOReturnSuccess
!= err
) return false;
1634 if ((_flags
& kIOMemoryAutoPrepare
)
1635 && prepare() != kIOReturnSuccess
)
1648 void IOGeneralMemoryDescriptor::free()
1650 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1655 reserved
->dp
.memory
= 0;
1658 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
1661 if (_memoryEntries
&& (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
1663 dataP
->fMapper
->iovmFree(atop_64(dataP
->fMappedBase
), _pages
);
1664 dataP
->fMappedBase
= 0;
1669 while (_wireCount
) complete();
1672 if (_memoryEntries
) _memoryEntries
->release();
1674 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
1676 if (kIOMemoryTypeUIO
== type
)
1677 uio_free((uio_t
) _ranges
.v
);
1679 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
1680 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
1681 #endif /* !__LP64__ */
1683 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
1690 if (reserved
->dp
.devicePager
)
1692 // memEntry holds a ref on the device pager which owns reserved
1693 // (IOMemoryDescriptorReserved) so no reserved access after this point
1694 device_pager_deallocate( (memory_object_t
) reserved
->dp
.devicePager
);
1697 IODelete(reserved
, IOMemoryDescriptorReserved
, 1);
1701 if (_memRef
) memoryReferenceRelease(_memRef
);
1702 if (_prepareLock
) IOLockFree(_prepareLock
);
1708 void IOGeneralMemoryDescriptor::unmapFromKernel()
1710 panic("IOGMD::unmapFromKernel deprecated");
1713 void IOGeneralMemoryDescriptor::mapIntoKernel(unsigned rangeIndex
)
1715 panic("IOGMD::mapIntoKernel deprecated");
1717 #endif /* !__LP64__ */
1722 * Get the direction of the transfer.
1724 IODirection
IOMemoryDescriptor::getDirection() const
1729 #endif /* !__LP64__ */
1730 return (IODirection
) (_flags
& kIOMemoryDirectionMask
);
1736 * Get the length of the transfer (over all ranges).
1738 IOByteCount
IOMemoryDescriptor::getLength() const
1743 void IOMemoryDescriptor::setTag( IOOptionBits tag
)
1748 IOOptionBits
IOMemoryDescriptor::getTag( void )
1754 // @@@ gvdl: who is using this API? Seems like a wierd thing to implement.
1756 IOMemoryDescriptor::getSourceSegment( IOByteCount offset
, IOByteCount
* length
)
1758 addr64_t physAddr
= 0;
1760 if( prepare() == kIOReturnSuccess
) {
1761 physAddr
= getPhysicalSegment64( offset
, length
);
1765 return( (IOPhysicalAddress
) physAddr
); // truncated but only page offset is used
1767 #endif /* !__LP64__ */
1769 IOByteCount
IOMemoryDescriptor::readBytes
1770 (IOByteCount offset
, void *bytes
, IOByteCount length
)
1772 addr64_t dstAddr
= CAST_DOWN(addr64_t
, bytes
);
1773 IOByteCount remaining
;
1775 // Assert that this entire I/O is withing the available range
1776 assert(offset
<= _length
);
1777 assert(offset
+ length
<= _length
);
1778 if (offset
>= _length
) {
1782 if (kIOMemoryThreadSafe
& _flags
)
1785 remaining
= length
= min(length
, _length
- offset
);
1786 while (remaining
) { // (process another target segment?)
1790 srcAddr64
= getPhysicalSegment(offset
, &srcLen
, kIOMemoryMapperNone
);
1794 // Clip segment length to remaining
1795 if (srcLen
> remaining
)
1798 copypv(srcAddr64
, dstAddr
, srcLen
,
1799 cppvPsrc
| cppvNoRefSrc
| cppvFsnk
| cppvKmap
);
1803 remaining
-= srcLen
;
1806 if (kIOMemoryThreadSafe
& _flags
)
1811 return length
- remaining
;
1814 IOByteCount
IOMemoryDescriptor::writeBytes
1815 (IOByteCount inoffset
, const void *bytes
, IOByteCount length
)
1817 addr64_t srcAddr
= CAST_DOWN(addr64_t
, bytes
);
1818 IOByteCount remaining
;
1819 IOByteCount offset
= inoffset
;
1821 // Assert that this entire I/O is withing the available range
1822 assert(offset
<= _length
);
1823 assert(offset
+ length
<= _length
);
1825 assert( !(kIOMemoryPreparedReadOnly
& _flags
) );
1827 if ( (kIOMemoryPreparedReadOnly
& _flags
) || offset
>= _length
) {
1831 if (kIOMemoryThreadSafe
& _flags
)
1834 remaining
= length
= min(length
, _length
- offset
);
1835 while (remaining
) { // (process another target segment?)
1839 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1843 // Clip segment length to remaining
1844 if (dstLen
> remaining
)
1847 if (!srcAddr
) bzero_phys(dstAddr64
, dstLen
);
1850 copypv(srcAddr
, (addr64_t
) dstAddr64
, dstLen
,
1851 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
1855 remaining
-= dstLen
;
1858 if (kIOMemoryThreadSafe
& _flags
)
1863 if (!srcAddr
) performOperation(kIOMemoryIncoherentIOFlush
, inoffset
, length
);
1865 return length
- remaining
;
1869 void IOGeneralMemoryDescriptor::setPosition(IOByteCount position
)
1871 panic("IOGMD::setPosition deprecated");
1873 #endif /* !__LP64__ */
1875 static volatile SInt64 gIOMDPreparationID
__attribute__((aligned(8))) = (1ULL << 32);
1878 IOGeneralMemoryDescriptor::getPreparationID( void )
1883 return (kIOPreparationIDUnprepared
);
1885 if (((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical
)
1886 || ((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical64
))
1888 IOMemoryDescriptor::setPreparationID();
1889 return (IOMemoryDescriptor::getPreparationID());
1892 if (!_memoryEntries
|| !(dataP
= getDataP(_memoryEntries
)))
1893 return (kIOPreparationIDUnprepared
);
1895 if (kIOPreparationIDUnprepared
== dataP
->fPreparationID
)
1897 dataP
->fPreparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1899 return (dataP
->fPreparationID
);
1902 IOMemoryDescriptorReserved
* IOMemoryDescriptor::getKernelReserved( void )
1906 reserved
= IONew(IOMemoryDescriptorReserved
, 1);
1908 bzero(reserved
, sizeof(IOMemoryDescriptorReserved
));
1913 void IOMemoryDescriptor::setPreparationID( void )
1915 if (getKernelReserved() && (kIOPreparationIDUnprepared
== reserved
->preparationID
))
1917 #if defined(__ppc__ )
1918 reserved
->preparationID
= gIOMDPreparationID
++;
1920 reserved
->preparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1925 uint64_t IOMemoryDescriptor::getPreparationID( void )
1928 return (reserved
->preparationID
);
1930 return (kIOPreparationIDUnsupported
);
1933 IOReturn
IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1935 IOReturn err
= kIOReturnSuccess
;
1936 DMACommandOps params
;
1937 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
1940 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
1941 op
&= kIOMDDMACommandOperationMask
;
1943 if (kIOMDDMAMap
== op
)
1945 if (dataSize
< sizeof(IOMDDMAMapArgs
))
1946 return kIOReturnUnderrun
;
1948 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
1951 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1953 if (_memoryEntries
&& data
->fMapper
)
1956 bool whole
= ((data
->fOffset
== 0) && (data
->fLength
== _length
));
1957 dataP
= getDataP(_memoryEntries
);
1959 if (data
->fMapSpec
.numAddressBits
< dataP
->fDMAMapNumAddressBits
) dataP
->fDMAMapNumAddressBits
= data
->fMapSpec
.numAddressBits
;
1960 if (data
->fMapSpec
.alignment
> dataP
->fDMAMapAlignment
) dataP
->fDMAMapAlignment
= data
->fMapSpec
.alignment
;
1962 remap
= (dataP
->fDMAMapNumAddressBits
< 64)
1963 && ((dataP
->fMappedBase
+ _length
) > (1ULL << dataP
->fDMAMapNumAddressBits
));
1964 remap
|= (dataP
->fDMAMapAlignment
> page_size
);
1966 if (remap
|| !dataP
->fMappedBase
)
1968 // if (dataP->fMappedBase) OSReportWithBacktrace("kIOMDDMAMap whole %d remap %d params %d\n", whole, remap, params);
1969 err
= md
->dmaMap(data
->fMapper
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocCount
);
1970 if ((kIOReturnSuccess
== err
) && whole
&& !dataP
->fMappedBase
)
1972 dataP
->fMappedBase
= data
->fAlloc
;
1973 data
->fAllocCount
= 0; // IOMD owns the alloc now
1978 data
->fAlloc
= dataP
->fMappedBase
;
1979 data
->fAllocCount
= 0; // IOMD owns the alloc
1981 data
->fMapContig
= !dataP
->fDiscontig
;
1987 if (kIOMDAddDMAMapSpec
== op
)
1989 if (dataSize
< sizeof(IODMAMapSpecification
))
1990 return kIOReturnUnderrun
;
1992 IODMAMapSpecification
* data
= (IODMAMapSpecification
*) vData
;
1995 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1999 dataP
= getDataP(_memoryEntries
);
2000 if (data
->numAddressBits
< dataP
->fDMAMapNumAddressBits
)
2001 dataP
->fDMAMapNumAddressBits
= data
->numAddressBits
;
2002 if (data
->alignment
> dataP
->fDMAMapAlignment
)
2003 dataP
->fDMAMapAlignment
= data
->alignment
;
2005 return kIOReturnSuccess
;
2008 if (kIOMDGetCharacteristics
== op
) {
2010 if (dataSize
< sizeof(IOMDDMACharacteristics
))
2011 return kIOReturnUnderrun
;
2013 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
2014 data
->fLength
= _length
;
2015 data
->fSGCount
= _rangesCount
;
2016 data
->fPages
= _pages
;
2017 data
->fDirection
= getDirection();
2019 data
->fIsPrepared
= false;
2021 data
->fIsPrepared
= true;
2022 data
->fHighestPage
= _highestPage
;
2025 dataP
= getDataP(_memoryEntries
);
2026 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2027 UInt count
= getNumIOPL(_memoryEntries
, dataP
);
2029 data
->fPageAlign
= (ioplList
[0].fPageOffset
& PAGE_MASK
) | ~PAGE_MASK
;
2033 return kIOReturnSuccess
;
2035 #if IOMD_DEBUG_DMAACTIVE
2036 } else if (kIOMDDMAActive
== op
) {
2037 if (params
) OSIncrementAtomic(&md
->__iomd_reservedA
);
2039 if (md
->__iomd_reservedA
)
2040 OSDecrementAtomic(&md
->__iomd_reservedA
);
2042 panic("kIOMDSetDMAInactive");
2044 #endif /* IOMD_DEBUG_DMAACTIVE */
2046 } else if (kIOMDWalkSegments
!= op
)
2047 return kIOReturnBadArgument
;
2049 // Get the next segment
2050 struct InternalState
{
2051 IOMDDMAWalkSegmentArgs fIO
;
2057 // Find the next segment
2058 if (dataSize
< sizeof(*isP
))
2059 return kIOReturnUnderrun
;
2061 isP
= (InternalState
*) vData
;
2062 UInt offset
= isP
->fIO
.fOffset
;
2063 bool mapped
= isP
->fIO
.fMapped
;
2065 if (IOMapper::gSystem
&& mapped
2066 && (!(kIOMemoryHostOnly
& _flags
))
2067 && (!_memoryEntries
|| !getDataP(_memoryEntries
)->fMappedBase
))
2068 // && (_memoryEntries && !getDataP(_memoryEntries)->fMappedBase))
2071 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
2073 dataP
= getDataP(_memoryEntries
);
2076 IODMAMapSpecification mapSpec
;
2077 bzero(&mapSpec
, sizeof(mapSpec
));
2078 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
2079 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
2080 err
= md
->dmaMap(dataP
->fMapper
, &mapSpec
, 0, _length
, &dataP
->fMappedBase
, NULL
);
2081 if (kIOReturnSuccess
!= err
) return (err
);
2085 if (offset
>= _length
)
2086 return (offset
== _length
)? kIOReturnOverrun
: kIOReturnInternalError
;
2088 // Validate the previous offset
2089 UInt ind
, off2Ind
= isP
->fOffset2Index
;
2092 && (offset
== isP
->fNextOffset
|| off2Ind
<= offset
))
2095 ind
= off2Ind
= 0; // Start from beginning
2101 if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
) {
2103 // Physical address based memory descriptor
2104 const IOPhysicalRange
*physP
= (IOPhysicalRange
*) &_ranges
.p
[0];
2106 // Find the range after the one that contains the offset
2108 for (len
= 0; off2Ind
<= offset
; ind
++) {
2109 len
= physP
[ind
].length
;
2113 // Calculate length within range and starting address
2114 length
= off2Ind
- offset
;
2115 address
= physP
[ind
- 1].address
+ len
- length
;
2117 if (true && mapped
&& _memoryEntries
2118 && (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
2120 address
= dataP
->fMappedBase
+ offset
;
2124 // see how far we can coalesce ranges
2125 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
2126 len
= physP
[ind
].length
;
2133 // correct contiguous check overshoot
2138 else if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
) {
2140 // Physical address based memory descriptor
2141 const IOAddressRange
*physP
= (IOAddressRange
*) &_ranges
.v64
[0];
2143 // Find the range after the one that contains the offset
2145 for (len
= 0; off2Ind
<= offset
; ind
++) {
2146 len
= physP
[ind
].length
;
2150 // Calculate length within range and starting address
2151 length
= off2Ind
- offset
;
2152 address
= physP
[ind
- 1].address
+ len
- length
;
2154 if (true && mapped
&& _memoryEntries
2155 && (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
2157 address
= dataP
->fMappedBase
+ offset
;
2161 // see how far we can coalesce ranges
2162 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
2163 len
= physP
[ind
].length
;
2169 // correct contiguous check overshoot
2173 #endif /* !__LP64__ */
2176 panic("IOGMD: not wired for the IODMACommand");
2178 assert(_memoryEntries
);
2180 dataP
= getDataP(_memoryEntries
);
2181 const ioPLBlock
*ioplList
= getIOPLList(dataP
);
2182 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
2183 upl_page_info_t
*pageList
= getPageList(dataP
);
2185 assert(numIOPLs
> 0);
2187 // Scan through iopl info blocks looking for block containing offset
2188 while (ind
< numIOPLs
&& offset
>= ioplList
[ind
].fIOMDOffset
)
2191 // Go back to actual range as search goes past it
2192 ioPLBlock ioplInfo
= ioplList
[ind
- 1];
2193 off2Ind
= ioplInfo
.fIOMDOffset
;
2196 length
= ioplList
[ind
].fIOMDOffset
;
2199 length
-= offset
; // Remainder within iopl
2201 // Subtract offset till this iopl in total list
2204 // If a mapped address is requested and this is a pre-mapped IOPL
2205 // then just need to compute an offset relative to the mapped base.
2206 if (mapped
&& dataP
->fMappedBase
) {
2207 offset
+= (ioplInfo
.fPageOffset
& PAGE_MASK
);
2208 address
= trunc_page_64(dataP
->fMappedBase
) + ptoa_64(ioplInfo
.fMappedPage
) + offset
;
2209 continue; // Done leave do/while(false) now
2212 // The offset is rebased into the current iopl.
2213 // Now add the iopl 1st page offset.
2214 offset
+= ioplInfo
.fPageOffset
;
2216 // For external UPLs the fPageInfo field points directly to
2217 // the upl's upl_page_info_t array.
2218 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
2219 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
2221 pageList
= &pageList
[ioplInfo
.fPageInfo
];
2223 // Check for direct device non-paged memory
2224 if ( ioplInfo
.fFlags
& kIOPLOnDevice
) {
2225 address
= ptoa_64(pageList
->phys_addr
) + offset
;
2226 continue; // Done leave do/while(false) now
2229 // Now we need compute the index into the pageList
2230 UInt pageInd
= atop_32(offset
);
2231 offset
&= PAGE_MASK
;
2233 // Compute the starting address of this segment
2234 IOPhysicalAddress pageAddr
= pageList
[pageInd
].phys_addr
;
2236 panic("!pageList phys_addr");
2239 address
= ptoa_64(pageAddr
) + offset
;
2241 // length is currently set to the length of the remainider of the iopl.
2242 // We need to check that the remainder of the iopl is contiguous.
2243 // This is indicated by pageList[ind].phys_addr being sequential.
2244 IOByteCount contigLength
= PAGE_SIZE
- offset
;
2245 while (contigLength
< length
2246 && ++pageAddr
== pageList
[++pageInd
].phys_addr
)
2248 contigLength
+= PAGE_SIZE
;
2251 if (contigLength
< length
)
2252 length
= contigLength
;
2260 // Update return values and state
2261 isP
->fIO
.fIOVMAddr
= address
;
2262 isP
->fIO
.fLength
= length
;
2264 isP
->fOffset2Index
= off2Ind
;
2265 isP
->fNextOffset
= isP
->fIO
.fOffset
+ length
;
2267 return kIOReturnSuccess
;
2271 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
2274 mach_vm_address_t address
= 0;
2275 mach_vm_size_t length
= 0;
2276 IOMapper
* mapper
= gIOSystemMapper
;
2277 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2279 if (lengthOfSegment
)
2280 *lengthOfSegment
= 0;
2282 if (offset
>= _length
)
2285 // IOMemoryDescriptor::doMap() cannot use getPhysicalSegment() to obtain the page offset, since it must
2286 // support the unwired memory case in IOGeneralMemoryDescriptor, and hibernate_write_image() cannot use
2287 // map()->getVirtualAddress() to obtain the kernel pointer, since it must prevent the memory allocation
2288 // due to IOMemoryMap, so _kIOMemorySourceSegment is a necessary evil until all of this gets cleaned up
2290 if ((options
& _kIOMemorySourceSegment
) && (kIOMemoryTypeUPL
!= type
))
2292 unsigned rangesIndex
= 0;
2293 Ranges vec
= _ranges
;
2294 mach_vm_address_t addr
;
2296 // Find starting address within the vector of ranges
2298 getAddrLenForInd(addr
, length
, type
, vec
, rangesIndex
);
2299 if (offset
< length
)
2301 offset
-= length
; // (make offset relative)
2305 // Now that we have the starting range,
2306 // lets find the last contiguous range
2310 for ( ++rangesIndex
; rangesIndex
< _rangesCount
; rangesIndex
++ ) {
2311 mach_vm_address_t newAddr
;
2312 mach_vm_size_t newLen
;
2314 getAddrLenForInd(newAddr
, newLen
, type
, vec
, rangesIndex
);
2315 if (addr
+ length
!= newAddr
)
2320 address
= (IOPhysicalAddress
) addr
; // Truncate address to 32bit
2324 IOMDDMAWalkSegmentState _state
;
2325 IOMDDMAWalkSegmentArgs
* state
= (IOMDDMAWalkSegmentArgs
*) (void *)&_state
;
2327 state
->fOffset
= offset
;
2328 state
->fLength
= _length
- offset
;
2329 state
->fMapped
= (0 == (options
& kIOMemoryMapperNone
)) && !(_flags
& kIOMemoryHostOnly
);
2331 ret
= dmaCommandOperation(kIOMDFirstSegment
, _state
, sizeof(_state
));
2333 if ((kIOReturnSuccess
!= ret
) && (kIOReturnOverrun
!= ret
))
2334 DEBG("getPhysicalSegment dmaCommandOperation(%lx), %p, offset %qx, addr %qx, len %qx\n",
2335 ret
, this, state
->fOffset
,
2336 state
->fIOVMAddr
, state
->fLength
);
2337 if (kIOReturnSuccess
== ret
)
2339 address
= state
->fIOVMAddr
;
2340 length
= state
->fLength
;
2343 // dmaCommandOperation() does not distinguish between "mapped" and "unmapped" physical memory, even
2344 // with fMapped set correctly, so we must handle the transformation here until this gets cleaned up
2346 if (mapper
&& ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
)))
2348 if ((options
& kIOMemoryMapperNone
) && !(_flags
& kIOMemoryMapperNone
))
2350 addr64_t origAddr
= address
;
2351 IOByteCount origLen
= length
;
2353 address
= mapper
->mapAddr(origAddr
);
2354 length
= page_size
- (address
& (page_size
- 1));
2355 while ((length
< origLen
)
2356 && ((address
+ length
) == mapper
->mapAddr(origAddr
+ length
)))
2357 length
+= page_size
;
2358 if (length
> origLen
)
2367 if (lengthOfSegment
)
2368 *lengthOfSegment
= length
;
2375 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
2377 addr64_t address
= 0;
2379 if (options
& _kIOMemorySourceSegment
)
2381 address
= getSourceSegment(offset
, lengthOfSegment
);
2383 else if (options
& kIOMemoryMapperNone
)
2385 address
= getPhysicalSegment64(offset
, lengthOfSegment
);
2389 address
= getPhysicalSegment(offset
, lengthOfSegment
);
2396 IOGeneralMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2398 return (getPhysicalSegment(offset
, lengthOfSegment
, kIOMemoryMapperNone
));
2402 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2404 addr64_t address
= 0;
2405 IOByteCount length
= 0;
2407 address
= getPhysicalSegment(offset
, lengthOfSegment
, 0);
2409 if (lengthOfSegment
)
2410 length
= *lengthOfSegment
;
2412 if ((address
+ length
) > 0x100000000ULL
)
2414 panic("getPhysicalSegment() out of 32b range 0x%qx, len 0x%lx, class %s",
2415 address
, (long) length
, (getMetaClass())->getClassName());
2418 return ((IOPhysicalAddress
) address
);
2422 IOMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2424 IOPhysicalAddress phys32
;
2427 IOMapper
* mapper
= 0;
2429 phys32
= getPhysicalSegment(offset
, lengthOfSegment
);
2433 if (gIOSystemMapper
)
2434 mapper
= gIOSystemMapper
;
2438 IOByteCount origLen
;
2440 phys64
= mapper
->mapAddr(phys32
);
2441 origLen
= *lengthOfSegment
;
2442 length
= page_size
- (phys64
& (page_size
- 1));
2443 while ((length
< origLen
)
2444 && ((phys64
+ length
) == mapper
->mapAddr(phys32
+ length
)))
2445 length
+= page_size
;
2446 if (length
> origLen
)
2449 *lengthOfSegment
= length
;
2452 phys64
= (addr64_t
) phys32
;
2458 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2460 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, 0));
2464 IOGeneralMemoryDescriptor::getSourceSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2466 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, _kIOMemorySourceSegment
));
2469 void * IOGeneralMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
2470 IOByteCount
* lengthOfSegment
)
2472 if (_task
== kernel_task
)
2473 return (void *) getSourceSegment(offset
, lengthOfSegment
);
2475 panic("IOGMD::getVirtualSegment deprecated");
2479 #endif /* !__LP64__ */
2482 IOMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
2484 IOMemoryDescriptor
*md
= const_cast<IOMemoryDescriptor
*>(this);
2485 DMACommandOps params
;
2488 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
2489 op
&= kIOMDDMACommandOperationMask
;
2491 if (kIOMDGetCharacteristics
== op
) {
2492 if (dataSize
< sizeof(IOMDDMACharacteristics
))
2493 return kIOReturnUnderrun
;
2495 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
2496 data
->fLength
= getLength();
2498 data
->fDirection
= getDirection();
2499 data
->fIsPrepared
= true; // Assume prepared - fails safe
2501 else if (kIOMDWalkSegments
== op
) {
2502 if (dataSize
< sizeof(IOMDDMAWalkSegmentArgs
))
2503 return kIOReturnUnderrun
;
2505 IOMDDMAWalkSegmentArgs
*data
= (IOMDDMAWalkSegmentArgs
*) vData
;
2506 IOByteCount offset
= (IOByteCount
) data
->fOffset
;
2508 IOPhysicalLength length
;
2509 if (data
->fMapped
&& IOMapper::gSystem
)
2510 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
);
2512 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
, kIOMemoryMapperNone
);
2513 data
->fLength
= length
;
2515 else if (kIOMDAddDMAMapSpec
== op
) return kIOReturnUnsupported
;
2516 else if (kIOMDDMAMap
== op
)
2518 if (dataSize
< sizeof(IOMDDMAMapArgs
))
2519 return kIOReturnUnderrun
;
2520 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
2522 if (params
) panic("class %s does not support IODMACommand::kIterateOnly", getMetaClass()->getClassName());
2524 data
->fMapContig
= true;
2525 err
= md
->dmaMap(data
->fMapper
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocCount
);
2528 else return kIOReturnBadArgument
;
2530 return kIOReturnSuccess
;
2534 IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState
,
2535 IOOptionBits
* oldState
)
2537 IOReturn err
= kIOReturnSuccess
;
2539 vm_purgable_t control
;
2544 err
= super::setPurgeable(newState
, oldState
);
2548 if (kIOMemoryThreadSafe
& _flags
)
2552 // Find the appropriate vm_map for the given task
2554 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
2556 err
= kIOReturnNotReady
;
2561 err
= kIOReturnUnsupported
;
2565 curMap
= get_task_map(_task
);
2567 // can only do one range
2568 Ranges vec
= _ranges
;
2569 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2570 mach_vm_address_t addr
;
2572 getAddrLenForInd(addr
, len
, type
, vec
, 0);
2574 err
= purgeableControlBits(newState
, &control
, &state
);
2575 if (kIOReturnSuccess
!= err
)
2577 err
= mach_vm_purgable_control(curMap
, addr
, control
, &state
);
2580 if (kIOReturnSuccess
== err
)
2582 err
= purgeableStateBits(&state
);
2588 if (kIOMemoryThreadSafe
& _flags
)
2595 IOReturn
IOMemoryDescriptor::setPurgeable( IOOptionBits newState
,
2596 IOOptionBits
* oldState
)
2598 IOReturn err
= kIOReturnNotReady
;
2600 if (kIOMemoryThreadSafe
& _flags
) LOCK
;
2601 if (_memRef
) err
= IOGeneralMemoryDescriptor::memoryReferenceSetPurgeable(_memRef
, newState
, oldState
);
2602 if (kIOMemoryThreadSafe
& _flags
) UNLOCK
;
2607 IOReturn
IOMemoryDescriptor::getPageCounts( IOByteCount
* residentPageCount
,
2608 IOByteCount
* dirtyPageCount
)
2610 IOReturn err
= kIOReturnNotReady
;
2612 if (kIOMemoryThreadSafe
& _flags
) LOCK
;
2613 if (_memRef
) err
= IOGeneralMemoryDescriptor::memoryReferenceGetPageCounts(_memRef
, residentPageCount
, dirtyPageCount
);
2614 if (kIOMemoryThreadSafe
& _flags
) UNLOCK
;
2620 extern "C" void dcache_incoherent_io_flush64(addr64_t pa
, unsigned int count
);
2621 extern "C" void dcache_incoherent_io_store64(addr64_t pa
, unsigned int count
);
2623 static void SetEncryptOp(addr64_t pa
, unsigned int count
)
2627 page
= atop_64(round_page_64(pa
));
2628 end
= atop_64(trunc_page_64(pa
+ count
));
2629 for (; page
< end
; page
++)
2631 pmap_clear_noencrypt(page
);
2635 static void ClearEncryptOp(addr64_t pa
, unsigned int count
)
2639 page
= atop_64(round_page_64(pa
));
2640 end
= atop_64(trunc_page_64(pa
+ count
));
2641 for (; page
< end
; page
++)
2643 pmap_set_noencrypt(page
);
2647 IOReturn
IOMemoryDescriptor::performOperation( IOOptionBits options
,
2648 IOByteCount offset
, IOByteCount length
)
2650 IOByteCount remaining
;
2652 void (*func
)(addr64_t pa
, unsigned int count
) = 0;
2656 case kIOMemoryIncoherentIOFlush
:
2657 func
= &dcache_incoherent_io_flush64
;
2659 case kIOMemoryIncoherentIOStore
:
2660 func
= &dcache_incoherent_io_store64
;
2663 case kIOMemorySetEncrypted
:
2664 func
= &SetEncryptOp
;
2666 case kIOMemoryClearEncrypted
:
2667 func
= &ClearEncryptOp
;
2672 return (kIOReturnUnsupported
);
2674 if (kIOMemoryThreadSafe
& _flags
)
2678 remaining
= length
= min(length
, getLength() - offset
);
2680 // (process another target segment?)
2685 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
2689 // Clip segment length to remaining
2690 if (dstLen
> remaining
)
2693 (*func
)(dstAddr64
, dstLen
);
2696 remaining
-= dstLen
;
2699 if (kIOMemoryThreadSafe
& _flags
)
2702 return (remaining
? kIOReturnUnderrun
: kIOReturnSuccess
);
2705 #if defined(__i386__) || defined(__x86_64__)
2706 extern vm_offset_t first_avail
;
2707 #define io_kernel_static_end first_avail
2709 #error io_kernel_static_end is undefined for this architecture
2712 static kern_return_t
2713 io_get_kernel_static_upl(
2716 vm_size_t
*upl_size
,
2718 upl_page_info_array_t page_list
,
2719 unsigned int *count
,
2720 ppnum_t
*highest_page
)
2722 unsigned int pageCount
, page
;
2724 ppnum_t highestPage
= 0;
2726 pageCount
= atop_32(*upl_size
);
2727 if (pageCount
> *count
)
2732 for (page
= 0; page
< pageCount
; page
++)
2734 phys
= pmap_find_phys(kernel_pmap
, ((addr64_t
)offset
) + ptoa_64(page
));
2737 page_list
[page
].phys_addr
= phys
;
2738 page_list
[page
].pageout
= 0;
2739 page_list
[page
].absent
= 0;
2740 page_list
[page
].dirty
= 0;
2741 page_list
[page
].precious
= 0;
2742 page_list
[page
].device
= 0;
2743 if (phys
> highestPage
)
2747 *highest_page
= highestPage
;
2749 return ((page
>= pageCount
) ? kIOReturnSuccess
: kIOReturnVMError
);
2752 IOReturn
IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection
)
2754 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2755 IOReturn error
= kIOReturnCannotWire
;
2757 upl_page_info_array_t pageInfo
;
2760 assert(kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
);
2762 if ((kIODirectionOutIn
& forDirection
) == kIODirectionNone
)
2763 forDirection
= (IODirection
) (forDirection
| getDirection());
2765 int uplFlags
; // This Mem Desc's default flags for upl creation
2766 switch (kIODirectionOutIn
& forDirection
)
2768 case kIODirectionOut
:
2769 // Pages do not need to be marked as dirty on commit
2770 uplFlags
= UPL_COPYOUT_FROM
;
2773 case kIODirectionIn
:
2775 uplFlags
= 0; // i.e. ~UPL_COPYOUT_FROM
2781 if ((kIOMemoryPreparedReadOnly
& _flags
) && !(UPL_COPYOUT_FROM
& uplFlags
))
2783 OSReportWithBacktrace("IOMemoryDescriptor 0x%lx prepared read only", VM_KERNEL_ADDRPERM(this));
2784 error
= kIOReturnNotWritable
;
2786 else error
= kIOReturnSuccess
;
2790 dataP
= getDataP(_memoryEntries
);
2792 mapper
= dataP
->fMapper
;
2793 dataP
->fMappedBase
= 0;
2795 uplFlags
|= UPL_SET_IO_WIRE
| UPL_SET_LITE
;
2796 if (kIODirectionPrepareToPhys32
& forDirection
)
2798 if (!mapper
) uplFlags
|= UPL_NEED_32BIT_ADDR
;
2799 if (dataP
->fDMAMapNumAddressBits
> 32) dataP
->fDMAMapNumAddressBits
= 32;
2801 if (kIODirectionPrepareNoFault
& forDirection
) uplFlags
|= UPL_REQUEST_NO_FAULT
;
2802 if (kIODirectionPrepareNoZeroFill
& forDirection
) uplFlags
|= UPL_NOZEROFILLIO
;
2803 if (kIODirectionPrepareNonCoherent
& forDirection
) uplFlags
|= UPL_REQUEST_FORCE_COHERENCY
;
2807 // Note that appendBytes(NULL) zeros the data up to the desired length
2808 // and the length parameter is an unsigned int
2809 size_t uplPageSize
= dataP
->fPageCnt
* sizeof(upl_page_info_t
);
2810 if (uplPageSize
> ((unsigned int)uplPageSize
)) return (kIOReturnNoMemory
);
2811 if (!_memoryEntries
->appendBytes(0, uplPageSize
)) return (kIOReturnNoMemory
);
2814 // Find the appropriate vm_map for the given task
2816 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
)) curMap
= 0;
2817 else curMap
= get_task_map(_task
);
2819 // Iterate over the vector of virtual ranges
2820 Ranges vec
= _ranges
;
2821 unsigned int pageIndex
= 0;
2822 IOByteCount mdOffset
= 0;
2823 ppnum_t highestPage
= 0;
2825 IOMemoryEntry
* memRefEntry
= 0;
2826 if (_memRef
) memRefEntry
= &_memRef
->entries
[0];
2828 for (UInt range
= 0; range
< _rangesCount
; range
++) {
2830 mach_vm_address_t startPage
;
2831 mach_vm_size_t numBytes
;
2832 ppnum_t highPage
= 0;
2834 // Get the startPage address and length of vec[range]
2835 getAddrLenForInd(startPage
, numBytes
, type
, vec
, range
);
2836 iopl
.fPageOffset
= startPage
& PAGE_MASK
;
2837 numBytes
+= iopl
.fPageOffset
;
2838 startPage
= trunc_page_64(startPage
);
2841 iopl
.fMappedPage
= mapBase
+ pageIndex
;
2843 iopl
.fMappedPage
= 0;
2845 // Iterate over the current range, creating UPLs
2847 vm_address_t kernelStart
= (vm_address_t
) startPage
;
2849 if (curMap
) theMap
= curMap
;
2856 assert(_task
== kernel_task
);
2857 theMap
= IOPageableMapForAddress(kernelStart
);
2860 int ioplFlags
= uplFlags
;
2861 dataP
= getDataP(_memoryEntries
);
2862 pageInfo
= getPageList(dataP
);
2863 upl_page_list_ptr_t baseInfo
= &pageInfo
[pageIndex
];
2865 vm_size_t ioplSize
= round_page(numBytes
);
2866 unsigned int numPageInfo
= atop_32(ioplSize
);
2868 if ((theMap
== kernel_map
) && (kernelStart
< io_kernel_static_end
)) {
2869 error
= io_get_kernel_static_upl(theMap
,
2878 memory_object_offset_t entryOffset
;
2880 entryOffset
= (mdOffset
- iopl
.fPageOffset
- memRefEntry
->offset
);
2881 if (entryOffset
>= memRefEntry
->size
) {
2883 if (memRefEntry
>= &_memRef
->entries
[_memRef
->count
]) panic("memRefEntry");
2886 if (ioplSize
> (memRefEntry
->size
- entryOffset
)) ioplSize
= (memRefEntry
->size
- entryOffset
);
2887 error
= memory_object_iopl_request(memRefEntry
->entry
,
2897 error
= vm_map_create_upl(theMap
,
2899 (upl_size_t
*)&ioplSize
,
2907 if (error
!= KERN_SUCCESS
)
2911 highPage
= upl_get_highest_page(iopl
.fIOPL
);
2912 if (highPage
> highestPage
)
2913 highestPage
= highPage
;
2915 error
= kIOReturnCannotWire
;
2917 if (baseInfo
->device
) {
2919 iopl
.fFlags
= kIOPLOnDevice
;
2925 iopl
.fIOMDOffset
= mdOffset
;
2926 iopl
.fPageInfo
= pageIndex
;
2927 if (mapper
&& pageIndex
&& (page_mask
& (mdOffset
+ iopl
.fPageOffset
))) dataP
->fDiscontig
= true;
2930 // used to remove the upl for auto prepares here, for some errant code
2931 // that freed memory before the descriptor pointing at it
2932 if ((_flags
& kIOMemoryAutoPrepare
) && iopl
.fIOPL
)
2934 upl_commit(iopl
.fIOPL
, 0, 0);
2935 upl_deallocate(iopl
.fIOPL
);
2940 if (!_memoryEntries
->appendBytes(&iopl
, sizeof(iopl
))) {
2941 // Clean up partial created and unsaved iopl
2943 upl_abort(iopl
.fIOPL
, 0);
2944 upl_deallocate(iopl
.fIOPL
);
2950 // Check for a multiple iopl's in one virtual range
2951 pageIndex
+= numPageInfo
;
2952 mdOffset
-= iopl
.fPageOffset
;
2953 if (ioplSize
< numBytes
) {
2954 numBytes
-= ioplSize
;
2955 startPage
+= ioplSize
;
2956 mdOffset
+= ioplSize
;
2957 iopl
.fPageOffset
= 0;
2958 if (mapper
) iopl
.fMappedPage
= mapBase
+ pageIndex
;
2961 mdOffset
+= numBytes
;
2967 _highestPage
= highestPage
;
2969 if (UPL_COPYOUT_FROM
& uplFlags
) _flags
|= kIOMemoryPreparedReadOnly
;
2971 return kIOReturnSuccess
;
2975 dataP
= getDataP(_memoryEntries
);
2976 UInt done
= getNumIOPL(_memoryEntries
, dataP
);
2977 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2979 for (UInt range
= 0; range
< done
; range
++)
2981 if (ioplList
[range
].fIOPL
) {
2982 upl_abort(ioplList
[range
].fIOPL
, 0);
2983 upl_deallocate(ioplList
[range
].fIOPL
);
2986 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
2989 if (error
== KERN_FAILURE
)
2990 error
= kIOReturnCannotWire
;
2991 else if (error
== KERN_MEMORY_ERROR
)
2992 error
= kIOReturnNoResources
;
2997 bool IOGeneralMemoryDescriptor::initMemoryEntries(size_t size
, IOMapper
* mapper
)
3000 unsigned dataSize
= size
;
3002 if (!_memoryEntries
) {
3003 _memoryEntries
= OSData::withCapacity(dataSize
);
3004 if (!_memoryEntries
)
3007 else if (!_memoryEntries
->initWithCapacity(dataSize
))
3010 _memoryEntries
->appendBytes(0, computeDataSize(0, 0));
3011 dataP
= getDataP(_memoryEntries
);
3013 if (mapper
== kIOMapperWaitSystem
) {
3014 IOMapper::checkForSystemMapper();
3015 mapper
= IOMapper::gSystem
;
3017 dataP
->fMapper
= mapper
;
3018 dataP
->fPageCnt
= 0;
3019 dataP
->fMappedBase
= 0;
3020 dataP
->fDMAMapNumAddressBits
= 64;
3021 dataP
->fDMAMapAlignment
= 0;
3022 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
3023 dataP
->fDiscontig
= false;
3024 dataP
->fCompletionError
= false;
3029 IOReturn
IOMemoryDescriptor::dmaMap(
3031 const IODMAMapSpecification
* mapSpec
,
3037 IOMDDMAWalkSegmentState walkState
;
3038 IOMDDMAWalkSegmentArgs
* walkArgs
= (IOMDDMAWalkSegmentArgs
*) (void *)&walkState
;
3041 IOPhysicalLength segLen
;
3042 addr64_t phys
, align
, pageOffset
;
3043 ppnum_t base
, pageIndex
, pageCount
;
3045 uint32_t mapOptions
= 0;
3047 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
3049 walkArgs
->fMapped
= false;
3050 mdOp
= kIOMDFirstSegment
;
3052 for (index
= 0; index
< length
; )
3054 if (index
&& (page_mask
& (index
+ pageOffset
))) break;
3056 walkArgs
->fOffset
= offset
+ index
;
3057 ret
= dmaCommandOperation(mdOp
, &walkState
, sizeof(walkState
));
3058 mdOp
= kIOMDWalkSegments
;
3059 if (ret
!= kIOReturnSuccess
) break;
3060 phys
= walkArgs
->fIOVMAddr
;
3061 segLen
= walkArgs
->fLength
;
3063 align
= (phys
& page_mask
);
3064 if (!index
) pageOffset
= align
;
3065 else if (align
) break;
3066 pageCount
+= atop_64(round_page_64(align
+ segLen
));
3070 if (index
< length
) return (kIOReturnVMError
);
3072 base
= mapper
->iovmMapMemory(this, offset
, pageCount
,
3073 mapOptions
, NULL
, mapSpec
);
3075 if (!base
) return (kIOReturnNoResources
);
3077 mdOp
= kIOMDFirstSegment
;
3078 for (pageIndex
= 0, index
= 0; index
< length
; )
3080 walkArgs
->fOffset
= offset
+ index
;
3081 ret
= dmaCommandOperation(mdOp
, &walkState
, sizeof(walkState
));
3082 mdOp
= kIOMDWalkSegments
;
3083 if (ret
!= kIOReturnSuccess
) break;
3084 phys
= walkArgs
->fIOVMAddr
;
3085 segLen
= walkArgs
->fLength
;
3087 ppnum_t page
= atop_64(phys
);
3088 ppnum_t count
= atop_64(round_page_64(phys
+ segLen
)) - page
;
3091 mapper
->iovmInsert(base
, pageIndex
, page
);
3097 if (pageIndex
!= pageCount
) panic("pageIndex");
3099 *address
= ptoa_64(base
) + pageOffset
;
3100 if (mapPages
) *mapPages
= pageCount
;
3102 return (kIOReturnSuccess
);
3105 IOReturn
IOGeneralMemoryDescriptor::dmaMap(
3107 const IODMAMapSpecification
* mapSpec
,
3113 IOReturn err
= kIOReturnSuccess
;
3115 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3118 if (kIOMemoryHostOnly
& _flags
) return (kIOReturnSuccess
);
3120 if ((type
== kIOMemoryTypePhysical
) || (type
== kIOMemoryTypePhysical64
)
3121 || offset
|| (length
!= _length
))
3123 err
= super::dmaMap(mapper
, mapSpec
, offset
, length
, address
, mapPages
);
3125 else if (_memoryEntries
&& _pages
&& (dataP
= getDataP(_memoryEntries
)))
3127 const ioPLBlock
* ioplList
= getIOPLList(dataP
);
3128 upl_page_info_t
* pageList
;
3129 uint32_t mapOptions
= 0;
3132 IODMAMapSpecification mapSpec
;
3133 bzero(&mapSpec
, sizeof(mapSpec
));
3134 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
3135 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
3137 // For external UPLs the fPageInfo field points directly to
3138 // the upl's upl_page_info_t array.
3139 if (ioplList
->fFlags
& kIOPLExternUPL
)
3141 pageList
= (upl_page_info_t
*) ioplList
->fPageInfo
;
3142 mapOptions
|= kIODMAMapPagingPath
;
3145 pageList
= getPageList(dataP
);
3147 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
3149 // Check for direct device non-paged memory
3150 if (ioplList
->fFlags
& kIOPLOnDevice
) mapOptions
|= kIODMAMapPhysicallyContiguous
;
3152 base
= mapper
->iovmMapMemory(
3153 this, offset
, _pages
, mapOptions
, &pageList
[0], &mapSpec
);
3154 *address
= ptoa_64(base
) + (ioplList
->fPageOffset
& PAGE_MASK
);
3155 if (mapPages
) *mapPages
= _pages
;
3164 * Prepare the memory for an I/O transfer. This involves paging in
3165 * the memory, if necessary, and wiring it down for the duration of
3166 * the transfer. The complete() method completes the processing of
3167 * the memory after the I/O transfer finishes. This method needn't
3168 * called for non-pageable memory.
3171 IOReturn
IOGeneralMemoryDescriptor::prepare(IODirection forDirection
)
3173 IOReturn error
= kIOReturnSuccess
;
3174 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3176 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
3177 return kIOReturnSuccess
;
3180 IOLockLock(_prepareLock
);
3182 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
)
3184 error
= wireVirtual(forDirection
);
3187 if (kIOReturnSuccess
== error
)
3189 if (1 == ++_wireCount
)
3191 if (kIOMemoryClearEncrypt
& _flags
)
3193 performOperation(kIOMemoryClearEncrypted
, 0, _length
);
3199 IOLockUnlock(_prepareLock
);
3207 * Complete processing of the memory after an I/O transfer finishes.
3208 * This method should not be called unless a prepare was previously
3209 * issued; the prepare() and complete() must occur in pairs, before
3210 * before and after an I/O transfer involving pageable memory.
3213 IOReturn
IOGeneralMemoryDescriptor::complete(IODirection forDirection
)
3215 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3218 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
3219 return kIOReturnSuccess
;
3222 IOLockLock(_prepareLock
);
3226 if ((kIODirectionCompleteWithError
& forDirection
)
3227 && (dataP
= getDataP(_memoryEntries
)))
3228 dataP
->fCompletionError
= true;
3232 if ((kIOMemoryClearEncrypt
& _flags
) && (1 == _wireCount
))
3234 performOperation(kIOMemorySetEncrypted
, 0, _length
);
3238 if (!_wireCount
|| (kIODirectionCompleteWithDataValid
& forDirection
))
3240 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3241 dataP
= getDataP(_memoryEntries
);
3242 ioPLBlock
*ioplList
= getIOPLList(dataP
);
3243 UInt ind
, count
= getNumIOPL(_memoryEntries
, dataP
);
3247 // kIODirectionCompleteWithDataValid & forDirection
3248 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
)
3250 for (ind
= 0; ind
< count
; ind
++)
3252 if (ioplList
[ind
].fIOPL
) iopl_valid_data(ioplList
[ind
].fIOPL
);
3258 #if IOMD_DEBUG_DMAACTIVE
3259 if (__iomd_reservedA
) panic("complete() while dma active");
3260 #endif /* IOMD_DEBUG_DMAACTIVE */
3262 if (dataP
->fMappedBase
) {
3263 dataP
->fMapper
->iovmFree(atop_64(dataP
->fMappedBase
), _pages
);
3264 dataP
->fMappedBase
= 0;
3266 // Only complete iopls that we created which are for TypeVirtual
3267 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) {
3268 for (ind
= 0; ind
< count
; ind
++)
3269 if (ioplList
[ind
].fIOPL
) {
3270 if (dataP
->fCompletionError
)
3271 upl_abort(ioplList
[ind
].fIOPL
, 0 /*!UPL_ABORT_DUMP_PAGES*/);
3273 upl_commit(ioplList
[ind
].fIOPL
, 0, 0);
3274 upl_deallocate(ioplList
[ind
].fIOPL
);
3276 } else if (kIOMemoryTypeUPL
== type
) {
3277 upl_set_referenced(ioplList
[0].fIOPL
, false);
3280 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
3282 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
3288 IOLockUnlock(_prepareLock
);
3290 return kIOReturnSuccess
;
3293 IOReturn
IOGeneralMemoryDescriptor::doMap(
3294 vm_map_t __addressMap
,
3295 IOVirtualAddress
* __address
,
3296 IOOptionBits options
,
3297 IOByteCount __offset
,
3298 IOByteCount __length
)
3302 if (!(kIOMap64Bit
& options
)) panic("IOGeneralMemoryDescriptor::doMap !64bit");
3303 #endif /* !__LP64__ */
3307 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
3308 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3309 mach_vm_size_t length
= mapping
->fLength
;
3311 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3312 Ranges vec
= _ranges
;
3314 mach_vm_address_t range0Addr
= 0;
3315 mach_vm_size_t range0Len
= 0;
3317 if ((offset
>= _length
) || ((offset
+ length
) > _length
))
3318 return( kIOReturnBadArgument
);
3321 getAddrLenForInd(range0Addr
, range0Len
, type
, vec
, 0);
3323 // mapping source == dest? (could be much better)
3325 && (mapping
->fAddressTask
== _task
)
3326 && (mapping
->fAddressMap
== get_task_map(_task
))
3327 && (options
& kIOMapAnywhere
)
3328 && (1 == _rangesCount
)
3331 && (length
<= range0Len
))
3333 mapping
->fAddress
= range0Addr
;
3334 mapping
->fOptions
|= kIOMapStatic
;
3336 return( kIOReturnSuccess
);
3341 IOOptionBits createOptions
= 0;
3342 if (!(kIOMapReadOnly
& options
))
3344 createOptions
|= kIOMemoryReferenceWrite
;
3345 #if DEVELOPMENT || DEBUG
3346 if (kIODirectionOut
== (kIODirectionOutIn
& _flags
))
3348 OSReportWithBacktrace("warning: creating writable mapping from IOMemoryDescriptor(kIODirectionOut) - use kIOMapReadOnly or change direction");
3352 err
= memoryReferenceCreate(createOptions
, &_memRef
);
3353 if (kIOReturnSuccess
!= err
) return (err
);
3356 memory_object_t pager
;
3357 pager
= (memory_object_t
) (reserved
? reserved
->dp
.devicePager
: 0);
3359 // <upl_transpose //
3360 if ((kIOMapReference
|kIOMapUnique
) == ((kIOMapReference
|kIOMapUnique
) & options
))
3367 unsigned int lock_count
;
3369 if (!_memRef
|| (1 != _memRef
->count
))
3371 err
= kIOReturnNotReadable
;
3375 size
= round_page(mapping
->fLength
);
3376 flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3377 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
3379 if (KERN_SUCCESS
!= memory_object_iopl_request(_memRef
->entries
[0].entry
, 0, &size
, &redirUPL2
,
3384 for (lock_count
= 0;
3385 IORecursiveLockHaveLock(gIOMemoryLock
);
3389 err
= upl_transpose(redirUPL2
, mapping
->fRedirUPL
);
3396 if (kIOReturnSuccess
!= err
)
3398 IOLog("upl_transpose(%x)\n", err
);
3399 err
= kIOReturnSuccess
;
3404 upl_commit(redirUPL2
, NULL
, 0);
3405 upl_deallocate(redirUPL2
);
3409 // swap the memEntries since they now refer to different vm_objects
3410 IOMemoryReference
* me
= _memRef
;
3411 _memRef
= mapping
->fMemory
->_memRef
;
3412 mapping
->fMemory
->_memRef
= me
;
3415 err
= populateDevicePager( pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
3419 // upl_transpose> //
3422 err
= memoryReferenceMap(_memRef
, mapping
->fAddressMap
, offset
, length
, options
, &mapping
->fAddress
);
3424 if ((err
== KERN_SUCCESS
) && pager
)
3426 err
= populateDevicePager(pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
3427 if (err
!= KERN_SUCCESS
)
3429 doUnmap(mapping
->fAddressMap
, (IOVirtualAddress
) mapping
, 0);
3431 else if (kIOMapDefaultCache
== (options
& kIOMapCacheMask
))
3433 mapping
->fOptions
|= ((_flags
& kIOMemoryBufferCacheMask
) >> kIOMemoryBufferCacheShift
);
3441 IOReturn
IOGeneralMemoryDescriptor::doUnmap(
3442 vm_map_t addressMap
,
3443 IOVirtualAddress __address
,
3444 IOByteCount __length
)
3446 return (super::doUnmap(addressMap
, __address
, __length
));
3449 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3452 #define super OSObject
3454 OSDefineMetaClassAndStructors( IOMemoryMap
, OSObject
)
3456 OSMetaClassDefineReservedUnused(IOMemoryMap
, 0);
3457 OSMetaClassDefineReservedUnused(IOMemoryMap
, 1);
3458 OSMetaClassDefineReservedUnused(IOMemoryMap
, 2);
3459 OSMetaClassDefineReservedUnused(IOMemoryMap
, 3);
3460 OSMetaClassDefineReservedUnused(IOMemoryMap
, 4);
3461 OSMetaClassDefineReservedUnused(IOMemoryMap
, 5);
3462 OSMetaClassDefineReservedUnused(IOMemoryMap
, 6);
3463 OSMetaClassDefineReservedUnused(IOMemoryMap
, 7);
3465 /* ex-inline function implementation */
3466 IOPhysicalAddress
IOMemoryMap::getPhysicalAddress()
3467 { return( getPhysicalSegment( 0, 0 )); }
3469 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3471 bool IOMemoryMap::init(
3473 mach_vm_address_t toAddress
,
3474 IOOptionBits _options
,
3475 mach_vm_size_t _offset
,
3476 mach_vm_size_t _length
)
3484 fAddressMap
= get_task_map(intoTask
);
3487 vm_map_reference(fAddressMap
);
3489 fAddressTask
= intoTask
;
3490 fOptions
= _options
;
3493 fAddress
= toAddress
;
3498 bool IOMemoryMap::setMemoryDescriptor(IOMemoryDescriptor
* _memory
, mach_vm_size_t _offset
)
3505 if( (_offset
+ fLength
) > _memory
->getLength())
3513 if (fMemory
!= _memory
)
3514 fMemory
->removeMapping(this);
3522 IOReturn
IOMemoryDescriptor::doMap(
3523 vm_map_t __addressMap
,
3524 IOVirtualAddress
* __address
,
3525 IOOptionBits options
,
3526 IOByteCount __offset
,
3527 IOByteCount __length
)
3529 return (kIOReturnUnsupported
);
3532 IOReturn
IOMemoryDescriptor::handleFault(
3534 mach_vm_size_t sourceOffset
,
3535 mach_vm_size_t length
)
3537 if( kIOMemoryRedirected
& _flags
)
3540 IOLog("sleep mem redirect %p, %qx\n", this, sourceOffset
);
3544 } while( kIOMemoryRedirected
& _flags
);
3546 return (kIOReturnSuccess
);
3549 IOReturn
IOMemoryDescriptor::populateDevicePager(
3551 vm_map_t addressMap
,
3552 mach_vm_address_t address
,
3553 mach_vm_size_t sourceOffset
,
3554 mach_vm_size_t length
,
3555 IOOptionBits options
)
3557 IOReturn err
= kIOReturnSuccess
;
3558 memory_object_t pager
= (memory_object_t
) _pager
;
3559 mach_vm_size_t size
;
3560 mach_vm_size_t bytes
;
3561 mach_vm_size_t page
;
3562 mach_vm_size_t pageOffset
;
3563 mach_vm_size_t pagerOffset
;
3564 IOPhysicalLength segLen
;
3567 physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
);
3569 pageOffset
= physAddr
- trunc_page_64( physAddr
);
3570 pagerOffset
= sourceOffset
;
3572 size
= length
+ pageOffset
;
3573 physAddr
-= pageOffset
;
3575 segLen
+= pageOffset
;
3579 // in the middle of the loop only map whole pages
3580 if( segLen
>= bytes
) segLen
= bytes
;
3581 else if (segLen
!= trunc_page(segLen
)) err
= kIOReturnVMError
;
3582 if (physAddr
!= trunc_page_64(physAddr
)) err
= kIOReturnBadArgument
;
3584 if (kIOReturnSuccess
!= err
) break;
3586 if (reserved
&& reserved
->dp
.pagerContig
)
3588 IOPhysicalLength allLen
;
3591 allPhys
= getPhysicalSegment( 0, &allLen
, kIOMemoryMapperNone
);
3593 err
= device_pager_populate_object( pager
, 0, atop_64(allPhys
), round_page(allLen
) );
3598 (page
< segLen
) && (KERN_SUCCESS
== err
);
3601 err
= device_pager_populate_object(pager
, pagerOffset
,
3602 (ppnum_t
)(atop_64(physAddr
+ page
)), page_size
);
3603 pagerOffset
+= page_size
;
3606 assert (KERN_SUCCESS
== err
);
3609 // This call to vm_fault causes an early pmap level resolution
3610 // of the mappings created above for kernel mappings, since
3611 // faulting in later can't take place from interrupt level.
3612 if ((addressMap
== kernel_map
) && !(kIOMemoryRedirected
& _flags
))
3614 vm_fault(addressMap
,
3615 (vm_map_offset_t
)trunc_page_64(address
),
3616 VM_PROT_READ
|VM_PROT_WRITE
,
3617 FALSE
, THREAD_UNINT
, NULL
,
3618 (vm_map_offset_t
)0);
3621 sourceOffset
+= segLen
- pageOffset
;
3626 while (bytes
&& (physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
)));
3629 err
= kIOReturnBadArgument
;
3634 IOReturn
IOMemoryDescriptor::doUnmap(
3635 vm_map_t addressMap
,
3636 IOVirtualAddress __address
,
3637 IOByteCount __length
)
3640 mach_vm_address_t address
;
3641 mach_vm_size_t length
;
3645 address
= __address
;
3650 addressMap
= ((IOMemoryMap
*) __address
)->fAddressMap
;
3651 address
= ((IOMemoryMap
*) __address
)->fAddress
;
3652 length
= ((IOMemoryMap
*) __address
)->fLength
;
3655 if ((addressMap
== kernel_map
) && (kIOMemoryBufferPageable
& _flags
))
3656 addressMap
= IOPageableMapForAddress( address
);
3659 if( kIOLogMapping
& gIOKitDebug
)
3660 IOLog("IOMemoryDescriptor::doUnmap map %p, 0x%qx:0x%qx\n",
3661 addressMap
, address
, length
);
3664 err
= mach_vm_deallocate( addressMap
, address
, length
);
3669 IOReturn
IOMemoryDescriptor::redirect( task_t safeTask
, bool doRedirect
)
3671 IOReturn err
= kIOReturnSuccess
;
3672 IOMemoryMap
* mapping
= 0;
3678 _flags
|= kIOMemoryRedirected
;
3680 _flags
&= ~kIOMemoryRedirected
;
3683 if( (iter
= OSCollectionIterator::withCollection( _mappings
))) {
3685 memory_object_t pager
;
3688 pager
= (memory_object_t
) reserved
->dp
.devicePager
;
3690 pager
= MACH_PORT_NULL
;
3692 while( (mapping
= (IOMemoryMap
*) iter
->getNextObject()))
3694 mapping
->redirect( safeTask
, doRedirect
);
3695 if (!doRedirect
&& !safeTask
&& pager
&& (kernel_map
== mapping
->fAddressMap
))
3697 err
= populateDevicePager(pager
, mapping
->fAddressMap
, mapping
->fAddress
, mapping
->fOffset
, mapping
->fLength
, kIOMapDefaultCache
);
3713 // temporary binary compatibility
3714 IOSubMemoryDescriptor
* subMem
;
3715 if( (subMem
= OSDynamicCast( IOSubMemoryDescriptor
, this)))
3716 err
= subMem
->redirect( safeTask
, doRedirect
);
3718 err
= kIOReturnSuccess
;
3719 #endif /* !__LP64__ */
3724 IOReturn
IOMemoryMap::redirect( task_t safeTask
, bool doRedirect
)
3726 IOReturn err
= kIOReturnSuccess
;
3729 // err = ((IOMemoryMap *)superMap)->redirect( safeTask, doRedirect );
3741 if ((!safeTask
|| (get_task_map(safeTask
) != fAddressMap
))
3742 && (0 == (fOptions
& kIOMapStatic
)))
3744 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3745 err
= kIOReturnSuccess
;
3747 IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect
, this, fAddress
, fLength
, fAddressMap
);
3750 else if (kIOMapWriteCombineCache
== (fOptions
& kIOMapCacheMask
))
3752 IOOptionBits newMode
;
3753 newMode
= (fOptions
& ~kIOMapCacheMask
) | (doRedirect
? kIOMapInhibitCache
: kIOMapWriteCombineCache
);
3754 IOProtectCacheMode(fAddressMap
, fAddress
, fLength
, newMode
);
3761 if ((((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3762 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3764 && (doRedirect
!= (0 != (fMemory
->_flags
& kIOMemoryRedirected
))))
3765 fMemory
->redirect(safeTask
, doRedirect
);
3770 IOReturn
IOMemoryMap::unmap( void )
3776 if( fAddress
&& fAddressMap
&& (0 == fSuperMap
) && fMemory
3777 && (0 == (fOptions
& kIOMapStatic
))) {
3779 err
= fMemory
->doUnmap(fAddressMap
, (IOVirtualAddress
) this, 0);
3782 err
= kIOReturnSuccess
;
3786 vm_map_deallocate(fAddressMap
);
3797 void IOMemoryMap::taskDied( void )
3800 if (fUserClientUnmap
)
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
);
3962 if (kIODirectionOutIn
& options
)
3964 kr
= vm_map_wire(fAddressMap
, start
, end
, (kIODirectionOutIn
& options
), FALSE
);
3968 kr
= vm_map_unwire(fAddressMap
, start
, end
, FALSE
);
3977 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
, IOOptionBits _options
)
3978 #else /* !__LP64__ */
3979 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
)
3980 #endif /* !__LP64__ */
3982 IOPhysicalAddress address
;
3986 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
, _options
);
3987 #else /* !__LP64__ */
3988 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
);
3989 #endif /* !__LP64__ */
3995 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3998 #define super OSObject
4000 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4002 void IOMemoryDescriptor::initialize( void )
4004 if( 0 == gIOMemoryLock
)
4005 gIOMemoryLock
= IORecursiveLockAlloc();
4007 gIOLastPage
= IOGetLastPageNumber();
4010 void IOMemoryDescriptor::free( void )
4013 _mappings
->release();
4018 IOMemoryMap
* IOMemoryDescriptor::setMapping(
4020 IOVirtualAddress mapAddress
,
4021 IOOptionBits options
)
4023 return (createMappingInTask( intoTask
, mapAddress
,
4024 options
| kIOMapStatic
,
4028 IOMemoryMap
* IOMemoryDescriptor::map(
4029 IOOptionBits options
)
4031 return (createMappingInTask( kernel_task
, 0,
4032 options
| kIOMapAnywhere
,
4037 IOMemoryMap
* IOMemoryDescriptor::map(
4039 IOVirtualAddress atAddress
,
4040 IOOptionBits options
,
4042 IOByteCount length
)
4044 if ((!(kIOMapAnywhere
& options
)) && vm_map_is_64bit(get_task_map(intoTask
)))
4046 OSReportWithBacktrace("IOMemoryDescriptor::map() in 64b task, use ::createMappingInTask()");
4050 return (createMappingInTask(intoTask
, atAddress
,
4051 options
, offset
, length
));
4053 #endif /* !__LP64__ */
4055 IOMemoryMap
* IOMemoryDescriptor::createMappingInTask(
4057 mach_vm_address_t atAddress
,
4058 IOOptionBits options
,
4059 mach_vm_size_t offset
,
4060 mach_vm_size_t length
)
4062 IOMemoryMap
* result
;
4063 IOMemoryMap
* mapping
;
4066 length
= getLength();
4068 mapping
= new IOMemoryMap
;
4071 && !mapping
->init( intoTask
, atAddress
,
4072 options
, offset
, length
)) {
4078 result
= makeMapping(this, intoTask
, (IOVirtualAddress
) mapping
, options
| kIOMap64Bit
, 0, 0);
4084 IOLog("createMappingInTask failed desc %p, addr %qx, options %x, offset %qx, length %llx\n",
4085 this, atAddress
, (uint32_t) options
, offset
, length
);
4091 #ifndef __LP64__ // there is only a 64 bit version for LP64
4092 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
4093 IOOptionBits options
,
4096 return (redirect(newBackingMemory
, options
, (mach_vm_size_t
)offset
));
4100 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
4101 IOOptionBits options
,
4102 mach_vm_size_t offset
)
4104 IOReturn err
= kIOReturnSuccess
;
4105 IOMemoryDescriptor
* physMem
= 0;
4109 if (fAddress
&& fAddressMap
) do
4111 if (((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
4112 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
4118 if (!fRedirUPL
&& fMemory
->_memRef
&& (1 == fMemory
->_memRef
->count
))
4120 vm_size_t size
= round_page(fLength
);
4121 int flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
4122 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
4123 if (KERN_SUCCESS
!= memory_object_iopl_request(fMemory
->_memRef
->entries
[0].entry
, 0, &size
, &fRedirUPL
,
4130 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
4132 physMem
->redirect(0, true);
4136 if (newBackingMemory
)
4138 if (newBackingMemory
!= fMemory
)
4141 if (this != newBackingMemory
->makeMapping(newBackingMemory
, fAddressTask
, (IOVirtualAddress
) this,
4142 options
| kIOMapUnique
| kIOMapReference
| kIOMap64Bit
,
4144 err
= kIOReturnError
;
4148 upl_commit(fRedirUPL
, NULL
, 0);
4149 upl_deallocate(fRedirUPL
);
4152 if ((false) && physMem
)
4153 physMem
->redirect(0, false);
4166 IOMemoryMap
* IOMemoryDescriptor::makeMapping(
4167 IOMemoryDescriptor
* owner
,
4169 IOVirtualAddress __address
,
4170 IOOptionBits options
,
4171 IOByteCount __offset
,
4172 IOByteCount __length
)
4175 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::makeMapping !64bit");
4176 #endif /* !__LP64__ */
4178 IOMemoryDescriptor
* mapDesc
= 0;
4179 IOMemoryMap
* result
= 0;
4182 IOMemoryMap
* mapping
= (IOMemoryMap
*) __address
;
4183 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
4184 mach_vm_size_t length
= mapping
->fLength
;
4186 mapping
->fOffset
= offset
;
4192 if (kIOMapStatic
& options
)
4195 addMapping(mapping
);
4196 mapping
->setMemoryDescriptor(this, 0);
4200 if (kIOMapUnique
& options
)
4203 IOByteCount physLen
;
4205 // if (owner != this) continue;
4207 if (((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
4208 || ((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
4210 phys
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
4211 if (!phys
|| (physLen
< length
))
4214 mapDesc
= IOMemoryDescriptor::withAddressRange(
4215 phys
, length
, getDirection() | kIOMemoryMapperNone
, NULL
);
4219 mapping
->fOffset
= offset
;
4224 // look for a compatible existing mapping
4225 if( (iter
= OSCollectionIterator::withCollection(_mappings
)))
4227 IOMemoryMap
* lookMapping
;
4228 while ((lookMapping
= (IOMemoryMap
*) iter
->getNextObject()))
4230 if ((result
= lookMapping
->copyCompatible(mapping
)))
4233 result
->setMemoryDescriptor(this, offset
);
4239 if (result
|| (options
& kIOMapReference
))
4241 if (result
!= mapping
)
4256 kr
= mapDesc
->doMap( 0, (IOVirtualAddress
*) &mapping
, options
, 0, 0 );
4257 if (kIOReturnSuccess
== kr
)
4260 mapDesc
->addMapping(result
);
4261 result
->setMemoryDescriptor(mapDesc
, offset
);
4279 void IOMemoryDescriptor::addMapping(
4280 IOMemoryMap
* mapping
)
4285 _mappings
= OSSet::withCapacity(1);
4287 _mappings
->setObject( mapping
);
4291 void IOMemoryDescriptor::removeMapping(
4292 IOMemoryMap
* mapping
)
4295 _mappings
->removeObject( mapping
);
4299 // obsolete initializers
4300 // - initWithOptions is the designated initializer
4302 IOMemoryDescriptor::initWithAddress(void * address
,
4304 IODirection direction
)
4310 IOMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
4312 IODirection direction
,
4319 IOMemoryDescriptor::initWithPhysicalAddress(
4320 IOPhysicalAddress address
,
4322 IODirection direction
)
4328 IOMemoryDescriptor::initWithRanges(
4329 IOVirtualRange
* ranges
,
4331 IODirection direction
,
4339 IOMemoryDescriptor::initWithPhysicalRanges( IOPhysicalRange
* ranges
,
4341 IODirection direction
,
4347 void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
4348 IOByteCount
* lengthOfSegment
)
4352 #endif /* !__LP64__ */
4354 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4356 bool IOGeneralMemoryDescriptor::serialize(OSSerialize
* s
) const
4358 OSSymbol
const *keys
[2];
4359 OSObject
*values
[2];
4363 user_addr_t address
;
4366 unsigned int index
, nRanges
;
4369 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
4371 if (s
== NULL
) return false;
4373 array
= OSArray::withCapacity(4);
4374 if (!array
) return (false);
4376 nRanges
= _rangesCount
;
4377 vcopy
= (SerData
*) IOMalloc(sizeof(SerData
) * nRanges
);
4378 if (vcopy
== 0) return false;
4380 keys
[0] = OSSymbol::withCString("address");
4381 keys
[1] = OSSymbol::withCString("length");
4384 values
[0] = values
[1] = 0;
4386 // From this point on we can go to bail.
4388 // Copy the volatile data so we don't have to allocate memory
4389 // while the lock is held.
4391 if (nRanges
== _rangesCount
) {
4392 Ranges vec
= _ranges
;
4393 for (index
= 0; index
< nRanges
; index
++) {
4394 mach_vm_address_t addr
; mach_vm_size_t len
;
4395 getAddrLenForInd(addr
, len
, type
, vec
, index
);
4396 vcopy
[index
].address
= addr
;
4397 vcopy
[index
].length
= len
;
4400 // The descriptor changed out from under us. Give up.
4407 for (index
= 0; index
< nRanges
; index
++)
4409 user_addr_t addr
= vcopy
[index
].address
;
4410 IOByteCount len
= (IOByteCount
) vcopy
[index
].length
;
4411 values
[0] = OSNumber::withNumber(addr
, sizeof(addr
) * 8);
4412 if (values
[0] == 0) {
4416 values
[1] = OSNumber::withNumber(len
, sizeof(len
) * 8);
4417 if (values
[1] == 0) {
4421 OSDictionary
*dict
= OSDictionary::withObjects((const OSObject
**)values
, (const OSSymbol
**)keys
, 2);
4426 array
->setObject(dict
);
4428 values
[0]->release();
4429 values
[1]->release();
4430 values
[0] = values
[1] = 0;
4433 result
= array
->serialize(s
);
4439 values
[0]->release();
4441 values
[1]->release();
4447 IOFree(vcopy
, sizeof(SerData
) * nRanges
);
4452 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4454 #if DEVELOPMENT || DEBUG
4456 extern "C" void IOMemoryDescriptorTest(int x
)
4458 IOGeneralMemoryDescriptor
* md
;
4460 vm_offset_t data
[2];
4461 vm_size_t bsize
= 16*1024*1024;
4463 vm_size_t srcsize
, srcoffset
, mapoffset
, size
;
4467 kr
= vm_allocate(kernel_map
, &data
[0], bsize
, VM_FLAGS_ANYWHERE
);
4468 vm_inherit(kernel_map
, data
[0] + 1*4096, 4096, VM_INHERIT_NONE
);
4469 vm_inherit(kernel_map
, data
[0] + 16*4096, 4096, VM_INHERIT_NONE
);
4471 kprintf("data 0x%lx, 0x%lx\n", (long)data
[0], (long)data
[1]);
4473 uint32_t idx
, offidx
;
4474 for (idx
= 0; idx
< (bsize
/ sizeof(uint32_t)); idx
++)
4476 ((uint32_t*)data
[0])[idx
] = idx
;
4479 for (srcoffset
= 0; srcoffset
< bsize
; srcoffset
= ((srcoffset
<< 1) + 0x40c))
4481 for (srcsize
= 4; srcsize
< (bsize
- srcoffset
- 1); srcsize
= ((srcsize
<< 1) + 0x3fc))
4483 IOAddressRange ranges
[3];
4484 uint32_t rangeCount
= 1;
4486 bzero(&ranges
[0], sizeof(ranges
));
4487 ranges
[0].address
= data
[0] + srcoffset
;
4488 ranges
[0].length
= srcsize
;
4490 if (srcsize
> 5*page_size
)
4492 ranges
[0].length
= 7634;
4493 ranges
[1].length
= 9870;
4494 ranges
[2].length
= srcsize
- ranges
[0].length
- ranges
[1].length
;
4495 ranges
[1].address
= ranges
[0].address
+ ranges
[0].length
;
4496 ranges
[2].address
= ranges
[1].address
+ ranges
[1].length
;
4499 else if ((srcsize
> 2*page_size
) && !(page_mask
& srcoffset
))
4501 ranges
[0].length
= 4096;
4502 ranges
[1].length
= 4096;
4503 ranges
[2].length
= srcsize
- ranges
[0].length
- ranges
[1].length
;
4504 ranges
[0].address
= data
[0] + srcoffset
+ 4096;
4505 ranges
[1].address
= data
[0] + srcoffset
;
4506 ranges
[2].address
= ranges
[0].address
+ ranges
[0].length
;
4510 md
= OSDynamicCast(IOGeneralMemoryDescriptor
,
4511 IOMemoryDescriptor::withAddressRanges(&ranges
[0], rangeCount
, kIODirectionInOut
, kernel_task
));
4514 kprintf("IOMemoryReferenceCreate [0x%lx @ 0x%lx]\n[0x%llx, 0x%llx],\n[0x%llx, 0x%llx],\n[0x%llx, 0x%llx]\n",
4515 (long) srcsize
, (long) srcoffset
,
4516 (long long) ranges
[0].address
- data
[0], (long long) ranges
[0].length
,
4517 (long long) ranges
[1].address
- data
[0], (long long) ranges
[1].length
,
4518 (long long) ranges
[2].address
- data
[0], (long long) ranges
[2].length
);
4520 if (kIOReturnSuccess
== kr
)
4522 for (mapoffset
= 0; mapoffset
< srcsize
; mapoffset
= ((mapoffset
<< 1) + 0xf00))
4524 for (size
= 4; size
< (srcsize
- mapoffset
- 1); size
= ((size
<< 1) + 0x20))
4527 mach_vm_address_t addr
= 0;
4530 kprintf("<mapRef [0x%lx @ 0x%lx]\n", (long) size
, (long) mapoffset
);
4532 map
= md
->createMappingInTask(kernel_task
, 0, kIOMapAnywhere
, mapoffset
, size
);
4533 if (map
) addr
= map
->getAddress();
4534 else kr
= kIOReturnError
;
4536 kprintf(">mapRef 0x%x %llx\n", kr
, addr
);
4538 if (kIOReturnSuccess
!= kr
) break;
4540 if (kIOReturnSuccess
!= kr
)
4542 kprintf("prepare() fail 0x%x\n", kr
);
4545 for (idx
= 0; idx
< size
; idx
+= sizeof(uint32_t))
4547 offidx
= (idx
+ mapoffset
+ srcoffset
);
4548 if ((srcsize
<= 5*page_size
) && (srcsize
> 2*page_size
) && !(page_mask
& srcoffset
))
4550 if (offidx
< 8192) offidx
^= 0x1000;
4552 offidx
/= sizeof(uint32_t);
4554 if (offidx
!= ((uint32_t*)addr
)[idx
/sizeof(uint32_t)])
4556 kprintf("vm mismatch @ 0x%x, 0x%lx, 0x%lx, \n", idx
, (long) srcoffset
, (long) mapoffset
);
4557 kr
= kIOReturnBadMedia
;
4561 if (sizeof(data
) != md
->readBytes(mapoffset
+ idx
, &data
, sizeof(data
))) data
= 0;
4564 kprintf("phys mismatch @ 0x%x, 0x%lx, 0x%lx, \n", idx
, (long) srcoffset
, (long) mapoffset
);
4565 kr
= kIOReturnBadMedia
;
4571 kprintf("unmapRef %llx\n", addr
);
4573 if (kIOReturnSuccess
!= kr
) break;
4576 if (kIOReturnSuccess
!= kr
) break;
4578 if (kIOReturnSuccess
!= kr
) break;
4581 if (kIOReturnSuccess
!= kr
) kprintf("FAIL: src 0x%lx @ 0x%lx, map 0x%lx @ 0x%lx\n",
4582 (long) srcsize
, (long) srcoffset
, (long) size
, (long) mapoffset
);
4584 vm_deallocate(kernel_map
, data
[0], bsize
);
4585 // vm_deallocate(kernel_map, data[1], size);
4588 #endif /* DEVELOPMENT || DEBUG */
4590 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4592 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 0);
4594 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 1);
4595 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 2);
4596 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 3);
4597 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 4);
4598 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 5);
4599 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 6);
4600 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 7);
4601 #else /* !__LP64__ */
4602 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 1);
4603 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 2);
4604 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 3);
4605 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 4);
4606 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 5);
4607 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 6);
4608 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 7);
4609 #endif /* !__LP64__ */
4610 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 8);
4611 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 9);
4612 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 10);
4613 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 11);
4614 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 12);
4615 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 13);
4616 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 14);
4617 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 15);
4619 /* ex-inline function implementation */
4621 IOMemoryDescriptor::getPhysicalAddress()
4622 { return( getPhysicalSegment( 0, 0 )); }