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/IOKitKeysPrivate.h>
46 #include <IOKit/IOSubMemoryDescriptor.h>
47 #endif /* !__LP64__ */
49 #include <IOKit/IOKitDebug.h>
50 #include <libkern/OSDebug.h>
52 #include "IOKitKernelInternal.h"
54 #include <libkern/c++/OSContainers.h>
55 #include <libkern/c++/OSDictionary.h>
56 #include <libkern/c++/OSArray.h>
57 #include <libkern/c++/OSSymbol.h>
58 #include <libkern/c++/OSNumber.h>
64 #include <vm/vm_pageout.h>
65 #include <mach/memory_object_types.h>
66 #include <device/device_port.h>
68 #include <mach/vm_prot.h>
69 #include <mach/mach_vm.h>
70 #include <vm/vm_fault.h>
71 #include <vm/vm_protos.h>
73 extern ppnum_t
pmap_find_phys(pmap_t pmap
, addr64_t va
);
74 extern void ipc_port_release_send(ipc_port_t port
);
77 memory_object_iopl_request(
79 memory_object_offset_t offset
,
82 upl_page_info_array_t user_page_list
,
83 unsigned int *page_list_count
,
86 unsigned int IOTranslateCacheBits(struct phys_entry
*pp
);
90 #define kIOMaximumMappedIOByteCount (512*1024*1024)
92 static IOMapper
* gIOSystemMapper
= NULL
;
94 static ppnum_t gIOMaximumMappedIOPageCount
= atop_32(kIOMaximumMappedIOByteCount
);
98 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
100 OSDefineMetaClassAndAbstractStructors( IOMemoryDescriptor
, OSObject
)
102 #define super IOMemoryDescriptor
104 OSDefineMetaClassAndStructors(IOGeneralMemoryDescriptor
, IOMemoryDescriptor
)
106 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
108 static IORecursiveLock
* gIOMemoryLock
;
110 #define LOCK IORecursiveLockLock( gIOMemoryLock)
111 #define UNLOCK IORecursiveLockUnlock( gIOMemoryLock)
112 #define SLEEP IORecursiveLockSleep( gIOMemoryLock, (void *)this, THREAD_UNINT)
114 IORecursiveLockWakeup( gIOMemoryLock, (void *)this, /* one-thread */ false)
117 #define DEBG(fmt, args...) { kprintf(fmt, ## args); }
119 #define DEBG(fmt, args...) {}
122 #define IOMD_DEBUG_DMAACTIVE 1
124 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
126 // Some data structures and accessor macros used by the initWithOptions
129 enum ioPLBlockFlags
{
130 kIOPLOnDevice
= 0x00000001,
131 kIOPLExternUPL
= 0x00000002,
134 struct typePersMDData
136 const IOGeneralMemoryDescriptor
*fMD
;
137 ipc_port_t fMemEntry
;
142 vm_address_t fPageInfo
; // Pointer to page list or index into it
143 uint32_t fIOMDOffset
; // The offset of this iopl in descriptor
144 ppnum_t fMappedBase
; // Page number of first page in this iopl
145 unsigned int fPageOffset
; // Offset within first page of iopl
146 unsigned int fFlags
; // Flags
151 uint64_t fPreparationID
;
152 unsigned int fPageCnt
;
154 // align arrays to 8 bytes so following macros work
157 upl_page_info_t fPageList
[1]; /* variable length */
158 ioPLBlock fBlocks
[1]; /* variable length */
161 #define getDataP(osd) ((ioGMDData *) (osd)->getBytesNoCopy())
162 #define getIOPLList(d) ((ioPLBlock *) &(d->fPageList[d->fPageCnt]))
163 #define getNumIOPL(osd, d) \
164 (((osd)->getLength() - ((char *) getIOPLList(d) - (char *) d)) / sizeof(ioPLBlock))
165 #define getPageList(d) (&(d->fPageList[0]))
166 #define computeDataSize(p, u) \
167 (offsetof(ioGMDData, fPageList) + p * sizeof(upl_page_info_t) + u * sizeof(ioPLBlock))
170 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
172 #define next_page(a) ( trunc_page(a) + PAGE_SIZE )
177 kern_return_t
device_data_action(
178 uintptr_t device_handle
,
179 ipc_port_t device_pager
,
180 vm_prot_t protection
,
181 vm_object_offset_t offset
,
185 IOMemoryDescriptorReserved
* ref
= (IOMemoryDescriptorReserved
*) device_handle
;
186 IOMemoryDescriptor
* memDesc
;
189 memDesc
= ref
->dp
.memory
;
193 kr
= memDesc
->handleFault( device_pager
, 0, 0,
194 offset
, size
, kIOMapDefaultCache
/*?*/);
204 kern_return_t
device_close(
205 uintptr_t device_handle
)
207 IOMemoryDescriptorReserved
* ref
= (IOMemoryDescriptorReserved
*) device_handle
;
209 IODelete( ref
, IOMemoryDescriptorReserved
, 1 );
211 return( kIOReturnSuccess
);
215 // Note this inline function uses C++ reference arguments to return values
216 // This means that pointers are not passed and NULLs don't have to be
217 // checked for as a NULL reference is illegal.
219 getAddrLenForInd(user_addr_t
&addr
, IOPhysicalLength
&len
, // Output variables
220 UInt32 type
, IOGeneralMemoryDescriptor::Ranges r
, UInt32 ind
)
222 assert(kIOMemoryTypeUIO
== type
223 || kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
224 || kIOMemoryTypePhysical
== type
|| kIOMemoryTypePhysical64
== type
);
225 if (kIOMemoryTypeUIO
== type
) {
227 uio_getiov((uio_t
) r
.uio
, ind
, &addr
, &us
); len
= us
;
230 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
)) {
231 IOAddressRange cur
= r
.v64
[ind
];
235 #endif /* !__LP64__ */
237 IOVirtualRange cur
= r
.v
[ind
];
243 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
246 IOMemoryDescriptor::withAddress(void * address
,
248 IODirection direction
)
250 return IOMemoryDescriptor::
251 withAddressRange((IOVirtualAddress
) address
, length
, direction
| kIOMemoryAutoPrepare
, kernel_task
);
256 IOMemoryDescriptor::withAddress(IOVirtualAddress address
,
258 IODirection direction
,
261 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
264 if (that
->initWithAddress(address
, length
, direction
, task
))
271 #endif /* !__LP64__ */
274 IOMemoryDescriptor::withPhysicalAddress(
275 IOPhysicalAddress address
,
277 IODirection direction
)
279 return (IOMemoryDescriptor::withAddressRange(address
, length
, direction
, TASK_NULL
));
284 IOMemoryDescriptor::withRanges( IOVirtualRange
* ranges
,
286 IODirection direction
,
290 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
293 if (that
->initWithRanges(ranges
, withCount
, direction
, task
, asReference
))
300 #endif /* !__LP64__ */
303 IOMemoryDescriptor::withAddressRange(mach_vm_address_t address
,
304 mach_vm_size_t length
,
305 IOOptionBits options
,
308 IOAddressRange range
= { address
, length
};
309 return (IOMemoryDescriptor::withAddressRanges(&range
, 1, options
, task
));
313 IOMemoryDescriptor::withAddressRanges(IOAddressRange
* ranges
,
315 IOOptionBits options
,
318 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
322 options
|= kIOMemoryTypeVirtual64
;
324 options
|= kIOMemoryTypePhysical64
;
326 if (that
->initWithOptions(ranges
, rangeCount
, 0, task
, options
, /* mapper */ 0))
339 * Create a new IOMemoryDescriptor. The buffer is made up of several
340 * virtual address ranges, from a given task.
342 * Passing the ranges as a reference will avoid an extra allocation.
345 IOMemoryDescriptor::withOptions(void * buffers
,
352 IOGeneralMemoryDescriptor
*self
= new IOGeneralMemoryDescriptor
;
355 && !self
->initWithOptions(buffers
, count
, offset
, task
, opts
, mapper
))
364 bool IOMemoryDescriptor::initWithOptions(void * buffers
,
368 IOOptionBits options
,
376 IOMemoryDescriptor::withPhysicalRanges( IOPhysicalRange
* ranges
,
378 IODirection direction
,
381 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
384 if (that
->initWithPhysicalRanges(ranges
, withCount
, direction
, asReference
))
393 IOMemoryDescriptor::withSubRange(IOMemoryDescriptor
* of
,
396 IODirection direction
)
398 return (IOSubMemoryDescriptor::withSubRange(of
, offset
, length
, direction
| kIOMemoryThreadSafe
));
400 #endif /* !__LP64__ */
403 IOMemoryDescriptor::withPersistentMemoryDescriptor(IOMemoryDescriptor
*originalMD
)
405 IOGeneralMemoryDescriptor
*origGenMD
=
406 OSDynamicCast(IOGeneralMemoryDescriptor
, originalMD
);
409 return IOGeneralMemoryDescriptor::
410 withPersistentMemoryDescriptor(origGenMD
);
416 IOGeneralMemoryDescriptor::withPersistentMemoryDescriptor(IOGeneralMemoryDescriptor
*originalMD
)
418 ipc_port_t sharedMem
= (ipc_port_t
) originalMD
->createNamedEntry();
423 if (sharedMem
== originalMD
->_memEntry
) {
424 originalMD
->retain(); // Add a new reference to ourselves
425 ipc_port_release_send(sharedMem
); // Remove extra send right
429 IOGeneralMemoryDescriptor
* self
= new IOGeneralMemoryDescriptor
;
430 typePersMDData initData
= { originalMD
, sharedMem
};
433 && !self
->initWithOptions(&initData
, 1, 0, 0, kIOMemoryTypePersistentMD
, 0)) {
440 void *IOGeneralMemoryDescriptor::createNamedEntry()
443 ipc_port_t sharedMem
;
445 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
447 user_addr_t range0Addr
;
448 IOByteCount range0Len
;
449 getAddrLenForInd(range0Addr
, range0Len
, type
, _ranges
, 0);
450 range0Addr
= trunc_page_64(range0Addr
);
452 vm_size_t size
= ptoa_32(_pages
);
453 vm_address_t kernelPage
= (vm_address_t
) range0Addr
;
455 vm_map_t theMap
= ((_task
== kernel_task
)
456 && (kIOMemoryBufferPageable
& _flags
))
457 ? IOPageableMapForAddress(kernelPage
)
458 : get_task_map(_task
);
460 memory_object_size_t actualSize
= size
;
461 vm_prot_t prot
= VM_PROT_READ
;
462 if (kIODirectionOut
!= (kIODirectionOutIn
& _flags
))
463 prot
|= VM_PROT_WRITE
;
466 prot
|= MAP_MEM_NAMED_REUSE
;
468 error
= mach_make_memory_entry_64(theMap
,
469 &actualSize
, range0Addr
, prot
, &sharedMem
, (ipc_port_t
) _memEntry
);
471 if (KERN_SUCCESS
== error
) {
472 if (actualSize
== size
) {
476 IOLog("IOGMD::mach_make_memory_entry_64 (%08llx) size (%08llx:%08llx)\n",
477 (UInt64
)range0Addr
, (UInt64
)actualSize
, (UInt64
)size
);
479 ipc_port_release_send( sharedMem
);
483 return MACH_PORT_NULL
;
488 IOGeneralMemoryDescriptor::initWithAddress(void * address
,
489 IOByteCount withLength
,
490 IODirection withDirection
)
492 _singleRange
.v
.address
= (vm_offset_t
) address
;
493 _singleRange
.v
.length
= withLength
;
495 return initWithRanges(&_singleRange
.v
, 1, withDirection
, kernel_task
, true);
499 IOGeneralMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
500 IOByteCount withLength
,
501 IODirection withDirection
,
504 _singleRange
.v
.address
= address
;
505 _singleRange
.v
.length
= withLength
;
507 return initWithRanges(&_singleRange
.v
, 1, withDirection
, withTask
, true);
511 IOGeneralMemoryDescriptor::initWithPhysicalAddress(
512 IOPhysicalAddress address
,
513 IOByteCount withLength
,
514 IODirection withDirection
)
516 _singleRange
.p
.address
= address
;
517 _singleRange
.p
.length
= withLength
;
519 return initWithPhysicalRanges( &_singleRange
.p
, 1, withDirection
, true);
523 IOGeneralMemoryDescriptor::initWithPhysicalRanges(
524 IOPhysicalRange
* ranges
,
526 IODirection direction
,
529 IOOptionBits mdOpts
= direction
| kIOMemoryTypePhysical
;
532 mdOpts
|= kIOMemoryAsReference
;
534 return initWithOptions(ranges
, count
, 0, 0, mdOpts
, /* mapper */ 0);
538 IOGeneralMemoryDescriptor::initWithRanges(
539 IOVirtualRange
* ranges
,
541 IODirection direction
,
545 IOOptionBits mdOpts
= direction
;
548 mdOpts
|= kIOMemoryAsReference
;
551 mdOpts
|= kIOMemoryTypeVirtual
;
553 // Auto-prepare if this is a kernel memory descriptor as very few
554 // clients bother to prepare() kernel memory.
555 // But it was not enforced so what are you going to do?
556 if (task
== kernel_task
)
557 mdOpts
|= kIOMemoryAutoPrepare
;
560 mdOpts
|= kIOMemoryTypePhysical
;
562 return initWithOptions(ranges
, count
, 0, task
, mdOpts
, /* mapper */ 0);
564 #endif /* !__LP64__ */
569 * IOMemoryDescriptor. The buffer is made up of several virtual address ranges,
570 * from a given task, several physical ranges, an UPL from the ubc
571 * system or a uio (may be 64bit) from the BSD subsystem.
573 * Passing the ranges as a reference will avoid an extra allocation.
575 * An IOMemoryDescriptor can be re-used by calling initWithOptions again on an
576 * existing instance -- note this behavior is not commonly supported in other
577 * I/O Kit classes, although it is supported here.
581 IOGeneralMemoryDescriptor::initWithOptions(void * buffers
,
585 IOOptionBits options
,
588 IOOptionBits type
= options
& kIOMemoryTypeMask
;
592 && (kIOMemoryTypeVirtual
== type
)
593 && vm_map_is_64bit(get_task_map(task
))
594 && ((IOVirtualRange
*) buffers
)->address
)
596 OSReportWithBacktrace("IOMemoryDescriptor: attempt to create 32b virtual in 64b task, use ::withAddressRange()");
599 #endif /* !__LP64__ */
601 // Grab the original MD's configuation data to initialse the
602 // arguments to this function.
603 if (kIOMemoryTypePersistentMD
== type
) {
605 typePersMDData
*initData
= (typePersMDData
*) buffers
;
606 const IOGeneralMemoryDescriptor
*orig
= initData
->fMD
;
607 ioGMDData
*dataP
= getDataP(orig
->_memoryEntries
);
609 // Only accept persistent memory descriptors with valid dataP data.
610 assert(orig
->_rangesCount
== 1);
611 if ( !(orig
->_flags
& kIOMemoryPersistent
) || !dataP
)
614 _memEntry
= initData
->fMemEntry
; // Grab the new named entry
615 options
= orig
->_flags
& ~kIOMemoryAsReference
;
616 type
= options
& kIOMemoryTypeMask
;
617 buffers
= orig
->_ranges
.v
;
618 count
= orig
->_rangesCount
;
620 // Now grab the original task and whatever mapper was previously used
622 mapper
= dataP
->fMapper
;
624 // We are ready to go through the original initialisation now
628 case kIOMemoryTypeUIO
:
629 case kIOMemoryTypeVirtual
:
631 case kIOMemoryTypeVirtual64
:
632 #endif /* !__LP64__ */
638 case kIOMemoryTypePhysical
: // Neither Physical nor UPL should have a task
640 case kIOMemoryTypePhysical64
:
641 #endif /* !__LP64__ */
642 case kIOMemoryTypeUPL
:
646 return false; /* bad argument */
653 * We can check the _initialized instance variable before having ever set
654 * it to an initial value because I/O Kit guarantees that all our instance
655 * variables are zeroed on an object's allocation.
660 * An existing memory descriptor is being retargeted to point to
661 * somewhere else. Clean up our present state.
663 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
664 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
669 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
671 if (kIOMemoryTypeUIO
== type
)
672 uio_free((uio_t
) _ranges
.v
);
674 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
675 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
676 #endif /* !__LP64__ */
678 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
683 ipc_port_release_send((ipc_port_t
) _memEntry
);
687 _mappings
->flushCollection();
695 // Grab the appropriate mapper
696 if (kIOMemoryMapperNone
& options
)
697 mapper
= 0; // No Mapper
698 else if (mapper
== kIOMapperSystem
) {
699 IOMapper::checkForSystemMapper();
700 gIOSystemMapper
= mapper
= IOMapper::gSystem
;
703 // Temp binary compatibility for kIOMemoryThreadSafe
704 if (kIOMemoryReserved6156215
& options
)
706 options
&= ~kIOMemoryReserved6156215
;
707 options
|= kIOMemoryThreadSafe
;
709 // Remove the dynamic internal use flags from the initial setting
710 options
&= ~(kIOMemoryPreparedReadOnly
);
715 _direction
= (IODirection
) (_flags
& kIOMemoryDirectionMask
);
716 #endif /* !__LP64__ */
718 __iomd_reservedA
= 0;
719 __iomd_reservedB
= 0;
722 if (kIOMemoryThreadSafe
& options
)
725 _prepareLock
= IOLockAlloc();
727 else if (_prepareLock
)
729 IOLockFree(_prepareLock
);
733 if (kIOMemoryTypeUPL
== type
) {
736 unsigned int dataSize
= computeDataSize(/* pages */ 0, /* upls */ 1);
738 if (!_memoryEntries
) {
739 _memoryEntries
= OSData::withCapacity(dataSize
);
743 else if (!_memoryEntries
->initWithCapacity(dataSize
))
746 _memoryEntries
->appendBytes(0, computeDataSize(0, 0));
747 dataP
= getDataP(_memoryEntries
);
748 dataP
->fMapper
= mapper
;
751 // _wireCount++; // UPLs start out life wired
754 _pages
+= atop_32(offset
+ count
+ PAGE_MASK
) - atop_32(offset
);
757 iopl
.fIOPL
= (upl_t
) buffers
;
758 upl_set_referenced(iopl
.fIOPL
, true);
759 upl_page_info_t
*pageList
= UPL_GET_INTERNAL_PAGE_LIST(iopl
.fIOPL
);
761 if (upl_get_size(iopl
.fIOPL
) < (count
+ offset
))
762 panic("short external upl");
764 // Set the flag kIOPLOnDevice convieniently equal to 1
765 iopl
.fFlags
= pageList
->device
| kIOPLExternUPL
;
766 iopl
.fIOMDOffset
= 0;
768 _highestPage
= upl_get_highest_page(iopl
.fIOPL
);
770 if (!pageList
->device
) {
771 // Pre-compute the offset into the UPL's page list
772 pageList
= &pageList
[atop_32(offset
)];
775 iopl
.fMappedBase
= mapper
->iovmAlloc(_pages
);
776 mapper
->iovmInsert(iopl
.fMappedBase
, 0, pageList
, _pages
);
779 iopl
.fMappedBase
= 0;
782 iopl
.fMappedBase
= 0;
783 iopl
.fPageInfo
= (vm_address_t
) pageList
;
784 iopl
.fPageOffset
= offset
;
786 _memoryEntries
->appendBytes(&iopl
, sizeof(iopl
));
789 // kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO
790 // kIOMemoryTypePhysical | kIOMemoryTypePhysical64
792 // Initialize the memory descriptor
793 if (options
& kIOMemoryAsReference
) {
795 _rangesIsAllocated
= false;
796 #endif /* !__LP64__ */
798 // Hack assignment to get the buffer arg into _ranges.
799 // I'd prefer to do _ranges = (Ranges) buffers, but that doesn't
801 // This also initialises the uio & physical ranges.
802 _ranges
.v
= (IOVirtualRange
*) buffers
;
806 _rangesIsAllocated
= true;
807 #endif /* !__LP64__ */
810 case kIOMemoryTypeUIO
:
811 _ranges
.v
= (IOVirtualRange
*) uio_duplicate((uio_t
) buffers
);
815 case kIOMemoryTypeVirtual64
:
816 case kIOMemoryTypePhysical64
:
818 && (((IOAddressRange
*) buffers
)->address
+ ((IOAddressRange
*) buffers
)->length
) <= 0x100000000ULL
820 if (kIOMemoryTypeVirtual64
== type
)
821 type
= kIOMemoryTypeVirtual
;
823 type
= kIOMemoryTypePhysical
;
824 _flags
= (_flags
& ~kIOMemoryTypeMask
) | type
| kIOMemoryAsReference
;
825 _rangesIsAllocated
= false;
826 _ranges
.v
= &_singleRange
.v
;
827 _singleRange
.v
.address
= ((IOAddressRange
*) buffers
)->address
;
828 _singleRange
.v
.length
= ((IOAddressRange
*) buffers
)->length
;
831 _ranges
.v64
= IONew(IOAddressRange
, count
);
834 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOAddressRange
));
836 #endif /* !__LP64__ */
837 case kIOMemoryTypeVirtual
:
838 case kIOMemoryTypePhysical
:
840 _flags
|= kIOMemoryAsReference
;
842 _rangesIsAllocated
= false;
843 #endif /* !__LP64__ */
844 _ranges
.v
= &_singleRange
.v
;
846 _ranges
.v
= IONew(IOVirtualRange
, count
);
850 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOVirtualRange
));
855 // Find starting address within the vector of ranges
856 Ranges vec
= _ranges
;
859 for (unsigned ind
= 0; ind
< count
; ind
++) {
861 IOPhysicalLength len
;
863 // addr & len are returned by this function
864 getAddrLenForInd(addr
, len
, type
, vec
, ind
);
865 pages
+= (atop_64(addr
+ len
+ PAGE_MASK
) - atop_64(addr
));
867 assert(len
>= length
); // Check for 32 bit wrap around
870 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
872 ppnum_t highPage
= atop_64(addr
+ len
- 1);
873 if (highPage
> _highestPage
)
874 _highestPage
= highPage
;
879 _rangesCount
= count
;
881 // Auto-prepare memory at creation time.
882 // Implied completion when descriptor is free-ed
883 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
884 _wireCount
++; // Physical MDs are, by definition, wired
885 else { /* kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO */
887 unsigned dataSize
= computeDataSize(_pages
, /* upls */ count
* 2);
889 if (!_memoryEntries
) {
890 _memoryEntries
= OSData::withCapacity(dataSize
);
894 else if (!_memoryEntries
->initWithCapacity(dataSize
))
897 _memoryEntries
->appendBytes(0, computeDataSize(0, 0));
898 dataP
= getDataP(_memoryEntries
);
899 dataP
->fMapper
= mapper
;
900 dataP
->fPageCnt
= _pages
;
902 if ( (kIOMemoryPersistent
& _flags
) && !_memEntry
)
903 _memEntry
= createNamedEntry();
905 if ((_flags
& kIOMemoryAutoPrepare
)
906 && prepare() != kIOReturnSuccess
)
919 void IOGeneralMemoryDescriptor::free()
921 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
926 reserved
->dp
.memory
= 0;
930 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
936 _memoryEntries
->release();
938 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
940 if (kIOMemoryTypeUIO
== type
)
941 uio_free((uio_t
) _ranges
.v
);
943 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
944 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
945 #endif /* !__LP64__ */
947 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
954 if (reserved
->dp
.devicePager
)
956 // memEntry holds a ref on the device pager which owns reserved
957 // (IOMemoryDescriptorReserved) so no reserved access after this point
958 device_pager_deallocate( (memory_object_t
) reserved
->dp
.devicePager
);
961 IODelete(reserved
, IOMemoryDescriptorReserved
, 1);
966 ipc_port_release_send( (ipc_port_t
) _memEntry
);
969 IOLockFree(_prepareLock
);
975 void IOGeneralMemoryDescriptor::unmapFromKernel()
977 panic("IOGMD::unmapFromKernel deprecated");
980 void IOGeneralMemoryDescriptor::mapIntoKernel(unsigned rangeIndex
)
982 panic("IOGMD::mapIntoKernel deprecated");
984 #endif /* !__LP64__ */
989 * Get the direction of the transfer.
991 IODirection
IOMemoryDescriptor::getDirection() const
996 #endif /* !__LP64__ */
997 return (IODirection
) (_flags
& kIOMemoryDirectionMask
);
1003 * Get the length of the transfer (over all ranges).
1005 IOByteCount
IOMemoryDescriptor::getLength() const
1010 void IOMemoryDescriptor::setTag( IOOptionBits tag
)
1015 IOOptionBits
IOMemoryDescriptor::getTag( void )
1021 // @@@ gvdl: who is using this API? Seems like a wierd thing to implement.
1023 IOMemoryDescriptor::getSourceSegment( IOByteCount offset
, IOByteCount
* length
)
1025 addr64_t physAddr
= 0;
1027 if( prepare() == kIOReturnSuccess
) {
1028 physAddr
= getPhysicalSegment64( offset
, length
);
1032 return( (IOPhysicalAddress
) physAddr
); // truncated but only page offset is used
1034 #endif /* !__LP64__ */
1036 IOByteCount
IOMemoryDescriptor::readBytes
1037 (IOByteCount offset
, void *bytes
, IOByteCount length
)
1039 addr64_t dstAddr
= CAST_DOWN(addr64_t
, bytes
);
1040 IOByteCount remaining
;
1042 // Assert that this entire I/O is withing the available range
1043 assert(offset
< _length
);
1044 assert(offset
+ length
<= _length
);
1045 if (offset
>= _length
) {
1049 if (kIOMemoryThreadSafe
& _flags
)
1052 remaining
= length
= min(length
, _length
- offset
);
1053 while (remaining
) { // (process another target segment?)
1057 srcAddr64
= getPhysicalSegment(offset
, &srcLen
, kIOMemoryMapperNone
);
1061 // Clip segment length to remaining
1062 if (srcLen
> remaining
)
1065 copypv(srcAddr64
, dstAddr
, srcLen
,
1066 cppvPsrc
| cppvNoRefSrc
| cppvFsnk
| cppvKmap
);
1070 remaining
-= srcLen
;
1073 if (kIOMemoryThreadSafe
& _flags
)
1078 return length
- remaining
;
1081 IOByteCount
IOMemoryDescriptor::writeBytes
1082 (IOByteCount offset
, const void *bytes
, IOByteCount length
)
1084 addr64_t srcAddr
= CAST_DOWN(addr64_t
, bytes
);
1085 IOByteCount remaining
;
1087 // Assert that this entire I/O is withing the available range
1088 assert(offset
< _length
);
1089 assert(offset
+ length
<= _length
);
1091 assert( !(kIOMemoryPreparedReadOnly
& _flags
) );
1093 if ( (kIOMemoryPreparedReadOnly
& _flags
) || offset
>= _length
) {
1097 if (kIOMemoryThreadSafe
& _flags
)
1100 remaining
= length
= min(length
, _length
- offset
);
1101 while (remaining
) { // (process another target segment?)
1105 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1109 // Clip segment length to remaining
1110 if (dstLen
> remaining
)
1113 copypv(srcAddr
, (addr64_t
) dstAddr64
, dstLen
,
1114 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
1118 remaining
-= dstLen
;
1121 if (kIOMemoryThreadSafe
& _flags
)
1126 return length
- remaining
;
1129 // osfmk/device/iokit_rpc.c
1130 extern "C" unsigned int IODefaultCacheBits(addr64_t pa
);
1133 void IOGeneralMemoryDescriptor::setPosition(IOByteCount position
)
1135 panic("IOGMD::setPosition deprecated");
1137 #endif /* !__LP64__ */
1139 static volatile SInt64 gIOMDPreparationID
__attribute__((aligned(8))) = (1ULL << 32);
1142 IOGeneralMemoryDescriptor::getPreparationID( void )
1147 return (kIOPreparationIDUnprepared
);
1149 if (_flags
& (kIOMemoryTypePhysical
| kIOMemoryTypePhysical64
))
1151 IOMemoryDescriptor::setPreparationID();
1152 return (IOMemoryDescriptor::getPreparationID());
1155 if (!_memoryEntries
|| !(dataP
= getDataP(_memoryEntries
)))
1156 return (kIOPreparationIDUnprepared
);
1158 if (kIOPreparationIDUnprepared
== dataP
->fPreparationID
)
1160 dataP
->fPreparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1162 return (dataP
->fPreparationID
);
1165 IOMemoryDescriptorReserved
* IOMemoryDescriptor::getKernelReserved( void )
1169 reserved
= IONew(IOMemoryDescriptorReserved
, 1);
1171 bzero(reserved
, sizeof(IOMemoryDescriptorReserved
));
1176 void IOMemoryDescriptor::setPreparationID( void )
1178 if (getKernelReserved() && (kIOPreparationIDUnprepared
== reserved
->preparationID
))
1180 #if defined(__ppc__ )
1181 reserved
->preparationID
= gIOMDPreparationID
++;
1183 reserved
->preparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1188 uint64_t IOMemoryDescriptor::getPreparationID( void )
1191 return (reserved
->preparationID
);
1193 return (kIOPreparationIDUnsupported
);
1196 IOReturn
IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1198 if (kIOMDGetCharacteristics
== op
) {
1200 if (dataSize
< sizeof(IOMDDMACharacteristics
))
1201 return kIOReturnUnderrun
;
1203 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
1204 data
->fLength
= _length
;
1205 data
->fSGCount
= _rangesCount
;
1206 data
->fPages
= _pages
;
1207 data
->fDirection
= getDirection();
1209 data
->fIsPrepared
= false;
1211 data
->fIsPrepared
= true;
1212 data
->fHighestPage
= _highestPage
;
1213 if (_memoryEntries
) {
1214 ioGMDData
*gmdData
= getDataP(_memoryEntries
);
1215 ioPLBlock
*ioplList
= getIOPLList(gmdData
);
1216 UInt count
= getNumIOPL(_memoryEntries
, gmdData
);
1218 data
->fIsMapped
= (gmdData
->fMapper
&& _pages
&& (count
> 0)
1219 && ioplList
[0].fMappedBase
);
1221 data
->fPageAlign
= (ioplList
[0].fPageOffset
& PAGE_MASK
) | ~PAGE_MASK
;
1224 data
->fIsMapped
= false;
1227 return kIOReturnSuccess
;
1229 #if IOMD_DEBUG_DMAACTIVE
1230 } else if (kIOMDSetDMAActive
== op
) {
1231 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
1232 OSIncrementAtomic(&md
->__iomd_reservedA
);
1233 } else if (kIOMDSetDMAInactive
== op
) {
1234 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
1235 if (md
->__iomd_reservedA
)
1236 OSDecrementAtomic(&md
->__iomd_reservedA
);
1238 panic("kIOMDSetDMAInactive");
1239 #endif /* IOMD_DEBUG_DMAACTIVE */
1241 } else if (!(kIOMDWalkSegments
& op
))
1242 return kIOReturnBadArgument
;
1244 // Get the next segment
1245 struct InternalState
{
1246 IOMDDMAWalkSegmentArgs fIO
;
1252 // Find the next segment
1253 if (dataSize
< sizeof(*isP
))
1254 return kIOReturnUnderrun
;
1256 isP
= (InternalState
*) vData
;
1257 UInt offset
= isP
->fIO
.fOffset
;
1258 bool mapped
= isP
->fIO
.fMapped
;
1260 if (offset
>= _length
)
1261 return (offset
== _length
)? kIOReturnOverrun
: kIOReturnInternalError
;
1263 // Validate the previous offset
1264 UInt ind
, off2Ind
= isP
->fOffset2Index
;
1265 if ((kIOMDFirstSegment
!= op
)
1267 && (offset
== isP
->fNextOffset
|| off2Ind
<= offset
))
1270 ind
= off2Ind
= 0; // Start from beginning
1274 if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
) {
1276 // Physical address based memory descriptor
1277 const IOPhysicalRange
*physP
= (IOPhysicalRange
*) &_ranges
.p
[0];
1279 // Find the range after the one that contains the offset
1281 for (len
= 0; off2Ind
<= offset
; ind
++) {
1282 len
= physP
[ind
].length
;
1286 // Calculate length within range and starting address
1287 length
= off2Ind
- offset
;
1288 address
= physP
[ind
- 1].address
+ len
- length
;
1290 // see how far we can coalesce ranges
1291 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
1292 len
= physP
[ind
].length
;
1298 // correct contiguous check overshoot
1303 else if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
) {
1305 // Physical address based memory descriptor
1306 const IOAddressRange
*physP
= (IOAddressRange
*) &_ranges
.v64
[0];
1308 // Find the range after the one that contains the offset
1310 for (len
= 0; off2Ind
<= offset
; ind
++) {
1311 len
= physP
[ind
].length
;
1315 // Calculate length within range and starting address
1316 length
= off2Ind
- offset
;
1317 address
= physP
[ind
- 1].address
+ len
- length
;
1319 // see how far we can coalesce ranges
1320 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
1321 len
= physP
[ind
].length
;
1327 // correct contiguous check overshoot
1331 #endif /* !__LP64__ */
1334 panic("IOGMD: not wired for the IODMACommand");
1336 assert(_memoryEntries
);
1338 ioGMDData
* dataP
= getDataP(_memoryEntries
);
1339 const ioPLBlock
*ioplList
= getIOPLList(dataP
);
1340 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
1341 upl_page_info_t
*pageList
= getPageList(dataP
);
1343 assert(numIOPLs
> 0);
1345 // Scan through iopl info blocks looking for block containing offset
1346 while (ind
< numIOPLs
&& offset
>= ioplList
[ind
].fIOMDOffset
)
1349 // Go back to actual range as search goes past it
1350 ioPLBlock ioplInfo
= ioplList
[ind
- 1];
1351 off2Ind
= ioplInfo
.fIOMDOffset
;
1354 length
= ioplList
[ind
].fIOMDOffset
;
1357 length
-= offset
; // Remainder within iopl
1359 // Subtract offset till this iopl in total list
1362 // If a mapped address is requested and this is a pre-mapped IOPL
1363 // then just need to compute an offset relative to the mapped base.
1364 if (mapped
&& ioplInfo
.fMappedBase
) {
1365 offset
+= (ioplInfo
.fPageOffset
& PAGE_MASK
);
1366 address
= ptoa_64(ioplInfo
.fMappedBase
) + offset
;
1367 continue; // Done leave do/while(false) now
1370 // The offset is rebased into the current iopl.
1371 // Now add the iopl 1st page offset.
1372 offset
+= ioplInfo
.fPageOffset
;
1374 // For external UPLs the fPageInfo field points directly to
1375 // the upl's upl_page_info_t array.
1376 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
1377 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
1379 pageList
= &pageList
[ioplInfo
.fPageInfo
];
1381 // Check for direct device non-paged memory
1382 if ( ioplInfo
.fFlags
& kIOPLOnDevice
) {
1383 address
= ptoa_64(pageList
->phys_addr
) + offset
;
1384 continue; // Done leave do/while(false) now
1387 // Now we need compute the index into the pageList
1388 UInt pageInd
= atop_32(offset
);
1389 offset
&= PAGE_MASK
;
1391 // Compute the starting address of this segment
1392 IOPhysicalAddress pageAddr
= pageList
[pageInd
].phys_addr
;
1394 panic("!pageList phys_addr");
1397 address
= ptoa_64(pageAddr
) + offset
;
1399 // length is currently set to the length of the remainider of the iopl.
1400 // We need to check that the remainder of the iopl is contiguous.
1401 // This is indicated by pageList[ind].phys_addr being sequential.
1402 IOByteCount contigLength
= PAGE_SIZE
- offset
;
1403 while (contigLength
< length
1404 && ++pageAddr
== pageList
[++pageInd
].phys_addr
)
1406 contigLength
+= PAGE_SIZE
;
1409 if (contigLength
< length
)
1410 length
= contigLength
;
1418 // Update return values and state
1419 isP
->fIO
.fIOVMAddr
= address
;
1420 isP
->fIO
.fLength
= length
;
1422 isP
->fOffset2Index
= off2Ind
;
1423 isP
->fNextOffset
= isP
->fIO
.fOffset
+ length
;
1425 return kIOReturnSuccess
;
1429 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
1432 addr64_t address
= 0;
1433 IOByteCount length
= 0;
1434 IOMapper
* mapper
= gIOSystemMapper
;
1435 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1437 if (lengthOfSegment
)
1438 *lengthOfSegment
= 0;
1440 if (offset
>= _length
)
1443 // IOMemoryDescriptor::doMap() cannot use getPhysicalSegment() to obtain the page offset, since it must
1444 // support the unwired memory case in IOGeneralMemoryDescriptor, and hibernate_write_image() cannot use
1445 // map()->getVirtualAddress() to obtain the kernel pointer, since it must prevent the memory allocation
1446 // due to IOMemoryMap, so _kIOMemorySourceSegment is a necessary evil until all of this gets cleaned up
1448 if ((options
& _kIOMemorySourceSegment
) && (kIOMemoryTypeUPL
!= type
))
1450 unsigned rangesIndex
= 0;
1451 Ranges vec
= _ranges
;
1454 // Find starting address within the vector of ranges
1456 getAddrLenForInd(addr
, length
, type
, vec
, rangesIndex
);
1457 if (offset
< length
)
1459 offset
-= length
; // (make offset relative)
1463 // Now that we have the starting range,
1464 // lets find the last contiguous range
1468 for ( ++rangesIndex
; rangesIndex
< _rangesCount
; rangesIndex
++ ) {
1469 user_addr_t newAddr
;
1470 IOPhysicalLength newLen
;
1472 getAddrLenForInd(newAddr
, newLen
, type
, vec
, rangesIndex
);
1473 if (addr
+ length
!= newAddr
)
1478 address
= (IOPhysicalAddress
) addr
; // Truncate address to 32bit
1482 IOMDDMAWalkSegmentState _state
;
1483 IOMDDMAWalkSegmentArgs
* state
= (IOMDDMAWalkSegmentArgs
*) &_state
;
1485 state
->fOffset
= offset
;
1486 state
->fLength
= _length
- offset
;
1487 state
->fMapped
= (0 == (options
& kIOMemoryMapperNone
));
1489 ret
= dmaCommandOperation(kIOMDFirstSegment
, _state
, sizeof(_state
));
1491 if ((kIOReturnSuccess
!= ret
) && (kIOReturnOverrun
!= ret
))
1492 DEBG("getPhysicalSegment dmaCommandOperation(%lx), %p, offset %qx, addr %qx, len %qx\n",
1493 ret
, this, state
->fOffset
,
1494 state
->fIOVMAddr
, state
->fLength
);
1495 if (kIOReturnSuccess
== ret
)
1497 address
= state
->fIOVMAddr
;
1498 length
= state
->fLength
;
1501 // dmaCommandOperation() does not distinguish between "mapped" and "unmapped" physical memory, even
1502 // with fMapped set correctly, so we must handle the transformation here until this gets cleaned up
1504 if (mapper
&& ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
)))
1506 if ((options
& kIOMemoryMapperNone
) && !(_flags
& kIOMemoryMapperNone
))
1508 addr64_t origAddr
= address
;
1509 IOByteCount origLen
= length
;
1511 address
= mapper
->mapAddr(origAddr
);
1512 length
= page_size
- (address
& (page_size
- 1));
1513 while ((length
< origLen
)
1514 && ((address
+ length
) == mapper
->mapAddr(origAddr
+ length
)))
1515 length
+= page_size
;
1516 if (length
> origLen
)
1520 else if (!(options
& kIOMemoryMapperNone
) && (_flags
& kIOMemoryMapperNone
))
1522 panic("getPhysicalSegment not mapped for I/O");
1524 #endif /* __LP64__ */
1531 if (lengthOfSegment
)
1532 *lengthOfSegment
= length
;
1539 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
1541 addr64_t address
= 0;
1543 if (options
& _kIOMemorySourceSegment
)
1545 address
= getSourceSegment(offset
, lengthOfSegment
);
1547 else if (options
& kIOMemoryMapperNone
)
1549 address
= getPhysicalSegment64(offset
, lengthOfSegment
);
1553 address
= getPhysicalSegment(offset
, lengthOfSegment
);
1560 IOGeneralMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1562 return (getPhysicalSegment(offset
, lengthOfSegment
, kIOMemoryMapperNone
));
1566 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1568 addr64_t address
= 0;
1569 IOByteCount length
= 0;
1571 address
= getPhysicalSegment(offset
, lengthOfSegment
, 0);
1573 if (lengthOfSegment
)
1574 length
= *lengthOfSegment
;
1576 if ((address
+ length
) > 0x100000000ULL
)
1578 panic("getPhysicalSegment() out of 32b range 0x%qx, len 0x%lx, class %s",
1579 address
, (long) length
, (getMetaClass())->getClassName());
1582 return ((IOPhysicalAddress
) address
);
1586 IOMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1588 IOPhysicalAddress phys32
;
1591 IOMapper
* mapper
= 0;
1593 phys32
= getPhysicalSegment(offset
, lengthOfSegment
);
1597 if (gIOSystemMapper
)
1598 mapper
= gIOSystemMapper
;
1602 IOByteCount origLen
;
1604 phys64
= mapper
->mapAddr(phys32
);
1605 origLen
= *lengthOfSegment
;
1606 length
= page_size
- (phys64
& (page_size
- 1));
1607 while ((length
< origLen
)
1608 && ((phys64
+ length
) == mapper
->mapAddr(phys32
+ length
)))
1609 length
+= page_size
;
1610 if (length
> origLen
)
1613 *lengthOfSegment
= length
;
1616 phys64
= (addr64_t
) phys32
;
1622 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1624 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, 0));
1628 IOGeneralMemoryDescriptor::getSourceSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1630 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, _kIOMemorySourceSegment
));
1633 void * IOGeneralMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
1634 IOByteCount
* lengthOfSegment
)
1636 if (_task
== kernel_task
)
1637 return (void *) getSourceSegment(offset
, lengthOfSegment
);
1639 panic("IOGMD::getVirtualSegment deprecated");
1643 #endif /* !__LP64__ */
1646 IOMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1648 if (kIOMDGetCharacteristics
== op
) {
1649 if (dataSize
< sizeof(IOMDDMACharacteristics
))
1650 return kIOReturnUnderrun
;
1652 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
1653 data
->fLength
= getLength();
1655 data
->fDirection
= getDirection();
1656 if (IOMapper::gSystem
)
1657 data
->fIsMapped
= true;
1658 data
->fIsPrepared
= true; // Assume prepared - fails safe
1660 else if (kIOMDWalkSegments
& op
) {
1661 if (dataSize
< sizeof(IOMDDMAWalkSegmentArgs
))
1662 return kIOReturnUnderrun
;
1664 IOMDDMAWalkSegmentArgs
*data
= (IOMDDMAWalkSegmentArgs
*) vData
;
1665 IOByteCount offset
= (IOByteCount
) data
->fOffset
;
1667 IOPhysicalLength length
;
1668 IOMemoryDescriptor
*ncmd
= const_cast<IOMemoryDescriptor
*>(this);
1669 if (data
->fMapped
&& IOMapper::gSystem
)
1670 data
->fIOVMAddr
= ncmd
->getPhysicalSegment(offset
, &length
);
1672 data
->fIOVMAddr
= ncmd
->getPhysicalSegment(offset
, &length
, kIOMemoryMapperNone
);
1673 data
->fLength
= length
;
1676 return kIOReturnBadArgument
;
1678 return kIOReturnSuccess
;
1682 purgeableControlBits(IOOptionBits newState
, vm_purgable_t
* control
, int * state
)
1684 IOReturn err
= kIOReturnSuccess
;
1686 *control
= VM_PURGABLE_SET_STATE
;
1689 case kIOMemoryPurgeableKeepCurrent
:
1690 *control
= VM_PURGABLE_GET_STATE
;
1693 case kIOMemoryPurgeableNonVolatile
:
1694 *state
= VM_PURGABLE_NONVOLATILE
;
1696 case kIOMemoryPurgeableVolatile
:
1697 *state
= VM_PURGABLE_VOLATILE
;
1699 case kIOMemoryPurgeableEmpty
:
1700 *state
= VM_PURGABLE_EMPTY
;
1703 err
= kIOReturnBadArgument
;
1710 purgeableStateBits(int * state
)
1712 IOReturn err
= kIOReturnSuccess
;
1716 case VM_PURGABLE_NONVOLATILE
:
1717 *state
= kIOMemoryPurgeableNonVolatile
;
1719 case VM_PURGABLE_VOLATILE
:
1720 *state
= kIOMemoryPurgeableVolatile
;
1722 case VM_PURGABLE_EMPTY
:
1723 *state
= kIOMemoryPurgeableEmpty
;
1726 *state
= kIOMemoryPurgeableNonVolatile
;
1727 err
= kIOReturnNotReady
;
1734 IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState
,
1735 IOOptionBits
* oldState
)
1737 IOReturn err
= kIOReturnSuccess
;
1738 vm_purgable_t control
;
1743 err
= super::setPurgeable(newState
, oldState
);
1747 if (kIOMemoryThreadSafe
& _flags
)
1751 // Find the appropriate vm_map for the given task
1753 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
1755 err
= kIOReturnNotReady
;
1759 curMap
= get_task_map(_task
);
1761 // can only do one range
1762 Ranges vec
= _ranges
;
1763 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1766 getAddrLenForInd(addr
, len
, type
, vec
, 0);
1768 err
= purgeableControlBits(newState
, &control
, &state
);
1769 if (kIOReturnSuccess
!= err
)
1771 err
= mach_vm_purgable_control(curMap
, addr
, control
, &state
);
1774 if (kIOReturnSuccess
== err
)
1776 err
= purgeableStateBits(&state
);
1782 if (kIOMemoryThreadSafe
& _flags
)
1788 IOReturn
IOMemoryDescriptor::setPurgeable( IOOptionBits newState
,
1789 IOOptionBits
* oldState
)
1791 IOReturn err
= kIOReturnSuccess
;
1792 vm_purgable_t control
;
1795 if (kIOMemoryThreadSafe
& _flags
)
1802 err
= kIOReturnNotReady
;
1805 err
= purgeableControlBits(newState
, &control
, &state
);
1806 if (kIOReturnSuccess
!= err
)
1808 err
= mach_memory_entry_purgable_control((ipc_port_t
) _memEntry
, control
, &state
);
1811 if (kIOReturnSuccess
== err
)
1813 err
= purgeableStateBits(&state
);
1820 if (kIOMemoryThreadSafe
& _flags
)
1826 extern "C" void dcache_incoherent_io_flush64(addr64_t pa
, unsigned int count
);
1827 extern "C" void dcache_incoherent_io_store64(addr64_t pa
, unsigned int count
);
1829 static void SetEncryptOp(addr64_t pa
, unsigned int count
)
1833 page
= atop_64(round_page_64(pa
));
1834 end
= atop_64(trunc_page_64(pa
+ count
));
1835 for (; page
< end
; page
++)
1837 pmap_clear_noencrypt(page
);
1841 static void ClearEncryptOp(addr64_t pa
, unsigned int count
)
1845 page
= atop_64(round_page_64(pa
));
1846 end
= atop_64(trunc_page_64(pa
+ count
));
1847 for (; page
< end
; page
++)
1849 pmap_set_noencrypt(page
);
1853 IOReturn
IOMemoryDescriptor::performOperation( IOOptionBits options
,
1854 IOByteCount offset
, IOByteCount length
)
1856 IOByteCount remaining
;
1858 void (*func
)(addr64_t pa
, unsigned int count
) = 0;
1862 case kIOMemoryIncoherentIOFlush
:
1863 func
= &dcache_incoherent_io_flush64
;
1865 case kIOMemoryIncoherentIOStore
:
1866 func
= &dcache_incoherent_io_store64
;
1869 case kIOMemorySetEncrypted
:
1870 func
= &SetEncryptOp
;
1872 case kIOMemoryClearEncrypted
:
1873 func
= &ClearEncryptOp
;
1878 return (kIOReturnUnsupported
);
1880 if (kIOMemoryThreadSafe
& _flags
)
1884 remaining
= length
= min(length
, getLength() - offset
);
1886 // (process another target segment?)
1891 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1895 // Clip segment length to remaining
1896 if (dstLen
> remaining
)
1899 (*func
)(dstAddr64
, dstLen
);
1902 remaining
-= dstLen
;
1905 if (kIOMemoryThreadSafe
& _flags
)
1908 return (remaining
? kIOReturnUnderrun
: kIOReturnSuccess
);
1911 #if defined(__i386__) || defined(__x86_64__)
1912 extern vm_offset_t first_avail
;
1913 #define io_kernel_static_end first_avail
1915 #error io_kernel_static_end is undefined for this architecture
1918 static kern_return_t
1919 io_get_kernel_static_upl(
1922 vm_size_t
*upl_size
,
1924 upl_page_info_array_t page_list
,
1925 unsigned int *count
,
1926 ppnum_t
*highest_page
)
1928 unsigned int pageCount
, page
;
1930 ppnum_t highestPage
= 0;
1932 pageCount
= atop_32(*upl_size
);
1933 if (pageCount
> *count
)
1938 for (page
= 0; page
< pageCount
; page
++)
1940 phys
= pmap_find_phys(kernel_pmap
, ((addr64_t
)offset
) + ptoa_64(page
));
1943 page_list
[page
].phys_addr
= phys
;
1944 page_list
[page
].pageout
= 0;
1945 page_list
[page
].absent
= 0;
1946 page_list
[page
].dirty
= 0;
1947 page_list
[page
].precious
= 0;
1948 page_list
[page
].device
= 0;
1949 if (phys
> highestPage
)
1953 *highest_page
= highestPage
;
1955 return ((page
>= pageCount
) ? kIOReturnSuccess
: kIOReturnVMError
);
1958 IOReturn
IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection
)
1960 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1961 IOReturn error
= kIOReturnCannotWire
;
1963 ppnum_t mapBase
= 0;
1965 ipc_port_t sharedMem
= (ipc_port_t
) _memEntry
;
1967 assert(!_wireCount
);
1968 assert(kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
);
1970 if (_pages
> gIOMaximumMappedIOPageCount
)
1971 return kIOReturnNoResources
;
1973 dataP
= getDataP(_memoryEntries
);
1974 mapper
= dataP
->fMapper
;
1975 if (mapper
&& _pages
)
1976 mapBase
= mapper
->iovmAlloc(_pages
);
1978 // Note that appendBytes(NULL) zeros the data up to the
1980 _memoryEntries
->appendBytes(0, dataP
->fPageCnt
* sizeof(upl_page_info_t
));
1981 dataP
= 0; // May no longer be valid so lets not get tempted.
1983 if (forDirection
== kIODirectionNone
)
1984 forDirection
= getDirection();
1986 int uplFlags
; // This Mem Desc's default flags for upl creation
1987 switch (kIODirectionOutIn
& forDirection
)
1989 case kIODirectionOut
:
1990 // Pages do not need to be marked as dirty on commit
1991 uplFlags
= UPL_COPYOUT_FROM
;
1992 _flags
|= kIOMemoryPreparedReadOnly
;
1995 case kIODirectionIn
:
1997 uplFlags
= 0; // i.e. ~UPL_COPYOUT_FROM
2000 uplFlags
|= UPL_SET_IO_WIRE
| UPL_SET_LITE
;
2002 #ifdef UPL_NEED_32BIT_ADDR
2003 if (kIODirectionPrepareToPhys32
& forDirection
)
2004 uplFlags
|= UPL_NEED_32BIT_ADDR
;
2007 // Find the appropriate vm_map for the given task
2009 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
2012 { curMap
= get_task_map(_task
); }
2014 // Iterate over the vector of virtual ranges
2015 Ranges vec
= _ranges
;
2016 unsigned int pageIndex
= 0;
2017 IOByteCount mdOffset
= 0;
2018 ppnum_t highestPage
= 0;
2019 for (UInt range
= 0; range
< _rangesCount
; range
++) {
2021 user_addr_t startPage
;
2022 IOByteCount numBytes
;
2023 ppnum_t highPage
= 0;
2025 // Get the startPage address and length of vec[range]
2026 getAddrLenForInd(startPage
, numBytes
, type
, vec
, range
);
2027 iopl
.fPageOffset
= startPage
& PAGE_MASK
;
2028 numBytes
+= iopl
.fPageOffset
;
2029 startPage
= trunc_page_64(startPage
);
2032 iopl
.fMappedBase
= mapBase
+ pageIndex
;
2034 iopl
.fMappedBase
= 0;
2036 // Iterate over the current range, creating UPLs
2038 dataP
= getDataP(_memoryEntries
);
2039 vm_address_t kernelStart
= (vm_address_t
) startPage
;
2043 else if (!sharedMem
) {
2044 assert(_task
== kernel_task
);
2045 theMap
= IOPageableMapForAddress(kernelStart
);
2050 upl_page_info_array_t pageInfo
= getPageList(dataP
);
2051 int ioplFlags
= uplFlags
;
2052 upl_page_list_ptr_t baseInfo
= &pageInfo
[pageIndex
];
2054 vm_size_t ioplSize
= round_page(numBytes
);
2055 unsigned int numPageInfo
= atop_32(ioplSize
);
2057 if (theMap
== kernel_map
&& kernelStart
< io_kernel_static_end
) {
2058 error
= io_get_kernel_static_upl(theMap
,
2066 else if (sharedMem
) {
2067 error
= memory_object_iopl_request(sharedMem
,
2077 error
= vm_map_create_upl(theMap
,
2079 (upl_size_t
*)&ioplSize
,
2087 if (error
!= KERN_SUCCESS
)
2091 highPage
= upl_get_highest_page(iopl
.fIOPL
);
2092 if (highPage
> highestPage
)
2093 highestPage
= highPage
;
2095 error
= kIOReturnCannotWire
;
2097 if (baseInfo
->device
) {
2099 iopl
.fFlags
= kIOPLOnDevice
;
2100 // Don't translate device memory at all
2101 if (mapper
&& mapBase
) {
2102 mapper
->iovmFree(mapBase
, _pages
);
2104 iopl
.fMappedBase
= 0;
2110 mapper
->iovmInsert(mapBase
, pageIndex
,
2111 baseInfo
, numPageInfo
);
2114 iopl
.fIOMDOffset
= mdOffset
;
2115 iopl
.fPageInfo
= pageIndex
;
2118 // used to remove the upl for auto prepares here, for some errant code
2119 // that freed memory before the descriptor pointing at it
2120 if ((_flags
& kIOMemoryAutoPrepare
) && iopl
.fIOPL
)
2122 upl_commit(iopl
.fIOPL
, 0, 0);
2123 upl_deallocate(iopl
.fIOPL
);
2128 if (!_memoryEntries
->appendBytes(&iopl
, sizeof(iopl
))) {
2129 // Clean up partial created and unsaved iopl
2131 upl_abort(iopl
.fIOPL
, 0);
2132 upl_deallocate(iopl
.fIOPL
);
2137 // Check for a multiple iopl's in one virtual range
2138 pageIndex
+= numPageInfo
;
2139 mdOffset
-= iopl
.fPageOffset
;
2140 if (ioplSize
< numBytes
) {
2141 numBytes
-= ioplSize
;
2142 startPage
+= ioplSize
;
2143 mdOffset
+= ioplSize
;
2144 iopl
.fPageOffset
= 0;
2146 iopl
.fMappedBase
= mapBase
+ pageIndex
;
2149 mdOffset
+= numBytes
;
2155 _highestPage
= highestPage
;
2157 return kIOReturnSuccess
;
2161 dataP
= getDataP(_memoryEntries
);
2162 UInt done
= getNumIOPL(_memoryEntries
, dataP
);
2163 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2165 for (UInt range
= 0; range
< done
; range
++)
2167 if (ioplList
[range
].fIOPL
) {
2168 upl_abort(ioplList
[range
].fIOPL
, 0);
2169 upl_deallocate(ioplList
[range
].fIOPL
);
2172 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
2174 if (mapper
&& mapBase
)
2175 mapper
->iovmFree(mapBase
, _pages
);
2178 if (error
== KERN_FAILURE
)
2179 error
= kIOReturnCannotWire
;
2187 * Prepare the memory for an I/O transfer. This involves paging in
2188 * the memory, if necessary, and wiring it down for the duration of
2189 * the transfer. The complete() method completes the processing of
2190 * the memory after the I/O transfer finishes. This method needn't
2191 * called for non-pageable memory.
2193 IOReturn
IOGeneralMemoryDescriptor::prepare(IODirection forDirection
)
2195 IOReturn error
= kIOReturnSuccess
;
2196 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2198 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
2199 return kIOReturnSuccess
;
2202 IOLockLock(_prepareLock
);
2205 && (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) ) {
2206 error
= wireVirtual(forDirection
);
2209 if (kIOReturnSuccess
== error
)
2212 if (1 == _wireCount
)
2214 if (kIOMemoryClearEncrypt
& _flags
)
2216 performOperation(kIOMemoryClearEncrypted
, 0, _length
);
2221 IOLockUnlock(_prepareLock
);
2229 * Complete processing of the memory after an I/O transfer finishes.
2230 * This method should not be called unless a prepare was previously
2231 * issued; the prepare() and complete() must occur in pairs, before
2232 * before and after an I/O transfer involving pageable memory.
2235 IOReturn
IOGeneralMemoryDescriptor::complete(IODirection
/* forDirection */)
2237 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2239 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
2240 return kIOReturnSuccess
;
2243 IOLockLock(_prepareLock
);
2249 if ((kIOMemoryClearEncrypt
& _flags
) && (1 == _wireCount
))
2251 performOperation(kIOMemorySetEncrypted
, 0, _length
);
2257 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2258 ioGMDData
* dataP
= getDataP(_memoryEntries
);
2259 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2260 UInt count
= getNumIOPL(_memoryEntries
, dataP
);
2262 #if IOMD_DEBUG_DMAACTIVE
2263 if (__iomd_reservedA
) panic("complete() while dma active");
2264 #endif /* IOMD_DEBUG_DMAACTIVE */
2266 if (dataP
->fMapper
&& _pages
&& ioplList
[0].fMappedBase
)
2267 dataP
->fMapper
->iovmFree(ioplList
[0].fMappedBase
, _pages
);
2269 // Only complete iopls that we created which are for TypeVirtual
2270 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) {
2271 for (UInt ind
= 0; ind
< count
; ind
++)
2272 if (ioplList
[ind
].fIOPL
) {
2273 upl_commit(ioplList
[ind
].fIOPL
, 0, 0);
2274 upl_deallocate(ioplList
[ind
].fIOPL
);
2276 } else if (kIOMemoryTypeUPL
== type
) {
2277 upl_set_referenced(ioplList
[0].fIOPL
, false);
2280 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
2282 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
2287 IOLockUnlock(_prepareLock
);
2289 return kIOReturnSuccess
;
2292 IOReturn
IOGeneralMemoryDescriptor::doMap(
2293 vm_map_t __addressMap
,
2294 IOVirtualAddress
* __address
,
2295 IOOptionBits options
,
2296 IOByteCount __offset
,
2297 IOByteCount __length
)
2301 if (!(kIOMap64Bit
& options
)) panic("IOGeneralMemoryDescriptor::doMap !64bit");
2302 #endif /* !__LP64__ */
2304 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
2305 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
2306 mach_vm_size_t length
= mapping
->fLength
;
2308 kern_return_t kr
= kIOReturnVMError
;
2309 ipc_port_t sharedMem
= (ipc_port_t
) _memEntry
;
2311 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2312 Ranges vec
= _ranges
;
2314 user_addr_t range0Addr
= 0;
2315 IOByteCount range0Len
= 0;
2317 if ((offset
>= _length
) || ((offset
+ length
) > _length
))
2318 return( kIOReturnBadArgument
);
2321 getAddrLenForInd(range0Addr
, range0Len
, type
, vec
, 0);
2323 // mapping source == dest? (could be much better)
2325 && (mapping
->fAddressMap
== get_task_map(_task
)) && (options
& kIOMapAnywhere
)
2326 && (1 == _rangesCount
) && (0 == offset
)
2327 && range0Addr
&& (length
<= range0Len
) )
2329 mapping
->fAddress
= range0Addr
;
2330 mapping
->fOptions
|= kIOMapStatic
;
2332 return( kIOReturnSuccess
);
2335 if( 0 == sharedMem
) {
2337 vm_size_t size
= ptoa_32(_pages
);
2341 memory_object_size_t actualSize
= size
;
2342 vm_prot_t prot
= VM_PROT_READ
;
2343 if (!(kIOMapReadOnly
& options
))
2344 prot
|= VM_PROT_WRITE
;
2345 else if (kIOMapDefaultCache
!= (options
& kIOMapCacheMask
))
2346 prot
|= VM_PROT_WRITE
;
2348 if (_rangesCount
== 1)
2350 kr
= mach_make_memory_entry_64(get_task_map(_task
),
2351 &actualSize
, range0Addr
,
2355 if( (_rangesCount
!= 1)
2356 || ((KERN_SUCCESS
== kr
) && (actualSize
!= round_page(size
))))
2360 IOLog("mach_vm_remap path for ranges %d size (%08llx:%08llx)\n",
2361 _rangesCount
, (UInt64
)actualSize
, (UInt64
)size
);
2363 kr
= kIOReturnVMError
;
2366 ipc_port_release_send(sharedMem
);
2367 sharedMem
= MACH_PORT_NULL
;
2370 mach_vm_address_t address
, segDestAddr
;
2371 mach_vm_size_t mapLength
;
2372 unsigned rangesIndex
;
2373 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2374 user_addr_t srcAddr
;
2375 IOPhysicalLength segLen
= 0;
2377 // Find starting address within the vector of ranges
2378 for (rangesIndex
= 0; rangesIndex
< _rangesCount
; rangesIndex
++) {
2379 getAddrLenForInd(srcAddr
, segLen
, type
, _ranges
, rangesIndex
);
2380 if (offset
< segLen
)
2382 offset
-= segLen
; // (make offset relative)
2385 mach_vm_size_t pageOffset
= (srcAddr
& PAGE_MASK
);
2386 address
= trunc_page_64(mapping
->fAddress
);
2388 if ((options
& kIOMapAnywhere
) || ((mapping
->fAddress
- address
) == pageOffset
))
2390 vm_map_t map
= mapping
->fAddressMap
;
2391 kr
= IOMemoryDescriptorMapCopy(&map
,
2393 offset
, &address
, round_page_64(length
+ pageOffset
));
2394 if (kr
== KERN_SUCCESS
)
2396 segDestAddr
= address
;
2403 vm_prot_t cur_prot
, max_prot
;
2405 if (segLen
> length
) segLen
= length
;
2406 kr
= mach_vm_remap(map
, &segDestAddr
, round_page_64(segLen
), PAGE_MASK
,
2407 VM_FLAGS_FIXED
| VM_FLAGS_OVERWRITE
,
2408 get_task_map(_task
), trunc_page_64(srcAddr
),
2413 if (KERN_SUCCESS
== kr
)
2415 if ((!(VM_PROT_READ
& cur_prot
))
2416 || (!(kIOMapReadOnly
& options
) && !(VM_PROT_WRITE
& cur_prot
)))
2418 kr
= KERN_PROTECTION_FAILURE
;
2421 if (KERN_SUCCESS
!= kr
)
2423 segDestAddr
+= segLen
;
2424 mapLength
-= segLen
;
2428 if (rangesIndex
>= _rangesCount
)
2430 kr
= kIOReturnBadArgument
;
2433 getAddrLenForInd(srcAddr
, segLen
, type
, vec
, rangesIndex
);
2434 if (srcAddr
& PAGE_MASK
)
2436 kr
= kIOReturnBadArgument
;
2439 if (segLen
> mapLength
)
2442 if (KERN_SUCCESS
!= kr
)
2444 mach_vm_deallocate(mapping
->fAddressMap
, address
, round_page_64(length
+ pageOffset
));
2448 if (KERN_SUCCESS
== kr
)
2449 mapping
->fAddress
= address
+ pageOffset
;
2451 mapping
->fAddress
= NULL
;
2457 { // _task == 0, must be physical
2459 memory_object_t pager
;
2460 unsigned int flags
= 0;
2462 IOPhysicalLength segLen
;
2464 pa
= getPhysicalSegment( offset
, &segLen
, kIOMemoryMapperNone
);
2466 if( !getKernelReserved())
2468 reserved
->dp
.pagerContig
= (1 == _rangesCount
);
2469 reserved
->dp
.memory
= this;
2471 /*What cache mode do we need*/
2472 switch(options
& kIOMapCacheMask
) {
2474 case kIOMapDefaultCache
:
2476 flags
= IODefaultCacheBits(pa
);
2477 if (DEVICE_PAGER_CACHE_INHIB
& flags
)
2479 if (DEVICE_PAGER_GUARDED
& flags
)
2480 mapping
->fOptions
|= kIOMapInhibitCache
;
2482 mapping
->fOptions
|= kIOMapWriteCombineCache
;
2484 else if (DEVICE_PAGER_WRITE_THROUGH
& flags
)
2485 mapping
->fOptions
|= kIOMapWriteThruCache
;
2487 mapping
->fOptions
|= kIOMapCopybackCache
;
2490 case kIOMapInhibitCache
:
2491 flags
= DEVICE_PAGER_CACHE_INHIB
|
2492 DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
2495 case kIOMapWriteThruCache
:
2496 flags
= DEVICE_PAGER_WRITE_THROUGH
|
2497 DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
2500 case kIOMapCopybackCache
:
2501 flags
= DEVICE_PAGER_COHERENT
;
2504 case kIOMapWriteCombineCache
:
2505 flags
= DEVICE_PAGER_CACHE_INHIB
|
2506 DEVICE_PAGER_COHERENT
;
2510 flags
|= reserved
->dp
.pagerContig
? DEVICE_PAGER_CONTIGUOUS
: 0;
2512 pager
= device_pager_setup( (memory_object_t
) 0, (uintptr_t) reserved
,
2517 kr
= mach_memory_object_memory_entry_64( (host_t
) 1, false /*internal*/,
2518 size
, VM_PROT_READ
| VM_PROT_WRITE
, pager
, &sharedMem
);
2520 assert( KERN_SUCCESS
== kr
);
2521 if( KERN_SUCCESS
!= kr
)
2523 device_pager_deallocate( pager
);
2524 pager
= MACH_PORT_NULL
;
2525 sharedMem
= MACH_PORT_NULL
;
2528 if( pager
&& sharedMem
)
2529 reserved
->dp
.devicePager
= pager
;
2533 _memEntry
= (void *) sharedMem
;
2540 result
= super::doMap( __addressMap
, __address
,
2541 options
, __offset
, __length
);
2546 IOReturn
IOGeneralMemoryDescriptor::doUnmap(
2547 vm_map_t addressMap
,
2548 IOVirtualAddress __address
,
2549 IOByteCount __length
)
2551 return (super::doUnmap(addressMap
, __address
, __length
));
2554 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2557 #define super OSObject
2559 OSDefineMetaClassAndStructors( IOMemoryMap
, OSObject
)
2561 OSMetaClassDefineReservedUnused(IOMemoryMap
, 0);
2562 OSMetaClassDefineReservedUnused(IOMemoryMap
, 1);
2563 OSMetaClassDefineReservedUnused(IOMemoryMap
, 2);
2564 OSMetaClassDefineReservedUnused(IOMemoryMap
, 3);
2565 OSMetaClassDefineReservedUnused(IOMemoryMap
, 4);
2566 OSMetaClassDefineReservedUnused(IOMemoryMap
, 5);
2567 OSMetaClassDefineReservedUnused(IOMemoryMap
, 6);
2568 OSMetaClassDefineReservedUnused(IOMemoryMap
, 7);
2570 /* ex-inline function implementation */
2571 IOPhysicalAddress
IOMemoryMap::getPhysicalAddress()
2572 { return( getPhysicalSegment( 0, 0 )); }
2574 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2576 bool IOMemoryMap::init(
2578 mach_vm_address_t toAddress
,
2579 IOOptionBits _options
,
2580 mach_vm_size_t _offset
,
2581 mach_vm_size_t _length
)
2589 fAddressMap
= get_task_map(intoTask
);
2592 vm_map_reference(fAddressMap
);
2594 fAddressTask
= intoTask
;
2595 fOptions
= _options
;
2598 fAddress
= toAddress
;
2603 bool IOMemoryMap::setMemoryDescriptor(IOMemoryDescriptor
* _memory
, mach_vm_size_t _offset
)
2610 if( (_offset
+ fLength
) > _memory
->getLength())
2618 if (fMemory
!= _memory
)
2619 fMemory
->removeMapping(this);
2627 struct IOMemoryDescriptorMapAllocRef
2629 ipc_port_t sharedMem
;
2631 mach_vm_address_t mapped
;
2632 mach_vm_size_t size
;
2633 mach_vm_size_t sourceOffset
;
2634 IOOptionBits options
;
2637 static kern_return_t
IOMemoryDescriptorMapAlloc(vm_map_t map
, void * _ref
)
2639 IOMemoryDescriptorMapAllocRef
* ref
= (IOMemoryDescriptorMapAllocRef
*)_ref
;
2645 vm_prot_t prot
= VM_PROT_READ
2646 | ((ref
->options
& kIOMapReadOnly
) ? 0 : VM_PROT_WRITE
);
2648 // VM system requires write access to change cache mode
2649 if (kIOMapDefaultCache
!= (ref
->options
& kIOMapCacheMask
))
2650 prot
|= VM_PROT_WRITE
;
2652 // set memory entry cache
2653 vm_prot_t memEntryCacheMode
= prot
| MAP_MEM_ONLY
;
2654 switch (ref
->options
& kIOMapCacheMask
)
2656 case kIOMapInhibitCache
:
2657 SET_MAP_MEM(MAP_MEM_IO
, memEntryCacheMode
);
2660 case kIOMapWriteThruCache
:
2661 SET_MAP_MEM(MAP_MEM_WTHRU
, memEntryCacheMode
);
2664 case kIOMapWriteCombineCache
:
2665 SET_MAP_MEM(MAP_MEM_WCOMB
, memEntryCacheMode
);
2668 case kIOMapCopybackCache
:
2669 SET_MAP_MEM(MAP_MEM_COPYBACK
, memEntryCacheMode
);
2672 case kIOMapCopybackInnerCache
:
2673 SET_MAP_MEM(MAP_MEM_INNERWBACK
, memEntryCacheMode
);
2676 case kIOMapDefaultCache
:
2678 SET_MAP_MEM(MAP_MEM_NOOP
, memEntryCacheMode
);
2682 vm_size_t unused
= 0;
2684 err
= mach_make_memory_entry( NULL
/*unused*/, &unused
, 0 /*unused*/,
2685 memEntryCacheMode
, NULL
, ref
->sharedMem
);
2686 if (KERN_SUCCESS
!= err
)
2687 IOLog("MAP_MEM_ONLY failed %d\n", err
);
2689 err
= mach_vm_map( map
,
2691 ref
->size
, 0 /* mask */,
2692 (( ref
->options
& kIOMapAnywhere
) ? VM_FLAGS_ANYWHERE
: VM_FLAGS_FIXED
)
2693 | VM_MAKE_TAG(VM_MEMORY_IOKIT
),
2694 ref
->sharedMem
, ref
->sourceOffset
,
2700 if( KERN_SUCCESS
!= err
) {
2708 err
= mach_vm_allocate(map
, &ref
->mapped
, ref
->size
,
2709 ((ref
->options
& kIOMapAnywhere
) ? VM_FLAGS_ANYWHERE
: VM_FLAGS_FIXED
)
2710 | VM_MAKE_TAG(VM_MEMORY_IOKIT
) );
2711 if( KERN_SUCCESS
!= err
) {
2716 // we have to make sure that these guys don't get copied if we fork.
2717 err
= vm_inherit(map
, ref
->mapped
, ref
->size
, VM_INHERIT_NONE
);
2718 assert( KERN_SUCCESS
== err
);
2727 IOMemoryDescriptorMapMemEntry(vm_map_t
* map
, ipc_port_t entry
, IOOptionBits options
, bool pageable
,
2728 mach_vm_size_t offset
,
2729 mach_vm_address_t
* address
, mach_vm_size_t length
)
2732 IOMemoryDescriptorMapAllocRef ref
;
2735 ref
.sharedMem
= entry
;
2736 ref
.sourceOffset
= trunc_page_64(offset
);
2737 ref
.options
= options
;
2740 if (options
& kIOMapAnywhere
)
2741 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
2744 ref
.mapped
= *address
;
2746 if( ref
.sharedMem
&& (ref
.map
== kernel_map
) && pageable
)
2747 err
= IOIteratePageableMaps( ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
2749 err
= IOMemoryDescriptorMapAlloc( ref
.map
, &ref
);
2751 *address
= ref
.mapped
;
2758 IOMemoryDescriptorMapCopy(vm_map_t
* map
,
2759 IOOptionBits options
,
2760 mach_vm_size_t offset
,
2761 mach_vm_address_t
* address
, mach_vm_size_t length
)
2764 IOMemoryDescriptorMapAllocRef ref
;
2767 ref
.sharedMem
= NULL
;
2768 ref
.sourceOffset
= trunc_page_64(offset
);
2769 ref
.options
= options
;
2772 if (options
& kIOMapAnywhere
)
2773 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
2776 ref
.mapped
= *address
;
2778 if (ref
.map
== kernel_map
)
2779 err
= IOIteratePageableMaps(ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
2781 err
= IOMemoryDescriptorMapAlloc(ref
.map
, &ref
);
2783 *address
= ref
.mapped
;
2789 IOReturn
IOMemoryDescriptor::doMap(
2790 vm_map_t __addressMap
,
2791 IOVirtualAddress
* __address
,
2792 IOOptionBits options
,
2793 IOByteCount __offset
,
2794 IOByteCount __length
)
2797 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::doMap !64bit");
2798 #endif /* !__LP64__ */
2800 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
2801 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
2802 mach_vm_size_t length
= mapping
->fLength
;
2804 IOReturn err
= kIOReturnSuccess
;
2805 memory_object_t pager
;
2806 mach_vm_size_t pageOffset
;
2807 IOPhysicalAddress sourceAddr
;
2808 unsigned int lock_count
;
2812 sourceAddr
= getPhysicalSegment( offset
, NULL
, _kIOMemorySourceSegment
);
2813 pageOffset
= sourceAddr
- trunc_page( sourceAddr
);
2816 pager
= (memory_object_t
) reserved
->dp
.devicePager
;
2818 pager
= MACH_PORT_NULL
;
2820 if ((kIOMapReference
|kIOMapUnique
) == ((kIOMapReference
|kIOMapUnique
) & options
))
2828 err
= kIOReturnNotReadable
;
2832 size
= round_page(mapping
->fLength
+ pageOffset
);
2833 flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
2834 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
2836 if (KERN_SUCCESS
!= memory_object_iopl_request((ipc_port_t
) _memEntry
, 0, &size
, &redirUPL2
,
2841 for (lock_count
= 0;
2842 IORecursiveLockHaveLock(gIOMemoryLock
);
2846 err
= upl_transpose(redirUPL2
, mapping
->fRedirUPL
);
2853 if (kIOReturnSuccess
!= err
)
2855 IOLog("upl_transpose(%x)\n", err
);
2856 err
= kIOReturnSuccess
;
2861 upl_commit(redirUPL2
, NULL
, 0);
2862 upl_deallocate(redirUPL2
);
2866 // swap the memEntries since they now refer to different vm_objects
2867 void * me
= _memEntry
;
2868 _memEntry
= mapping
->fMemory
->_memEntry
;
2869 mapping
->fMemory
->_memEntry
= me
;
2872 err
= handleFault( pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
2876 mach_vm_address_t address
;
2878 if (!(options
& kIOMapAnywhere
))
2880 address
= trunc_page_64(mapping
->fAddress
);
2881 if( (mapping
->fAddress
- address
) != pageOffset
)
2883 err
= kIOReturnVMError
;
2888 vm_map_t map
= mapping
->fAddressMap
;
2889 err
= IOMemoryDescriptorMapMemEntry(&map
, (ipc_port_t
) _memEntry
,
2890 options
, (kIOMemoryBufferPageable
& _flags
),
2891 offset
, &address
, round_page_64(length
+ pageOffset
));
2892 if( err
!= KERN_SUCCESS
)
2895 if (!_memEntry
|| pager
)
2897 err
= handleFault( pager
, mapping
->fAddressMap
, address
, offset
, length
, options
);
2898 if (err
!= KERN_SUCCESS
)
2899 doUnmap( mapping
->fAddressMap
, (IOVirtualAddress
) mapping
, 0 );
2903 if (kIOLogMapping
& gIOKitDebug
)
2904 IOLog("mapping(%x) desc %p @ %qx, map %p, address %qx, offset %qx, length %qx\n",
2905 err
, this, (uint64_t)sourceAddr
, mapping
, address
, offset
, length
);
2908 if (err
== KERN_SUCCESS
)
2909 mapping
->fAddress
= address
+ pageOffset
;
2911 mapping
->fAddress
= NULL
;
2919 IOReturn
IOMemoryDescriptor::handleFault(
2921 vm_map_t addressMap
,
2922 mach_vm_address_t address
,
2923 mach_vm_size_t sourceOffset
,
2924 mach_vm_size_t length
,
2925 IOOptionBits options
)
2927 IOReturn err
= kIOReturnSuccess
;
2928 memory_object_t pager
= (memory_object_t
) _pager
;
2929 mach_vm_size_t size
;
2930 mach_vm_size_t bytes
;
2931 mach_vm_size_t page
;
2932 mach_vm_size_t pageOffset
;
2933 mach_vm_size_t pagerOffset
;
2934 IOPhysicalLength segLen
;
2939 if( kIOMemoryRedirected
& _flags
)
2942 IOLog("sleep mem redirect %p, %qx\n", this, sourceOffset
);
2946 } while( kIOMemoryRedirected
& _flags
);
2949 return( kIOReturnSuccess
);
2952 physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
);
2954 pageOffset
= physAddr
- trunc_page_64( physAddr
);
2955 pagerOffset
= sourceOffset
;
2957 size
= length
+ pageOffset
;
2958 physAddr
-= pageOffset
;
2960 segLen
+= pageOffset
;
2964 // in the middle of the loop only map whole pages
2965 if( segLen
>= bytes
)
2967 else if( segLen
!= trunc_page( segLen
))
2968 err
= kIOReturnVMError
;
2969 if( physAddr
!= trunc_page_64( physAddr
))
2970 err
= kIOReturnBadArgument
;
2971 if (kIOReturnSuccess
!= err
)
2975 if( kIOLogMapping
& gIOKitDebug
)
2976 IOLog("IOMemoryMap::map(%p) 0x%qx->0x%qx:0x%qx\n",
2977 addressMap
, address
+ pageOffset
, physAddr
+ pageOffset
,
2978 segLen
- pageOffset
);
2983 if( reserved
&& reserved
->dp
.pagerContig
) {
2984 IOPhysicalLength allLen
;
2987 allPhys
= getPhysicalSegment( 0, &allLen
, kIOMemoryMapperNone
);
2989 err
= device_pager_populate_object( pager
, 0, atop_64(allPhys
), round_page(allLen
) );
2995 (page
< segLen
) && (KERN_SUCCESS
== err
);
2998 err
= device_pager_populate_object(pager
, pagerOffset
,
2999 (ppnum_t
)(atop_64(physAddr
+ page
)), page_size
);
3000 pagerOffset
+= page_size
;
3003 assert( KERN_SUCCESS
== err
);
3008 // This call to vm_fault causes an early pmap level resolution
3009 // of the mappings created above for kernel mappings, since
3010 // faulting in later can't take place from interrupt level.
3012 /* *** Temporary Workaround *** */
3014 if ((addressMap
== kernel_map
) && !(kIOMemoryRedirected
& _flags
))
3016 vm_fault(addressMap
,
3017 (vm_map_offset_t
)address
,
3018 VM_PROT_READ
|VM_PROT_WRITE
,
3019 FALSE
, THREAD_UNINT
, NULL
,
3020 (vm_map_offset_t
)0);
3023 /* *** Temporary Workaround *** */
3026 sourceOffset
+= segLen
- pageOffset
;
3032 while (bytes
&& (physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
)));
3035 err
= kIOReturnBadArgument
;
3040 IOReturn
IOMemoryDescriptor::doUnmap(
3041 vm_map_t addressMap
,
3042 IOVirtualAddress __address
,
3043 IOByteCount __length
)
3046 mach_vm_address_t address
;
3047 mach_vm_size_t length
;
3051 address
= __address
;
3056 addressMap
= ((IOMemoryMap
*) __address
)->fAddressMap
;
3057 address
= ((IOMemoryMap
*) __address
)->fAddress
;
3058 length
= ((IOMemoryMap
*) __address
)->fLength
;
3061 if ((addressMap
== kernel_map
)
3062 && ((kIOMemoryBufferPageable
& _flags
) || !_memEntry
))
3063 addressMap
= IOPageableMapForAddress( address
);
3066 if( kIOLogMapping
& gIOKitDebug
)
3067 IOLog("IOMemoryDescriptor::doUnmap map %p, 0x%qx:0x%qx\n",
3068 addressMap
, address
, length
);
3071 err
= mach_vm_deallocate( addressMap
, address
, length
);
3076 IOReturn
IOMemoryDescriptor::redirect( task_t safeTask
, bool doRedirect
)
3078 IOReturn err
= kIOReturnSuccess
;
3079 IOMemoryMap
* mapping
= 0;
3085 _flags
|= kIOMemoryRedirected
;
3087 _flags
&= ~kIOMemoryRedirected
;
3090 if( (iter
= OSCollectionIterator::withCollection( _mappings
))) {
3091 while( (mapping
= (IOMemoryMap
*) iter
->getNextObject()))
3092 mapping
->redirect( safeTask
, doRedirect
);
3106 // temporary binary compatibility
3107 IOSubMemoryDescriptor
* subMem
;
3108 if( (subMem
= OSDynamicCast( IOSubMemoryDescriptor
, this)))
3109 err
= subMem
->redirect( safeTask
, doRedirect
);
3111 err
= kIOReturnSuccess
;
3112 #endif /* !__LP64__ */
3117 IOReturn
IOMemoryMap::redirect( task_t safeTask
, bool doRedirect
)
3119 IOReturn err
= kIOReturnSuccess
;
3122 // err = ((IOMemoryMap *)superMap)->redirect( safeTask, doRedirect );
3134 if ((!safeTask
|| (get_task_map(safeTask
) != fAddressMap
))
3135 && (0 == (fOptions
& kIOMapStatic
)))
3137 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3138 err
= kIOReturnSuccess
;
3140 IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect
, this, fAddress
, fLength
, fAddressMap
);
3143 else if (kIOMapWriteCombineCache
== (fOptions
& kIOMapCacheMask
))
3145 IOOptionBits newMode
;
3146 newMode
= (fOptions
& ~kIOMapCacheMask
) | (doRedirect
? kIOMapInhibitCache
: kIOMapWriteCombineCache
);
3147 IOProtectCacheMode(fAddressMap
, fAddress
, fLength
, newMode
);
3154 if ((((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3155 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3157 && (doRedirect
!= (0 != (fMemory
->_flags
& kIOMemoryRedirected
))))
3158 fMemory
->redirect(safeTask
, doRedirect
);
3163 IOReturn
IOMemoryMap::unmap( void )
3169 if( fAddress
&& fAddressMap
&& (0 == fSuperMap
) && fMemory
3170 && (0 == (fOptions
& kIOMapStatic
))) {
3172 err
= fMemory
->doUnmap(fAddressMap
, (IOVirtualAddress
) this, 0);
3175 err
= kIOReturnSuccess
;
3179 vm_map_deallocate(fAddressMap
);
3190 void IOMemoryMap::taskDied( void )
3193 if (fUserClientUnmap
)
3196 vm_map_deallocate(fAddressMap
);
3204 IOReturn
IOMemoryMap::userClientUnmap( void )
3206 fUserClientUnmap
= true;
3207 return (kIOReturnSuccess
);
3210 // Overload the release mechanism. All mappings must be a member
3211 // of a memory descriptors _mappings set. This means that we
3212 // always have 2 references on a mapping. When either of these mappings
3213 // are released we need to free ourselves.
3214 void IOMemoryMap::taggedRelease(const void *tag
) const
3217 super::taggedRelease(tag
, 2);
3221 void IOMemoryMap::free()
3228 fMemory
->removeMapping(this);
3233 if (fOwner
&& (fOwner
!= fMemory
))
3236 fOwner
->removeMapping(this);
3241 fSuperMap
->release();
3244 upl_commit(fRedirUPL
, NULL
, 0);
3245 upl_deallocate(fRedirUPL
);
3251 IOByteCount
IOMemoryMap::getLength()
3256 IOVirtualAddress
IOMemoryMap::getVirtualAddress()
3260 fSuperMap
->getVirtualAddress();
3261 else if (fAddressMap
3262 && vm_map_is_64bit(fAddressMap
)
3263 && (sizeof(IOVirtualAddress
) < 8))
3265 OSReportWithBacktrace("IOMemoryMap::getVirtualAddress(0x%qx) called on 64b map; use ::getAddress()", fAddress
);
3267 #endif /* !__LP64__ */
3273 mach_vm_address_t
IOMemoryMap::getAddress()
3278 mach_vm_size_t
IOMemoryMap::getSize()
3282 #endif /* !__LP64__ */
3285 task_t
IOMemoryMap::getAddressTask()
3288 return( fSuperMap
->getAddressTask());
3290 return( fAddressTask
);
3293 IOOptionBits
IOMemoryMap::getMapOptions()
3298 IOMemoryDescriptor
* IOMemoryMap::getMemoryDescriptor()
3303 IOMemoryMap
* IOMemoryMap::copyCompatible(
3304 IOMemoryMap
* newMapping
)
3306 task_t task
= newMapping
->getAddressTask();
3307 mach_vm_address_t toAddress
= newMapping
->fAddress
;
3308 IOOptionBits _options
= newMapping
->fOptions
;
3309 mach_vm_size_t _offset
= newMapping
->fOffset
;
3310 mach_vm_size_t _length
= newMapping
->fLength
;
3312 if( (!task
) || (!fAddressMap
) || (fAddressMap
!= get_task_map(task
)))
3314 if( (fOptions
^ _options
) & kIOMapReadOnly
)
3316 if( (kIOMapDefaultCache
!= (_options
& kIOMapCacheMask
))
3317 && ((fOptions
^ _options
) & kIOMapCacheMask
))
3320 if( (0 == (_options
& kIOMapAnywhere
)) && (fAddress
!= toAddress
))
3323 if( _offset
< fOffset
)
3328 if( (_offset
+ _length
) > fLength
)
3332 if( (fLength
== _length
) && (!_offset
))
3338 newMapping
->fSuperMap
= this;
3339 newMapping
->fOffset
= fOffset
+ _offset
;
3340 newMapping
->fAddress
= fAddress
+ _offset
;
3343 return( newMapping
);
3348 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
, IOOptionBits _options
)
3349 #else /* !__LP64__ */
3350 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
)
3351 #endif /* !__LP64__ */
3353 IOPhysicalAddress address
;
3357 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
, _options
);
3358 #else /* !__LP64__ */
3359 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
);
3360 #endif /* !__LP64__ */
3366 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3369 #define super OSObject
3371 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3373 void IOMemoryDescriptor::initialize( void )
3375 if( 0 == gIOMemoryLock
)
3376 gIOMemoryLock
= IORecursiveLockAlloc();
3378 IORegistryEntry::getRegistryRoot()->setProperty(kIOMaximumMappedIOByteCountKey
,
3379 ptoa_64(gIOMaximumMappedIOPageCount
), 64);
3380 gIOLastPage
= IOGetLastPageNumber();
3383 void IOMemoryDescriptor::free( void )
3386 _mappings
->release();
3391 IOMemoryMap
* IOMemoryDescriptor::setMapping(
3393 IOVirtualAddress mapAddress
,
3394 IOOptionBits options
)
3396 return (createMappingInTask( intoTask
, mapAddress
,
3397 options
| kIOMapStatic
,
3401 IOMemoryMap
* IOMemoryDescriptor::map(
3402 IOOptionBits options
)
3404 return (createMappingInTask( kernel_task
, 0,
3405 options
| kIOMapAnywhere
,
3410 IOMemoryMap
* IOMemoryDescriptor::map(
3412 IOVirtualAddress atAddress
,
3413 IOOptionBits options
,
3415 IOByteCount length
)
3417 if ((!(kIOMapAnywhere
& options
)) && vm_map_is_64bit(get_task_map(intoTask
)))
3419 OSReportWithBacktrace("IOMemoryDescriptor::map() in 64b task, use ::createMappingInTask()");
3423 return (createMappingInTask(intoTask
, atAddress
,
3424 options
, offset
, length
));
3426 #endif /* !__LP64__ */
3428 IOMemoryMap
* IOMemoryDescriptor::createMappingInTask(
3430 mach_vm_address_t atAddress
,
3431 IOOptionBits options
,
3432 mach_vm_size_t offset
,
3433 mach_vm_size_t length
)
3435 IOMemoryMap
* result
;
3436 IOMemoryMap
* mapping
;
3439 length
= getLength();
3441 mapping
= new IOMemoryMap
;
3444 && !mapping
->init( intoTask
, atAddress
,
3445 options
, offset
, length
)) {
3451 result
= makeMapping(this, intoTask
, (IOVirtualAddress
) mapping
, options
| kIOMap64Bit
, 0, 0);
3457 IOLog("createMappingInTask failed desc %p, addr %qx, options %x, offset %qx, length %llx\n",
3458 this, atAddress
, (uint32_t) options
, offset
, length
);
3464 #ifndef __LP64__ // there is only a 64 bit version for LP64
3465 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
3466 IOOptionBits options
,
3469 return (redirect(newBackingMemory
, options
, (mach_vm_size_t
)offset
));
3473 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
3474 IOOptionBits options
,
3475 mach_vm_size_t offset
)
3477 IOReturn err
= kIOReturnSuccess
;
3478 IOMemoryDescriptor
* physMem
= 0;
3482 if (fAddress
&& fAddressMap
) do
3484 if (((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3485 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3493 vm_size_t size
= round_page(fLength
);
3494 int flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3495 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
3496 if (KERN_SUCCESS
!= memory_object_iopl_request((ipc_port_t
) fMemory
->_memEntry
, 0, &size
, &fRedirUPL
,
3503 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3505 physMem
->redirect(0, true);
3509 if (newBackingMemory
)
3511 if (newBackingMemory
!= fMemory
)
3514 if (this != newBackingMemory
->makeMapping(newBackingMemory
, fAddressTask
, (IOVirtualAddress
) this,
3515 options
| kIOMapUnique
| kIOMapReference
| kIOMap64Bit
,
3517 err
= kIOReturnError
;
3521 upl_commit(fRedirUPL
, NULL
, 0);
3522 upl_deallocate(fRedirUPL
);
3525 if (false && physMem
)
3526 physMem
->redirect(0, false);
3539 IOMemoryMap
* IOMemoryDescriptor::makeMapping(
3540 IOMemoryDescriptor
* owner
,
3542 IOVirtualAddress __address
,
3543 IOOptionBits options
,
3544 IOByteCount __offset
,
3545 IOByteCount __length
)
3548 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::makeMapping !64bit");
3549 #endif /* !__LP64__ */
3551 IOMemoryDescriptor
* mapDesc
= 0;
3552 IOMemoryMap
* result
= 0;
3555 IOMemoryMap
* mapping
= (IOMemoryMap
*) __address
;
3556 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3557 mach_vm_size_t length
= mapping
->fLength
;
3559 mapping
->fOffset
= offset
;
3565 if (kIOMapStatic
& options
)
3568 addMapping(mapping
);
3569 mapping
->setMemoryDescriptor(this, 0);
3573 if (kIOMapUnique
& options
)
3576 IOByteCount physLen
;
3578 // if (owner != this) continue;
3580 if (((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3581 || ((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3583 phys
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
3584 if (!phys
|| (physLen
< length
))
3587 mapDesc
= IOMemoryDescriptor::withAddressRange(
3588 phys
, length
, getDirection() | kIOMemoryMapperNone
, NULL
);
3592 mapping
->fOffset
= offset
;
3597 // look for a compatible existing mapping
3598 if( (iter
= OSCollectionIterator::withCollection(_mappings
)))
3600 IOMemoryMap
* lookMapping
;
3601 while ((lookMapping
= (IOMemoryMap
*) iter
->getNextObject()))
3603 if ((result
= lookMapping
->copyCompatible(mapping
)))
3606 result
->setMemoryDescriptor(this, offset
);
3612 if (result
|| (options
& kIOMapReference
))
3614 if (result
!= mapping
)
3629 kr
= mapDesc
->doMap( 0, (IOVirtualAddress
*) &mapping
, options
, 0, 0 );
3630 if (kIOReturnSuccess
== kr
)
3633 mapDesc
->addMapping(result
);
3634 result
->setMemoryDescriptor(mapDesc
, offset
);
3652 void IOMemoryDescriptor::addMapping(
3653 IOMemoryMap
* mapping
)
3658 _mappings
= OSSet::withCapacity(1);
3660 _mappings
->setObject( mapping
);
3664 void IOMemoryDescriptor::removeMapping(
3665 IOMemoryMap
* mapping
)
3668 _mappings
->removeObject( mapping
);
3672 // obsolete initializers
3673 // - initWithOptions is the designated initializer
3675 IOMemoryDescriptor::initWithAddress(void * address
,
3677 IODirection direction
)
3683 IOMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
3685 IODirection direction
,
3692 IOMemoryDescriptor::initWithPhysicalAddress(
3693 IOPhysicalAddress address
,
3695 IODirection direction
)
3701 IOMemoryDescriptor::initWithRanges(
3702 IOVirtualRange
* ranges
,
3704 IODirection direction
,
3712 IOMemoryDescriptor::initWithPhysicalRanges( IOPhysicalRange
* ranges
,
3714 IODirection direction
,
3720 void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
3721 IOByteCount
* lengthOfSegment
)
3725 #endif /* !__LP64__ */
3727 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3729 bool IOGeneralMemoryDescriptor::serialize(OSSerialize
* s
) const
3731 OSSymbol
const *keys
[2];
3732 OSObject
*values
[2];
3734 user_addr_t address
;
3737 unsigned int index
, nRanges
;
3740 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3742 if (s
== NULL
) return false;
3743 if (s
->previouslySerialized(this)) return true;
3745 // Pretend we are an array.
3746 if (!s
->addXMLStartTag(this, "array")) return false;
3748 nRanges
= _rangesCount
;
3749 vcopy
= (SerData
*) IOMalloc(sizeof(SerData
) * nRanges
);
3750 if (vcopy
== 0) return false;
3752 keys
[0] = OSSymbol::withCString("address");
3753 keys
[1] = OSSymbol::withCString("length");
3756 values
[0] = values
[1] = 0;
3758 // From this point on we can go to bail.
3760 // Copy the volatile data so we don't have to allocate memory
3761 // while the lock is held.
3763 if (nRanges
== _rangesCount
) {
3764 Ranges vec
= _ranges
;
3765 for (index
= 0; index
< nRanges
; index
++) {
3766 user_addr_t addr
; IOByteCount len
;
3767 getAddrLenForInd(addr
, len
, type
, vec
, index
);
3768 vcopy
[index
].address
= addr
;
3769 vcopy
[index
].length
= len
;
3772 // The descriptor changed out from under us. Give up.
3779 for (index
= 0; index
< nRanges
; index
++)
3781 user_addr_t addr
= vcopy
[index
].address
;
3782 IOByteCount len
= (IOByteCount
) vcopy
[index
].length
;
3784 OSNumber::withNumber(addr
, sizeof(addr
) * 8);
3785 if (values
[0] == 0) {
3789 values
[1] = OSNumber::withNumber(len
, sizeof(len
) * 8);
3790 if (values
[1] == 0) {
3794 OSDictionary
*dict
= OSDictionary::withObjects((const OSObject
**)values
, (const OSSymbol
**)keys
, 2);
3799 values
[0]->release();
3800 values
[1]->release();
3801 values
[0] = values
[1] = 0;
3803 result
= dict
->serialize(s
);
3809 result
= s
->addXMLEndTag("array");
3813 values
[0]->release();
3815 values
[1]->release();
3821 IOFree(vcopy
, sizeof(SerData
) * nRanges
);
3825 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3827 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 0);
3829 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 1);
3830 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 2);
3831 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 3);
3832 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 4);
3833 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 5);
3834 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 6);
3835 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 7);
3836 #else /* !__LP64__ */
3837 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 1);
3838 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 2);
3839 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 3);
3840 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 4);
3841 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 5);
3842 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 6);
3843 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 7);
3844 #endif /* !__LP64__ */
3845 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 8);
3846 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 9);
3847 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 10);
3848 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 11);
3849 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 12);
3850 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 13);
3851 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 14);
3852 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 15);
3854 /* ex-inline function implementation */
3856 IOMemoryDescriptor::getPhysicalAddress()
3857 { return( getPhysicalSegment( 0, 0 )); }