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 void ipc_port_release_send(ipc_port_t port
);
76 /* Copy between a physical page and a virtual address in the given vm_map */
77 kern_return_t
copypv(addr64_t source
, addr64_t sink
, unsigned int size
, int which
);
81 memory_object_t pager
,
82 uintptr_t device_handle
,
86 device_pager_deallocate(
89 device_pager_populate_object(
90 memory_object_t pager
,
91 vm_object_offset_t offset
,
95 memory_object_iopl_request(
97 memory_object_offset_t offset
,
100 upl_page_info_array_t user_page_list
,
101 unsigned int *page_list_count
,
104 unsigned int IOTranslateCacheBits(struct phys_entry
*pp
);
108 #define kIOMaximumMappedIOByteCount (512*1024*1024)
110 static IOMapper
* gIOSystemMapper
= NULL
;
112 static ppnum_t gIOMaximumMappedIOPageCount
= atop_32(kIOMaximumMappedIOByteCount
);
116 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
118 OSDefineMetaClassAndAbstractStructors( IOMemoryDescriptor
, OSObject
)
120 #define super IOMemoryDescriptor
122 OSDefineMetaClassAndStructors(IOGeneralMemoryDescriptor
, IOMemoryDescriptor
)
124 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
126 static IORecursiveLock
* gIOMemoryLock
;
128 #define LOCK IORecursiveLockLock( gIOMemoryLock)
129 #define UNLOCK IORecursiveLockUnlock( gIOMemoryLock)
130 #define SLEEP IORecursiveLockSleep( gIOMemoryLock, (void *)this, THREAD_UNINT)
132 IORecursiveLockWakeup( gIOMemoryLock, (void *)this, /* one-thread */ false)
135 #define DEBG(fmt, args...) { kprintf(fmt, ## args); }
137 #define DEBG(fmt, args...) {}
140 #define IOMD_DEBUG_DMAACTIVE 1
142 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
144 // Some data structures and accessor macros used by the initWithOptions
147 enum ioPLBlockFlags
{
148 kIOPLOnDevice
= 0x00000001,
149 kIOPLExternUPL
= 0x00000002,
152 struct typePersMDData
154 const IOGeneralMemoryDescriptor
*fMD
;
155 ipc_port_t fMemEntry
;
160 vm_address_t fPageInfo
; // Pointer to page list or index into it
161 uint32_t fIOMDOffset
; // The offset of this iopl in descriptor
162 ppnum_t fMappedBase
; // Page number of first page in this iopl
163 unsigned int fPageOffset
; // Offset within first page of iopl
164 unsigned int fFlags
; // Flags
169 uint64_t fPreparationID
;
170 unsigned int fPageCnt
;
172 // align arrays to 8 bytes so following macros work
175 upl_page_info_t fPageList
[];
179 #define getDataP(osd) ((ioGMDData *) (osd)->getBytesNoCopy())
180 #define getIOPLList(d) ((ioPLBlock *) &(d->fPageList[d->fPageCnt]))
181 #define getNumIOPL(osd, d) \
182 (((osd)->getLength() - ((char *) getIOPLList(d) - (char *) d)) / sizeof(ioPLBlock))
183 #define getPageList(d) (&(d->fPageList[0]))
184 #define computeDataSize(p, u) \
185 (sizeof(ioGMDData) + p * sizeof(upl_page_info_t) + u * sizeof(ioPLBlock))
188 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
190 #define next_page(a) ( trunc_page(a) + PAGE_SIZE )
195 kern_return_t
device_data_action(
196 uintptr_t device_handle
,
197 ipc_port_t device_pager
,
198 vm_prot_t protection
,
199 vm_object_offset_t offset
,
202 struct ExpansionData
{
204 unsigned int pagerContig
:1;
205 unsigned int unused
:31;
206 IOMemoryDescriptor
* memory
;
209 ExpansionData
* ref
= (ExpansionData
*) device_handle
;
210 IOMemoryDescriptor
* memDesc
;
213 memDesc
= ref
->memory
;
217 kr
= memDesc
->handleFault( device_pager
, 0, 0,
218 offset
, size
, kIOMapDefaultCache
/*?*/);
228 kern_return_t
device_close(
229 uintptr_t device_handle
)
231 struct ExpansionData
{
233 unsigned int pagerContig
:1;
234 unsigned int unused
:31;
235 IOMemoryDescriptor
* memory
;
237 ExpansionData
* ref
= (ExpansionData
*) device_handle
;
239 IODelete( ref
, ExpansionData
, 1 );
241 return( kIOReturnSuccess
);
245 // Note this inline function uses C++ reference arguments to return values
246 // This means that pointers are not passed and NULLs don't have to be
247 // checked for as a NULL reference is illegal.
249 getAddrLenForInd(user_addr_t
&addr
, IOPhysicalLength
&len
, // Output variables
250 UInt32 type
, IOGeneralMemoryDescriptor::Ranges r
, UInt32 ind
)
252 assert(kIOMemoryTypeUIO
== type
253 || kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
254 || kIOMemoryTypePhysical
== type
|| kIOMemoryTypePhysical64
== type
);
255 if (kIOMemoryTypeUIO
== type
) {
257 uio_getiov((uio_t
) r
.uio
, ind
, &addr
, &us
); len
= us
;
260 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
)) {
261 IOAddressRange cur
= r
.v64
[ind
];
265 #endif /* !__LP64__ */
267 IOVirtualRange cur
= r
.v
[ind
];
273 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
276 IOMemoryDescriptor::withAddress(void * address
,
278 IODirection direction
)
280 return IOMemoryDescriptor::
281 withAddressRange((IOVirtualAddress
) address
, length
, direction
| kIOMemoryAutoPrepare
, kernel_task
);
286 IOMemoryDescriptor::withAddress(IOVirtualAddress address
,
288 IODirection direction
,
291 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
294 if (that
->initWithAddress(address
, length
, direction
, task
))
301 #endif /* !__LP64__ */
304 IOMemoryDescriptor::withPhysicalAddress(
305 IOPhysicalAddress address
,
307 IODirection direction
)
310 return (IOMemoryDescriptor::withAddressRange(address
, length
, direction
, TASK_NULL
));
311 #else /* !__LP64__ */
312 IOGeneralMemoryDescriptor
*self
= new IOGeneralMemoryDescriptor
;
314 && !self
->initWithPhysicalAddress(address
, length
, direction
)) {
320 #endif /* !__LP64__ */
325 IOMemoryDescriptor::withRanges( IOVirtualRange
* ranges
,
327 IODirection direction
,
331 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
334 if (that
->initWithRanges(ranges
, withCount
, direction
, task
, asReference
))
341 #endif /* !__LP64__ */
344 IOMemoryDescriptor::withAddressRange(mach_vm_address_t address
,
345 mach_vm_size_t length
,
346 IOOptionBits options
,
349 IOAddressRange range
= { address
, length
};
350 return (IOMemoryDescriptor::withAddressRanges(&range
, 1, options
, task
));
354 IOMemoryDescriptor::withAddressRanges(IOAddressRange
* ranges
,
356 IOOptionBits options
,
359 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
363 options
|= kIOMemoryTypeVirtual64
;
365 options
|= kIOMemoryTypePhysical64
;
367 if (that
->initWithOptions(ranges
, rangeCount
, 0, task
, options
, /* mapper */ 0))
380 * Create a new IOMemoryDescriptor. The buffer is made up of several
381 * virtual address ranges, from a given task.
383 * Passing the ranges as a reference will avoid an extra allocation.
386 IOMemoryDescriptor::withOptions(void * buffers
,
393 IOGeneralMemoryDescriptor
*self
= new IOGeneralMemoryDescriptor
;
396 && !self
->initWithOptions(buffers
, count
, offset
, task
, opts
, mapper
))
405 bool IOMemoryDescriptor::initWithOptions(void * buffers
,
409 IOOptionBits options
,
417 IOMemoryDescriptor::withPhysicalRanges( IOPhysicalRange
* ranges
,
419 IODirection direction
,
422 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
425 if (that
->initWithPhysicalRanges(ranges
, withCount
, direction
, asReference
))
434 IOMemoryDescriptor::withSubRange(IOMemoryDescriptor
* of
,
437 IODirection direction
)
439 return (IOSubMemoryDescriptor::withSubRange(of
, offset
, length
, direction
| kIOMemoryThreadSafe
));
441 #endif /* !__LP64__ */
444 IOMemoryDescriptor::withPersistentMemoryDescriptor(IOMemoryDescriptor
*originalMD
)
446 IOGeneralMemoryDescriptor
*origGenMD
=
447 OSDynamicCast(IOGeneralMemoryDescriptor
, originalMD
);
450 return IOGeneralMemoryDescriptor::
451 withPersistentMemoryDescriptor(origGenMD
);
457 IOGeneralMemoryDescriptor::withPersistentMemoryDescriptor(IOGeneralMemoryDescriptor
*originalMD
)
459 ipc_port_t sharedMem
= (ipc_port_t
) originalMD
->createNamedEntry();
464 if (sharedMem
== originalMD
->_memEntry
) {
465 originalMD
->retain(); // Add a new reference to ourselves
466 ipc_port_release_send(sharedMem
); // Remove extra send right
470 IOGeneralMemoryDescriptor
* self
= new IOGeneralMemoryDescriptor
;
471 typePersMDData initData
= { originalMD
, sharedMem
};
474 && !self
->initWithOptions(&initData
, 1, 0, 0, kIOMemoryTypePersistentMD
, 0)) {
481 void *IOGeneralMemoryDescriptor::createNamedEntry()
484 ipc_port_t sharedMem
;
486 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
488 user_addr_t range0Addr
;
489 IOByteCount range0Len
;
490 getAddrLenForInd(range0Addr
, range0Len
, type
, _ranges
, 0);
491 range0Addr
= trunc_page_64(range0Addr
);
493 vm_size_t size
= ptoa_32(_pages
);
494 vm_address_t kernelPage
= (vm_address_t
) range0Addr
;
496 vm_map_t theMap
= ((_task
== kernel_task
)
497 && (kIOMemoryBufferPageable
& _flags
))
498 ? IOPageableMapForAddress(kernelPage
)
499 : get_task_map(_task
);
501 memory_object_size_t actualSize
= size
;
502 vm_prot_t prot
= VM_PROT_READ
;
504 if (kIODirectionOut
!= (kIODirectionOutIn
& _flags
))
506 prot
|= VM_PROT_WRITE
;
509 prot
|= MAP_MEM_NAMED_REUSE
;
511 error
= mach_make_memory_entry_64(theMap
,
512 &actualSize
, range0Addr
, prot
, &sharedMem
, (ipc_port_t
) _memEntry
);
514 if (KERN_SUCCESS
== error
) {
515 if (actualSize
== size
) {
519 IOLog("IOGMD::mach_make_memory_entry_64 (%08llx) size (%08llx:%08llx)\n",
520 (UInt64
)range0Addr
, (UInt64
)actualSize
, (UInt64
)size
);
522 ipc_port_release_send( sharedMem
);
526 return MACH_PORT_NULL
;
531 IOGeneralMemoryDescriptor::initWithAddress(void * address
,
532 IOByteCount withLength
,
533 IODirection withDirection
)
535 _singleRange
.v
.address
= (vm_offset_t
) address
;
536 _singleRange
.v
.length
= withLength
;
538 return initWithRanges(&_singleRange
.v
, 1, withDirection
, kernel_task
, true);
542 IOGeneralMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
543 IOByteCount withLength
,
544 IODirection withDirection
,
547 _singleRange
.v
.address
= address
;
548 _singleRange
.v
.length
= withLength
;
550 return initWithRanges(&_singleRange
.v
, 1, withDirection
, withTask
, true);
554 IOGeneralMemoryDescriptor::initWithPhysicalAddress(
555 IOPhysicalAddress address
,
556 IOByteCount withLength
,
557 IODirection withDirection
)
559 _singleRange
.p
.address
= address
;
560 _singleRange
.p
.length
= withLength
;
562 return initWithPhysicalRanges( &_singleRange
.p
, 1, withDirection
, true);
566 IOGeneralMemoryDescriptor::initWithPhysicalRanges(
567 IOPhysicalRange
* ranges
,
569 IODirection direction
,
572 IOOptionBits mdOpts
= direction
| kIOMemoryTypePhysical
;
575 mdOpts
|= kIOMemoryAsReference
;
577 return initWithOptions(ranges
, count
, 0, 0, mdOpts
, /* mapper */ 0);
581 IOGeneralMemoryDescriptor::initWithRanges(
582 IOVirtualRange
* ranges
,
584 IODirection direction
,
588 IOOptionBits mdOpts
= direction
;
591 mdOpts
|= kIOMemoryAsReference
;
594 mdOpts
|= kIOMemoryTypeVirtual
;
596 // Auto-prepare if this is a kernel memory descriptor as very few
597 // clients bother to prepare() kernel memory.
598 // But it was not enforced so what are you going to do?
599 if (task
== kernel_task
)
600 mdOpts
|= kIOMemoryAutoPrepare
;
603 mdOpts
|= kIOMemoryTypePhysical
;
605 return initWithOptions(ranges
, count
, 0, task
, mdOpts
, /* mapper */ 0);
607 #endif /* !__LP64__ */
612 * IOMemoryDescriptor. The buffer is made up of several virtual address ranges,
613 * from a given task, several physical ranges, an UPL from the ubc
614 * system or a uio (may be 64bit) from the BSD subsystem.
616 * Passing the ranges as a reference will avoid an extra allocation.
618 * An IOMemoryDescriptor can be re-used by calling initWithOptions again on an
619 * existing instance -- note this behavior is not commonly supported in other
620 * I/O Kit classes, although it is supported here.
624 IOGeneralMemoryDescriptor::initWithOptions(void * buffers
,
628 IOOptionBits options
,
631 IOOptionBits type
= options
& kIOMemoryTypeMask
;
633 // Grab the original MD's configuation data to initialse the
634 // arguments to this function.
635 if (kIOMemoryTypePersistentMD
== type
) {
637 typePersMDData
*initData
= (typePersMDData
*) buffers
;
638 const IOGeneralMemoryDescriptor
*orig
= initData
->fMD
;
639 ioGMDData
*dataP
= getDataP(orig
->_memoryEntries
);
641 // Only accept persistent memory descriptors with valid dataP data.
642 assert(orig
->_rangesCount
== 1);
643 if ( !(orig
->_flags
& kIOMemoryPersistent
) || !dataP
)
646 _memEntry
= initData
->fMemEntry
; // Grab the new named entry
647 options
= orig
->_flags
| kIOMemoryAsReference
;
648 _singleRange
= orig
->_singleRange
; // Initialise our range
649 buffers
= &_singleRange
;
652 // Now grab the original task and whatever mapper was previously used
654 mapper
= dataP
->fMapper
;
656 // We are ready to go through the original initialisation now
660 case kIOMemoryTypeUIO
:
661 case kIOMemoryTypeVirtual
:
663 case kIOMemoryTypeVirtual64
:
664 #endif /* !__LP64__ */
670 if (vm_map_is_64bit(get_task_map(task
))
671 && (kIOMemoryTypeVirtual
== type
)
672 && ((IOVirtualRange
*) buffers
)->address
)
674 OSReportWithBacktrace("IOMemoryDescriptor: attempt to create 32b virtual in 64b task, use ::withAddressRange()");
677 #endif /* !__LP64__ */
680 case kIOMemoryTypePhysical
: // Neither Physical nor UPL should have a task
682 case kIOMemoryTypePhysical64
:
683 #endif /* !__LP64__ */
684 case kIOMemoryTypeUPL
:
688 return false; /* bad argument */
695 * We can check the _initialized instance variable before having ever set
696 * it to an initial value because I/O Kit guarantees that all our instance
697 * variables are zeroed on an object's allocation.
702 * An existing memory descriptor is being retargeted to point to
703 * somewhere else. Clean up our present state.
705 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
706 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
711 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
713 if (kIOMemoryTypeUIO
== type
)
714 uio_free((uio_t
) _ranges
.v
);
716 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
717 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
718 #endif /* !__LP64__ */
720 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
724 { ipc_port_release_send((ipc_port_t
) _memEntry
); _memEntry
= 0; }
726 _mappings
->flushCollection();
734 // Grab the appropriate mapper
735 if (kIOMemoryMapperNone
& options
)
736 mapper
= 0; // No Mapper
737 else if (mapper
== kIOMapperSystem
) {
738 IOMapper::checkForSystemMapper();
739 gIOSystemMapper
= mapper
= IOMapper::gSystem
;
742 // Temp binary compatibility for kIOMemoryThreadSafe
743 if (kIOMemoryReserved6156215
& options
)
745 options
&= ~kIOMemoryReserved6156215
;
746 options
|= kIOMemoryThreadSafe
;
748 // Remove the dynamic internal use flags from the initial setting
749 options
&= ~(kIOMemoryPreparedReadOnly
);
754 _direction
= (IODirection
) (_flags
& kIOMemoryDirectionMask
);
755 #endif /* !__LP64__ */
757 __iomd_reservedA
= 0;
758 __iomd_reservedB
= 0;
761 if (kIOMemoryThreadSafe
& options
)
764 _prepareLock
= IOLockAlloc();
766 else if (_prepareLock
)
768 IOLockFree(_prepareLock
);
772 if (kIOMemoryTypeUPL
== type
) {
775 unsigned int dataSize
= computeDataSize(/* pages */ 0, /* upls */ 1);
777 if (!_memoryEntries
) {
778 _memoryEntries
= OSData::withCapacity(dataSize
);
782 else if (!_memoryEntries
->initWithCapacity(dataSize
))
785 _memoryEntries
->appendBytes(0, sizeof(ioGMDData
));
786 dataP
= getDataP(_memoryEntries
);
787 dataP
->fMapper
= mapper
;
790 // _wireCount++; // UPLs start out life wired
793 _pages
+= atop_32(offset
+ count
+ PAGE_MASK
) - atop_32(offset
);
796 iopl
.fIOPL
= (upl_t
) buffers
;
797 upl_page_info_t
*pageList
= UPL_GET_INTERNAL_PAGE_LIST(iopl
.fIOPL
);
799 if (upl_get_size(iopl
.fIOPL
) < (count
+ offset
))
800 panic("short external upl");
802 // Set the flag kIOPLOnDevice convieniently equal to 1
803 iopl
.fFlags
= pageList
->device
| kIOPLExternUPL
;
804 iopl
.fIOMDOffset
= 0;
806 _highestPage
= upl_get_highest_page(iopl
.fIOPL
);
808 if (!pageList
->device
) {
809 // Pre-compute the offset into the UPL's page list
810 pageList
= &pageList
[atop_32(offset
)];
813 iopl
.fMappedBase
= mapper
->iovmAlloc(_pages
);
814 mapper
->iovmInsert(iopl
.fMappedBase
, 0, pageList
, _pages
);
817 iopl
.fMappedBase
= 0;
820 iopl
.fMappedBase
= 0;
821 iopl
.fPageInfo
= (vm_address_t
) pageList
;
822 iopl
.fPageOffset
= offset
;
824 _memoryEntries
->appendBytes(&iopl
, sizeof(iopl
));
827 // kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO
828 // kIOMemoryTypePhysical | kIOMemoryTypePhysical64
830 // Initialize the memory descriptor
831 if (options
& kIOMemoryAsReference
) {
833 _rangesIsAllocated
= false;
834 #endif /* !__LP64__ */
836 // Hack assignment to get the buffer arg into _ranges.
837 // I'd prefer to do _ranges = (Ranges) buffers, but that doesn't
839 // This also initialises the uio & physical ranges.
840 _ranges
.v
= (IOVirtualRange
*) buffers
;
844 _rangesIsAllocated
= true;
845 #endif /* !__LP64__ */
848 case kIOMemoryTypeUIO
:
849 _ranges
.v
= (IOVirtualRange
*) uio_duplicate((uio_t
) buffers
);
853 case kIOMemoryTypeVirtual64
:
854 case kIOMemoryTypePhysical64
:
856 && (((IOAddressRange
*) buffers
)->address
+ ((IOAddressRange
*) buffers
)->length
) <= 0x100000000ULL
) {
857 if (kIOMemoryTypeVirtual64
== type
)
858 type
= kIOMemoryTypeVirtual
;
860 type
= kIOMemoryTypePhysical
;
861 _flags
= (_flags
& ~kIOMemoryTypeMask
) | type
| kIOMemoryAsReference
;
862 _rangesIsAllocated
= false;
863 _ranges
.v
= &_singleRange
.v
;
864 _singleRange
.v
.address
= ((IOAddressRange
*) buffers
)->address
;
865 _singleRange
.v
.length
= ((IOAddressRange
*) buffers
)->length
;
868 _ranges
.v64
= IONew(IOAddressRange
, count
);
871 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOAddressRange
));
873 #endif /* !__LP64__ */
874 case kIOMemoryTypeVirtual
:
875 case kIOMemoryTypePhysical
:
877 _flags
|= kIOMemoryAsReference
;
879 _rangesIsAllocated
= false;
880 #endif /* !__LP64__ */
881 _ranges
.v
= &_singleRange
.v
;
883 _ranges
.v
= IONew(IOVirtualRange
, count
);
887 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOVirtualRange
));
892 // Find starting address within the vector of ranges
893 Ranges vec
= _ranges
;
896 for (unsigned ind
= 0; ind
< count
; ind
++) {
898 IOPhysicalLength len
;
900 // addr & len are returned by this function
901 getAddrLenForInd(addr
, len
, type
, vec
, ind
);
902 pages
+= (atop_64(addr
+ len
+ PAGE_MASK
) - atop_64(addr
));
904 assert(len
>= length
); // Check for 32 bit wrap around
907 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
909 ppnum_t highPage
= atop_64(addr
+ len
- 1);
910 if (highPage
> _highestPage
)
911 _highestPage
= highPage
;
916 _rangesCount
= count
;
918 // Auto-prepare memory at creation time.
919 // Implied completion when descriptor is free-ed
920 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
921 _wireCount
++; // Physical MDs are, by definition, wired
922 else { /* kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO */
924 unsigned dataSize
= computeDataSize(_pages
, /* upls */ count
* 2);
926 if (!_memoryEntries
) {
927 _memoryEntries
= OSData::withCapacity(dataSize
);
931 else if (!_memoryEntries
->initWithCapacity(dataSize
))
934 _memoryEntries
->appendBytes(0, sizeof(ioGMDData
));
935 dataP
= getDataP(_memoryEntries
);
936 dataP
->fMapper
= mapper
;
937 dataP
->fPageCnt
= _pages
;
939 if ( (kIOMemoryPersistent
& _flags
) && !_memEntry
)
940 _memEntry
= createNamedEntry();
942 if ((_flags
& kIOMemoryAutoPrepare
)
943 && prepare() != kIOReturnSuccess
)
956 void IOGeneralMemoryDescriptor::free()
958 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
963 reserved
->memory
= 0;
967 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
973 _memoryEntries
->release();
975 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
977 if (kIOMemoryTypeUIO
== type
)
978 uio_free((uio_t
) _ranges
.v
);
980 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
981 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
982 #endif /* !__LP64__ */
984 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
989 if (reserved
&& reserved
->devicePager
)
990 device_pager_deallocate( (memory_object_t
) reserved
->devicePager
);
992 // memEntry holds a ref on the device pager which owns reserved
993 // (ExpansionData) so no reserved access after this point
995 ipc_port_release_send( (ipc_port_t
) _memEntry
);
998 IOLockFree(_prepareLock
);
1004 void IOGeneralMemoryDescriptor::unmapFromKernel()
1006 panic("IOGMD::unmapFromKernel deprecated");
1009 void IOGeneralMemoryDescriptor::mapIntoKernel(unsigned rangeIndex
)
1011 panic("IOGMD::mapIntoKernel deprecated");
1013 #endif /* !__LP64__ */
1018 * Get the direction of the transfer.
1020 IODirection
IOMemoryDescriptor::getDirection() const
1025 #endif /* !__LP64__ */
1026 return (IODirection
) (_flags
& kIOMemoryDirectionMask
);
1032 * Get the length of the transfer (over all ranges).
1034 IOByteCount
IOMemoryDescriptor::getLength() const
1039 void IOMemoryDescriptor::setTag( IOOptionBits tag
)
1044 IOOptionBits
IOMemoryDescriptor::getTag( void )
1050 // @@@ gvdl: who is using this API? Seems like a wierd thing to implement.
1052 IOMemoryDescriptor::getSourceSegment( IOByteCount offset
, IOByteCount
* length
)
1054 addr64_t physAddr
= 0;
1056 if( prepare() == kIOReturnSuccess
) {
1057 physAddr
= getPhysicalSegment64( offset
, length
);
1061 return( (IOPhysicalAddress
) physAddr
); // truncated but only page offset is used
1063 #endif /* !__LP64__ */
1065 IOByteCount
IOMemoryDescriptor::readBytes
1066 (IOByteCount offset
, void *bytes
, IOByteCount length
)
1068 addr64_t dstAddr
= CAST_DOWN(addr64_t
, bytes
);
1069 IOByteCount remaining
;
1071 // Assert that this entire I/O is withing the available range
1072 assert(offset
< _length
);
1073 assert(offset
+ length
<= _length
);
1074 if (offset
>= _length
) {
1078 if (kIOMemoryThreadSafe
& _flags
)
1081 remaining
= length
= min(length
, _length
- offset
);
1082 while (remaining
) { // (process another target segment?)
1086 srcAddr64
= getPhysicalSegment(offset
, &srcLen
, kIOMemoryMapperNone
);
1090 // Clip segment length to remaining
1091 if (srcLen
> remaining
)
1094 copypv(srcAddr64
, dstAddr
, srcLen
,
1095 cppvPsrc
| cppvNoRefSrc
| cppvFsnk
| cppvKmap
);
1099 remaining
-= srcLen
;
1102 if (kIOMemoryThreadSafe
& _flags
)
1107 return length
- remaining
;
1110 IOByteCount
IOMemoryDescriptor::writeBytes
1111 (IOByteCount offset
, const void *bytes
, IOByteCount length
)
1113 addr64_t srcAddr
= CAST_DOWN(addr64_t
, bytes
);
1114 IOByteCount remaining
;
1116 // Assert that this entire I/O is withing the available range
1117 assert(offset
< _length
);
1118 assert(offset
+ length
<= _length
);
1120 assert( !(kIOMemoryPreparedReadOnly
& _flags
) );
1122 if ( (kIOMemoryPreparedReadOnly
& _flags
) || offset
>= _length
) {
1126 if (kIOMemoryThreadSafe
& _flags
)
1129 remaining
= length
= min(length
, _length
- offset
);
1130 while (remaining
) { // (process another target segment?)
1134 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1138 // Clip segment length to remaining
1139 if (dstLen
> remaining
)
1142 copypv(srcAddr
, (addr64_t
) dstAddr64
, dstLen
,
1143 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
1147 remaining
-= dstLen
;
1150 if (kIOMemoryThreadSafe
& _flags
)
1155 return length
- remaining
;
1158 // osfmk/device/iokit_rpc.c
1159 extern "C" unsigned int IODefaultCacheBits(addr64_t pa
);
1162 void IOGeneralMemoryDescriptor::setPosition(IOByteCount position
)
1164 panic("IOGMD::setPosition deprecated");
1166 #endif /* !__LP64__ */
1168 static volatile SInt64 gIOMDPreparationID
__attribute__((aligned(8))) = (1ULL << 32);
1171 IOGeneralMemoryDescriptor::getPreparationID( void )
1176 return (kIOPreparationIDUnprepared
);
1178 if (_flags
& (kIOMemoryTypePhysical
| kIOMemoryTypePhysical64
))
1179 return (kIOPreparationIDAlwaysPrepared
);
1181 if (!_memoryEntries
|| !(dataP
= getDataP(_memoryEntries
)))
1182 return (kIOPreparationIDUnprepared
);
1184 if (kIOPreparationIDUnprepared
== dataP
->fPreparationID
)
1186 #if defined(__ppc__ )
1187 dataP
->fPreparationID
= gIOMDPreparationID
++;
1189 dataP
->fPreparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1192 return (dataP
->fPreparationID
);
1196 IOMemoryDescriptor::getPreparationID( void )
1198 return (kIOPreparationIDUnsupported
);
1201 IOReturn
IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1203 if (kIOMDGetCharacteristics
== op
) {
1205 if (dataSize
< sizeof(IOMDDMACharacteristics
))
1206 return kIOReturnUnderrun
;
1208 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
1209 data
->fLength
= _length
;
1210 data
->fSGCount
= _rangesCount
;
1211 data
->fPages
= _pages
;
1212 data
->fDirection
= getDirection();
1214 data
->fIsPrepared
= false;
1216 data
->fIsPrepared
= true;
1217 data
->fHighestPage
= _highestPage
;
1218 if (_memoryEntries
) {
1219 ioGMDData
*gmdData
= getDataP(_memoryEntries
);
1220 ioPLBlock
*ioplList
= getIOPLList(gmdData
);
1221 UInt count
= getNumIOPL(_memoryEntries
, gmdData
);
1223 data
->fIsMapped
= (gmdData
->fMapper
&& _pages
&& (count
> 0)
1224 && ioplList
[0].fMappedBase
);
1226 data
->fPageAlign
= (ioplList
[0].fPageOffset
& PAGE_MASK
) | ~PAGE_MASK
;
1229 data
->fIsMapped
= false;
1232 return kIOReturnSuccess
;
1234 #if IOMD_DEBUG_DMAACTIVE
1235 } else if (kIOMDSetDMAActive
== op
) {
1236 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
1237 OSIncrementAtomic(&md
->__iomd_reservedA
);
1238 } else if (kIOMDSetDMAInactive
== op
) {
1239 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
1240 if (md
->__iomd_reservedA
)
1241 OSDecrementAtomic(&md
->__iomd_reservedA
);
1243 panic("kIOMDSetDMAInactive");
1244 #endif /* IOMD_DEBUG_DMAACTIVE */
1246 } else if (!(kIOMDWalkSegments
& op
))
1247 return kIOReturnBadArgument
;
1249 // Get the next segment
1250 struct InternalState
{
1251 IOMDDMAWalkSegmentArgs fIO
;
1257 // Find the next segment
1258 if (dataSize
< sizeof(*isP
))
1259 return kIOReturnUnderrun
;
1261 isP
= (InternalState
*) vData
;
1262 UInt offset
= isP
->fIO
.fOffset
;
1263 bool mapped
= isP
->fIO
.fMapped
;
1265 if (offset
>= _length
)
1266 return (offset
== _length
)? kIOReturnOverrun
: kIOReturnInternalError
;
1268 // Validate the previous offset
1269 UInt ind
, off2Ind
= isP
->fOffset2Index
;
1270 if ((kIOMDFirstSegment
!= op
)
1272 && (offset
== isP
->fNextOffset
|| off2Ind
<= offset
))
1275 ind
= off2Ind
= 0; // Start from beginning
1279 if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
) {
1281 // Physical address based memory descriptor
1282 const IOPhysicalRange
*physP
= (IOPhysicalRange
*) &_ranges
.p
[0];
1284 // Find the range after the one that contains the offset
1286 for (len
= 0; off2Ind
<= offset
; ind
++) {
1287 len
= physP
[ind
].length
;
1291 // Calculate length within range and starting address
1292 length
= off2Ind
- offset
;
1293 address
= physP
[ind
- 1].address
+ len
- length
;
1295 // see how far we can coalesce ranges
1296 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
1297 len
= physP
[ind
].length
;
1303 // correct contiguous check overshoot
1308 else if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
) {
1310 // Physical address based memory descriptor
1311 const IOAddressRange
*physP
= (IOAddressRange
*) &_ranges
.v64
[0];
1313 // Find the range after the one that contains the offset
1315 for (len
= 0; off2Ind
<= offset
; ind
++) {
1316 len
= physP
[ind
].length
;
1320 // Calculate length within range and starting address
1321 length
= off2Ind
- offset
;
1322 address
= physP
[ind
- 1].address
+ len
- length
;
1324 // see how far we can coalesce ranges
1325 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
1326 len
= physP
[ind
].length
;
1332 // correct contiguous check overshoot
1336 #endif /* !__LP64__ */
1339 panic("IOGMD: not wired for the IODMACommand");
1341 assert(_memoryEntries
);
1343 ioGMDData
* dataP
= getDataP(_memoryEntries
);
1344 const ioPLBlock
*ioplList
= getIOPLList(dataP
);
1345 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
1346 upl_page_info_t
*pageList
= getPageList(dataP
);
1348 assert(numIOPLs
> 0);
1350 // Scan through iopl info blocks looking for block containing offset
1351 while (ind
< numIOPLs
&& offset
>= ioplList
[ind
].fIOMDOffset
)
1354 // Go back to actual range as search goes past it
1355 ioPLBlock ioplInfo
= ioplList
[ind
- 1];
1356 off2Ind
= ioplInfo
.fIOMDOffset
;
1359 length
= ioplList
[ind
].fIOMDOffset
;
1362 length
-= offset
; // Remainder within iopl
1364 // Subtract offset till this iopl in total list
1367 // If a mapped address is requested and this is a pre-mapped IOPL
1368 // then just need to compute an offset relative to the mapped base.
1369 if (mapped
&& ioplInfo
.fMappedBase
) {
1370 offset
+= (ioplInfo
.fPageOffset
& PAGE_MASK
);
1371 address
= ptoa_64(ioplInfo
.fMappedBase
) + offset
;
1372 continue; // Done leave do/while(false) now
1375 // The offset is rebased into the current iopl.
1376 // Now add the iopl 1st page offset.
1377 offset
+= ioplInfo
.fPageOffset
;
1379 // For external UPLs the fPageInfo field points directly to
1380 // the upl's upl_page_info_t array.
1381 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
1382 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
1384 pageList
= &pageList
[ioplInfo
.fPageInfo
];
1386 // Check for direct device non-paged memory
1387 if ( ioplInfo
.fFlags
& kIOPLOnDevice
) {
1388 address
= ptoa_64(pageList
->phys_addr
) + offset
;
1389 continue; // Done leave do/while(false) now
1392 // Now we need compute the index into the pageList
1393 UInt pageInd
= atop_32(offset
);
1394 offset
&= PAGE_MASK
;
1396 // Compute the starting address of this segment
1397 IOPhysicalAddress pageAddr
= pageList
[pageInd
].phys_addr
;
1399 panic("!pageList phys_addr");
1402 address
= ptoa_64(pageAddr
) + offset
;
1404 // length is currently set to the length of the remainider of the iopl.
1405 // We need to check that the remainder of the iopl is contiguous.
1406 // This is indicated by pageList[ind].phys_addr being sequential.
1407 IOByteCount contigLength
= PAGE_SIZE
- offset
;
1408 while (contigLength
< length
1409 && ++pageAddr
== pageList
[++pageInd
].phys_addr
)
1411 contigLength
+= PAGE_SIZE
;
1414 if (contigLength
< length
)
1415 length
= contigLength
;
1423 // Update return values and state
1424 isP
->fIO
.fIOVMAddr
= address
;
1425 isP
->fIO
.fLength
= length
;
1427 isP
->fOffset2Index
= off2Ind
;
1428 isP
->fNextOffset
= isP
->fIO
.fOffset
+ length
;
1430 return kIOReturnSuccess
;
1434 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
1437 addr64_t address
= 0;
1438 IOByteCount length
= 0;
1439 IOMapper
* mapper
= gIOSystemMapper
;
1440 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1442 if (lengthOfSegment
)
1443 *lengthOfSegment
= 0;
1445 if (offset
>= _length
)
1448 // IOMemoryDescriptor::doMap() cannot use getPhysicalSegment() to obtain the page offset, since it must
1449 // support the unwired memory case in IOGeneralMemoryDescriptor, and hibernate_write_image() cannot use
1450 // map()->getVirtualAddress() to obtain the kernel pointer, since it must prevent the memory allocation
1451 // due to IOMemoryMap, so _kIOMemorySourceSegment is a necessary evil until all of this gets cleaned up
1453 if ((options
& _kIOMemorySourceSegment
) && (kIOMemoryTypeUPL
!= type
))
1455 unsigned rangesIndex
= 0;
1456 Ranges vec
= _ranges
;
1459 // Find starting address within the vector of ranges
1461 getAddrLenForInd(addr
, length
, type
, vec
, rangesIndex
);
1462 if (offset
< length
)
1464 offset
-= length
; // (make offset relative)
1468 // Now that we have the starting range,
1469 // lets find the last contiguous range
1473 for ( ++rangesIndex
; rangesIndex
< _rangesCount
; rangesIndex
++ ) {
1474 user_addr_t newAddr
;
1475 IOPhysicalLength newLen
;
1477 getAddrLenForInd(newAddr
, newLen
, type
, vec
, rangesIndex
);
1478 if (addr
+ length
!= newAddr
)
1483 address
= (IOPhysicalAddress
) addr
; // Truncate address to 32bit
1487 IOMDDMAWalkSegmentState _state
;
1488 IOMDDMAWalkSegmentArgs
* state
= (IOMDDMAWalkSegmentArgs
*) &_state
;
1490 state
->fOffset
= offset
;
1491 state
->fLength
= _length
- offset
;
1492 state
->fMapped
= (0 == (options
& kIOMemoryMapperNone
));
1494 ret
= dmaCommandOperation(kIOMDFirstSegment
, _state
, sizeof(_state
));
1496 if ((kIOReturnSuccess
!= ret
) && (kIOReturnOverrun
!= ret
))
1497 DEBG("getPhysicalSegment dmaCommandOperation(%lx), %p, offset %qx, addr %qx, len %qx\n",
1498 ret
, this, state
->fOffset
,
1499 state
->fIOVMAddr
, state
->fLength
);
1500 if (kIOReturnSuccess
== ret
)
1502 address
= state
->fIOVMAddr
;
1503 length
= state
->fLength
;
1506 // dmaCommandOperation() does not distinguish between "mapped" and "unmapped" physical memory, even
1507 // with fMapped set correctly, so we must handle the transformation here until this gets cleaned up
1509 if (mapper
&& ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
)))
1511 if ((options
& kIOMemoryMapperNone
) && !(_flags
& kIOMemoryMapperNone
))
1513 addr64_t origAddr
= address
;
1514 IOByteCount origLen
= length
;
1516 address
= mapper
->mapAddr(origAddr
);
1517 length
= page_size
- (address
& (page_size
- 1));
1518 while ((length
< origLen
)
1519 && ((address
+ length
) == mapper
->mapAddr(origAddr
+ length
)))
1520 length
+= page_size
;
1521 if (length
> origLen
)
1525 else if (!(options
& kIOMemoryMapperNone
) && (_flags
& kIOMemoryMapperNone
))
1527 panic("getPhysicalSegment not mapped for I/O");
1529 #endif /* __LP64__ */
1536 if (lengthOfSegment
)
1537 *lengthOfSegment
= length
;
1544 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
1546 addr64_t address
= 0;
1548 if (options
& _kIOMemorySourceSegment
)
1550 address
= getSourceSegment(offset
, lengthOfSegment
);
1552 else if (options
& kIOMemoryMapperNone
)
1554 address
= getPhysicalSegment64(offset
, lengthOfSegment
);
1558 address
= getPhysicalSegment(offset
, lengthOfSegment
);
1565 IOGeneralMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1567 return (getPhysicalSegment(offset
, lengthOfSegment
, kIOMemoryMapperNone
));
1571 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1573 addr64_t address
= 0;
1574 IOByteCount length
= 0;
1576 address
= getPhysicalSegment(offset
, lengthOfSegment
, 0);
1578 if (lengthOfSegment
)
1579 length
= *lengthOfSegment
;
1581 if ((address
+ length
) > 0x100000000ULL
)
1583 panic("getPhysicalSegment() out of 32b range 0x%qx, len 0x%lx, class %s",
1584 address
, (long) length
, (getMetaClass())->getClassName());
1587 return ((IOPhysicalAddress
) address
);
1591 IOMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1593 IOPhysicalAddress phys32
;
1596 IOMapper
* mapper
= 0;
1598 phys32
= getPhysicalSegment(offset
, lengthOfSegment
);
1602 if (gIOSystemMapper
)
1603 mapper
= gIOSystemMapper
;
1607 IOByteCount origLen
;
1609 phys64
= mapper
->mapAddr(phys32
);
1610 origLen
= *lengthOfSegment
;
1611 length
= page_size
- (phys64
& (page_size
- 1));
1612 while ((length
< origLen
)
1613 && ((phys64
+ length
) == mapper
->mapAddr(phys32
+ length
)))
1614 length
+= page_size
;
1615 if (length
> origLen
)
1618 *lengthOfSegment
= length
;
1621 phys64
= (addr64_t
) phys32
;
1627 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1629 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, 0));
1633 IOGeneralMemoryDescriptor::getSourceSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1635 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, _kIOMemorySourceSegment
));
1638 void * IOGeneralMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
1639 IOByteCount
* lengthOfSegment
)
1641 if (_task
== kernel_task
)
1642 return (void *) getSourceSegment(offset
, lengthOfSegment
);
1644 panic("IOGMD::getVirtualSegment deprecated");
1648 #endif /* !__LP64__ */
1651 IOMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1653 if (kIOMDGetCharacteristics
== op
) {
1654 if (dataSize
< sizeof(IOMDDMACharacteristics
))
1655 return kIOReturnUnderrun
;
1657 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
1658 data
->fLength
= getLength();
1660 data
->fDirection
= getDirection();
1661 if (IOMapper::gSystem
)
1662 data
->fIsMapped
= true;
1663 data
->fIsPrepared
= true; // Assume prepared - fails safe
1665 else if (kIOMDWalkSegments
& op
) {
1666 if (dataSize
< sizeof(IOMDDMAWalkSegmentArgs
))
1667 return kIOReturnUnderrun
;
1669 IOMDDMAWalkSegmentArgs
*data
= (IOMDDMAWalkSegmentArgs
*) vData
;
1670 IOByteCount offset
= (IOByteCount
) data
->fOffset
;
1672 IOPhysicalLength length
;
1673 IOMemoryDescriptor
*ncmd
= const_cast<IOMemoryDescriptor
*>(this);
1674 if (data
->fMapped
&& IOMapper::gSystem
)
1675 data
->fIOVMAddr
= ncmd
->getPhysicalSegment(offset
, &length
);
1677 data
->fIOVMAddr
= ncmd
->getPhysicalSegment(offset
, &length
, kIOMemoryMapperNone
);
1678 data
->fLength
= length
;
1681 return kIOReturnBadArgument
;
1683 return kIOReturnSuccess
;
1687 purgeableControlBits(IOOptionBits newState
, vm_purgable_t
* control
, int * state
)
1689 IOReturn err
= kIOReturnSuccess
;
1691 *control
= VM_PURGABLE_SET_STATE
;
1694 case kIOMemoryPurgeableKeepCurrent
:
1695 *control
= VM_PURGABLE_GET_STATE
;
1698 case kIOMemoryPurgeableNonVolatile
:
1699 *state
= VM_PURGABLE_NONVOLATILE
;
1701 case kIOMemoryPurgeableVolatile
:
1702 *state
= VM_PURGABLE_VOLATILE
;
1704 case kIOMemoryPurgeableEmpty
:
1705 *state
= VM_PURGABLE_EMPTY
;
1708 err
= kIOReturnBadArgument
;
1715 purgeableStateBits(int * state
)
1717 IOReturn err
= kIOReturnSuccess
;
1721 case VM_PURGABLE_NONVOLATILE
:
1722 *state
= kIOMemoryPurgeableNonVolatile
;
1724 case VM_PURGABLE_VOLATILE
:
1725 *state
= kIOMemoryPurgeableVolatile
;
1727 case VM_PURGABLE_EMPTY
:
1728 *state
= kIOMemoryPurgeableEmpty
;
1731 *state
= kIOMemoryPurgeableNonVolatile
;
1732 err
= kIOReturnNotReady
;
1739 IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState
,
1740 IOOptionBits
* oldState
)
1742 IOReturn err
= kIOReturnSuccess
;
1743 vm_purgable_t control
;
1748 err
= super::setPurgeable(newState
, oldState
);
1752 if (kIOMemoryThreadSafe
& _flags
)
1756 // Find the appropriate vm_map for the given task
1758 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
1760 err
= kIOReturnNotReady
;
1764 curMap
= get_task_map(_task
);
1766 // can only do one range
1767 Ranges vec
= _ranges
;
1768 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1771 getAddrLenForInd(addr
, len
, type
, vec
, 0);
1773 err
= purgeableControlBits(newState
, &control
, &state
);
1774 if (kIOReturnSuccess
!= err
)
1776 err
= mach_vm_purgable_control(curMap
, addr
, control
, &state
);
1779 if (kIOReturnSuccess
== err
)
1781 err
= purgeableStateBits(&state
);
1787 if (kIOMemoryThreadSafe
& _flags
)
1793 IOReturn
IOMemoryDescriptor::setPurgeable( IOOptionBits newState
,
1794 IOOptionBits
* oldState
)
1796 IOReturn err
= kIOReturnSuccess
;
1797 vm_purgable_t control
;
1800 if (kIOMemoryThreadSafe
& _flags
)
1807 err
= kIOReturnNotReady
;
1810 err
= purgeableControlBits(newState
, &control
, &state
);
1811 if (kIOReturnSuccess
!= err
)
1813 err
= mach_memory_entry_purgable_control((ipc_port_t
) _memEntry
, control
, &state
);
1816 if (kIOReturnSuccess
== err
)
1818 err
= purgeableStateBits(&state
);
1825 if (kIOMemoryThreadSafe
& _flags
)
1831 extern "C" void dcache_incoherent_io_flush64(addr64_t pa
, unsigned int count
);
1832 extern "C" void dcache_incoherent_io_store64(addr64_t pa
, unsigned int count
);
1834 static void SetEncryptOp(addr64_t pa
, unsigned int count
)
1838 page
= atop_64(round_page_64(pa
));
1839 end
= atop_64(trunc_page_64(pa
+ count
));
1840 for (; page
< end
; page
++)
1842 pmap_clear_noencrypt(page
);
1846 static void ClearEncryptOp(addr64_t pa
, unsigned int count
)
1850 page
= atop_64(round_page_64(pa
));
1851 end
= atop_64(trunc_page_64(pa
+ count
));
1852 for (; page
< end
; page
++)
1854 pmap_set_noencrypt(page
);
1858 IOReturn
IOMemoryDescriptor::performOperation( IOOptionBits options
,
1859 IOByteCount offset
, IOByteCount length
)
1861 IOByteCount remaining
;
1862 void (*func
)(addr64_t pa
, unsigned int count
) = 0;
1866 case kIOMemoryIncoherentIOFlush
:
1867 func
= &dcache_incoherent_io_flush64
;
1869 case kIOMemoryIncoherentIOStore
:
1870 func
= &dcache_incoherent_io_store64
;
1873 case kIOMemorySetEncrypted
:
1874 func
= &SetEncryptOp
;
1876 case kIOMemoryClearEncrypted
:
1877 func
= &ClearEncryptOp
;
1882 return (kIOReturnUnsupported
);
1884 if (kIOMemoryThreadSafe
& _flags
)
1887 remaining
= length
= min(length
, getLength() - offset
);
1889 // (process another target segment?)
1894 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1898 // Clip segment length to remaining
1899 if (dstLen
> remaining
)
1902 (*func
)(dstAddr64
, dstLen
);
1905 remaining
-= dstLen
;
1908 if (kIOMemoryThreadSafe
& _flags
)
1911 return (remaining
? kIOReturnUnderrun
: kIOReturnSuccess
);
1914 #if defined(__ppc__) || defined(__arm__)
1915 extern vm_offset_t static_memory_end
;
1916 #define io_kernel_static_end static_memory_end
1918 extern vm_offset_t first_avail
;
1919 #define io_kernel_static_end first_avail
1922 static kern_return_t
1923 io_get_kernel_static_upl(
1926 vm_size_t
*upl_size
,
1928 upl_page_info_array_t page_list
,
1929 unsigned int *count
,
1930 ppnum_t
*highest_page
)
1932 unsigned int pageCount
, page
;
1934 ppnum_t highestPage
= 0;
1936 pageCount
= atop_32(*upl_size
);
1937 if (pageCount
> *count
)
1942 for (page
= 0; page
< pageCount
; page
++)
1944 phys
= pmap_find_phys(kernel_pmap
, ((addr64_t
)offset
) + ptoa_64(page
));
1947 page_list
[page
].phys_addr
= phys
;
1948 page_list
[page
].pageout
= 0;
1949 page_list
[page
].absent
= 0;
1950 page_list
[page
].dirty
= 0;
1951 page_list
[page
].precious
= 0;
1952 page_list
[page
].device
= 0;
1953 if (phys
> highestPage
)
1957 *highest_page
= highestPage
;
1959 return ((page
>= pageCount
) ? kIOReturnSuccess
: kIOReturnVMError
);
1962 IOReturn
IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection
)
1964 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1965 IOReturn error
= kIOReturnCannotWire
;
1967 ppnum_t mapBase
= 0;
1969 ipc_port_t sharedMem
= (ipc_port_t
) _memEntry
;
1971 assert(!_wireCount
);
1972 assert(kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
);
1974 if (_pages
>= gIOMaximumMappedIOPageCount
)
1975 return kIOReturnNoResources
;
1977 dataP
= getDataP(_memoryEntries
);
1978 mapper
= dataP
->fMapper
;
1979 if (mapper
&& _pages
)
1980 mapBase
= mapper
->iovmAlloc(_pages
);
1982 // Note that appendBytes(NULL) zeros the data up to the
1984 _memoryEntries
->appendBytes(0, dataP
->fPageCnt
* sizeof(upl_page_info_t
));
1985 dataP
= 0; // May no longer be valid so lets not get tempted.
1987 if (forDirection
== kIODirectionNone
)
1988 forDirection
= getDirection();
1990 int uplFlags
; // This Mem Desc's default flags for upl creation
1991 switch (kIODirectionOutIn
& forDirection
)
1993 case kIODirectionOut
:
1994 // Pages do not need to be marked as dirty on commit
1995 uplFlags
= UPL_COPYOUT_FROM
;
1996 _flags
|= kIOMemoryPreparedReadOnly
;
1999 case kIODirectionIn
:
2001 uplFlags
= 0; // i.e. ~UPL_COPYOUT_FROM
2004 uplFlags
|= UPL_SET_IO_WIRE
| UPL_SET_LITE
;
2006 #ifdef UPL_NEED_32BIT_ADDR
2007 if (kIODirectionPrepareToPhys32
& forDirection
)
2008 uplFlags
|= UPL_NEED_32BIT_ADDR
;
2011 // Find the appropriate vm_map for the given task
2013 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
2016 { curMap
= get_task_map(_task
); }
2018 // Iterate over the vector of virtual ranges
2019 Ranges vec
= _ranges
;
2020 unsigned int pageIndex
= 0;
2021 IOByteCount mdOffset
= 0;
2022 ppnum_t highestPage
= 0;
2023 for (UInt range
= 0; range
< _rangesCount
; range
++) {
2025 user_addr_t startPage
;
2026 IOByteCount numBytes
;
2027 ppnum_t highPage
= 0;
2029 // Get the startPage address and length of vec[range]
2030 getAddrLenForInd(startPage
, numBytes
, type
, vec
, range
);
2031 iopl
.fPageOffset
= startPage
& PAGE_MASK
;
2032 numBytes
+= iopl
.fPageOffset
;
2033 startPage
= trunc_page_64(startPage
);
2036 iopl
.fMappedBase
= mapBase
+ pageIndex
;
2038 iopl
.fMappedBase
= 0;
2040 // Iterate over the current range, creating UPLs
2042 dataP
= getDataP(_memoryEntries
);
2043 vm_address_t kernelStart
= (vm_address_t
) startPage
;
2047 else if (!sharedMem
) {
2048 assert(_task
== kernel_task
);
2049 theMap
= IOPageableMapForAddress(kernelStart
);
2054 upl_page_info_array_t pageInfo
= getPageList(dataP
);
2055 int ioplFlags
= uplFlags
;
2056 upl_page_list_ptr_t baseInfo
= &pageInfo
[pageIndex
];
2058 vm_size_t ioplSize
= round_page(numBytes
);
2059 unsigned int numPageInfo
= atop_32(ioplSize
);
2061 if (theMap
== kernel_map
&& kernelStart
< io_kernel_static_end
) {
2062 error
= io_get_kernel_static_upl(theMap
,
2070 else if (sharedMem
) {
2071 error
= memory_object_iopl_request(sharedMem
,
2081 error
= vm_map_create_upl(theMap
,
2083 (upl_size_t
*)&ioplSize
,
2091 if (error
!= KERN_SUCCESS
)
2095 highPage
= upl_get_highest_page(iopl
.fIOPL
);
2096 if (highPage
> highestPage
)
2097 highestPage
= highPage
;
2099 error
= kIOReturnCannotWire
;
2101 if (baseInfo
->device
) {
2103 iopl
.fFlags
= kIOPLOnDevice
;
2104 // Don't translate device memory at all
2105 if (mapper
&& mapBase
) {
2106 mapper
->iovmFree(mapBase
, _pages
);
2108 iopl
.fMappedBase
= 0;
2114 mapper
->iovmInsert(mapBase
, pageIndex
,
2115 baseInfo
, numPageInfo
);
2118 iopl
.fIOMDOffset
= mdOffset
;
2119 iopl
.fPageInfo
= pageIndex
;
2121 if ((_flags
& kIOMemoryAutoPrepare
) && iopl
.fIOPL
)
2123 upl_commit(iopl
.fIOPL
, 0, 0);
2124 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
, sizeof(ioGMDData
)); // == 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
);
2277 (void) _memoryEntries
->initWithBytes(dataP
, sizeof(ioGMDData
)); // == setLength()
2279 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
2284 IOLockUnlock(_prepareLock
);
2286 return kIOReturnSuccess
;
2289 IOReturn
IOGeneralMemoryDescriptor::doMap(
2290 vm_map_t __addressMap
,
2291 IOVirtualAddress
* __address
,
2292 IOOptionBits options
,
2293 IOByteCount __offset
,
2294 IOByteCount __length
)
2298 if (!(kIOMap64Bit
& options
)) panic("IOGeneralMemoryDescriptor::doMap !64bit");
2299 #endif /* !__LP64__ */
2301 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
2302 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
2303 mach_vm_size_t length
= mapping
->fLength
;
2305 kern_return_t kr
= kIOReturnVMError
;
2306 ipc_port_t sharedMem
= (ipc_port_t
) _memEntry
;
2308 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2309 Ranges vec
= _ranges
;
2311 user_addr_t range0Addr
= 0;
2312 IOByteCount range0Len
= 0;
2315 getAddrLenForInd(range0Addr
, range0Len
, type
, vec
, 0);
2317 // mapping source == dest? (could be much better)
2319 && (mapping
->fAddressMap
== get_task_map(_task
)) && (options
& kIOMapAnywhere
)
2320 && (1 == _rangesCount
) && (0 == offset
)
2321 && range0Addr
&& (length
<= range0Len
) )
2323 mapping
->fAddress
= range0Addr
;
2324 mapping
->fOptions
|= kIOMapStatic
;
2326 return( kIOReturnSuccess
);
2329 if( 0 == sharedMem
) {
2331 vm_size_t size
= ptoa_32(_pages
);
2335 memory_object_size_t actualSize
= size
;
2336 vm_prot_t prot
= VM_PROT_READ
;
2337 if (!(kIOMapReadOnly
& options
))
2338 prot
|= VM_PROT_WRITE
;
2339 else if (kIOMapDefaultCache
!= (options
& kIOMapCacheMask
))
2340 prot
|= VM_PROT_WRITE
;
2342 kr
= mach_make_memory_entry_64(get_task_map(_task
),
2343 &actualSize
, range0Addr
,
2347 if( (KERN_SUCCESS
== kr
) && (actualSize
!= round_page(size
)))
2349 // map will cross vm objects
2351 IOLog("mach_make_memory_entry_64 (%08llx) size (%08llx:%08llx)\n",
2352 range0Addr
, (UInt64
)actualSize
, (UInt64
)size
);
2354 kr
= kIOReturnVMError
;
2355 ipc_port_release_send( sharedMem
);
2356 sharedMem
= MACH_PORT_NULL
;
2358 mach_vm_address_t address
;
2359 mach_vm_size_t pageOffset
= (range0Addr
& PAGE_MASK
);
2361 address
= trunc_page_64(mapping
->fAddress
);
2362 if ((options
& kIOMapAnywhere
) || ((mapping
->fAddress
- address
) == pageOffset
))
2364 kr
= IOMemoryDescriptorMapCopy(mapping
->fAddressMap
,
2365 get_task_map(_task
), range0Addr
,
2367 offset
, &address
, round_page_64(length
+ pageOffset
));
2368 if (kr
== KERN_SUCCESS
)
2369 mapping
->fAddress
= address
+ pageOffset
;
2371 mapping
->fAddress
= NULL
;
2376 { // _task == 0, must be physical
2378 memory_object_t pager
;
2379 unsigned int flags
= 0;
2381 IOPhysicalLength segLen
;
2383 pa
= getPhysicalSegment( offset
, &segLen
, kIOMemoryMapperNone
);
2386 reserved
= IONew( ExpansionData
, 1 );
2390 reserved
->pagerContig
= (1 == _rangesCount
);
2391 reserved
->memory
= this;
2393 /*What cache mode do we need*/
2394 switch(options
& kIOMapCacheMask
) {
2396 case kIOMapDefaultCache
:
2398 flags
= IODefaultCacheBits(pa
);
2399 if (DEVICE_PAGER_CACHE_INHIB
& flags
)
2401 if (DEVICE_PAGER_GUARDED
& flags
)
2402 mapping
->fOptions
|= kIOMapInhibitCache
;
2404 mapping
->fOptions
|= kIOMapWriteCombineCache
;
2406 else if (DEVICE_PAGER_WRITE_THROUGH
& flags
)
2407 mapping
->fOptions
|= kIOMapWriteThruCache
;
2409 mapping
->fOptions
|= kIOMapCopybackCache
;
2412 case kIOMapInhibitCache
:
2413 flags
= DEVICE_PAGER_CACHE_INHIB
|
2414 DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
2417 case kIOMapWriteThruCache
:
2418 flags
= DEVICE_PAGER_WRITE_THROUGH
|
2419 DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
2422 case kIOMapCopybackCache
:
2423 flags
= DEVICE_PAGER_COHERENT
;
2426 case kIOMapWriteCombineCache
:
2427 flags
= DEVICE_PAGER_CACHE_INHIB
|
2428 DEVICE_PAGER_COHERENT
;
2432 flags
|= reserved
->pagerContig
? DEVICE_PAGER_CONTIGUOUS
: 0;
2434 pager
= device_pager_setup( (memory_object_t
) 0, (uintptr_t) reserved
,
2439 kr
= mach_memory_object_memory_entry_64( (host_t
) 1, false /*internal*/,
2440 size
, VM_PROT_READ
| VM_PROT_WRITE
, pager
, &sharedMem
);
2442 assert( KERN_SUCCESS
== kr
);
2443 if( KERN_SUCCESS
!= kr
)
2445 device_pager_deallocate( pager
);
2446 pager
= MACH_PORT_NULL
;
2447 sharedMem
= MACH_PORT_NULL
;
2450 if( pager
&& sharedMem
)
2451 reserved
->devicePager
= pager
;
2453 IODelete( reserved
, ExpansionData
, 1 );
2459 _memEntry
= (void *) sharedMem
;
2466 result
= super::doMap( __addressMap
, __address
,
2467 options
, __offset
, __length
);
2472 IOReturn
IOGeneralMemoryDescriptor::doUnmap(
2473 vm_map_t addressMap
,
2474 IOVirtualAddress __address
,
2475 IOByteCount __length
)
2477 return (super::doUnmap(addressMap
, __address
, __length
));
2480 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2483 #define super OSObject
2485 OSDefineMetaClassAndStructors( IOMemoryMap
, OSObject
)
2487 OSMetaClassDefineReservedUnused(IOMemoryMap
, 0);
2488 OSMetaClassDefineReservedUnused(IOMemoryMap
, 1);
2489 OSMetaClassDefineReservedUnused(IOMemoryMap
, 2);
2490 OSMetaClassDefineReservedUnused(IOMemoryMap
, 3);
2491 OSMetaClassDefineReservedUnused(IOMemoryMap
, 4);
2492 OSMetaClassDefineReservedUnused(IOMemoryMap
, 5);
2493 OSMetaClassDefineReservedUnused(IOMemoryMap
, 6);
2494 OSMetaClassDefineReservedUnused(IOMemoryMap
, 7);
2496 /* ex-inline function implementation */
2497 IOPhysicalAddress
IOMemoryMap::getPhysicalAddress()
2498 { return( getPhysicalSegment( 0, 0 )); }
2500 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2502 bool IOMemoryMap::init(
2504 mach_vm_address_t toAddress
,
2505 IOOptionBits _options
,
2506 mach_vm_size_t _offset
,
2507 mach_vm_size_t _length
)
2515 fAddressMap
= get_task_map(intoTask
);
2518 vm_map_reference(fAddressMap
);
2520 fAddressTask
= intoTask
;
2521 fOptions
= _options
;
2524 fAddress
= toAddress
;
2529 bool IOMemoryMap::setMemoryDescriptor(IOMemoryDescriptor
* _memory
, mach_vm_size_t _offset
)
2536 if( (_offset
+ fLength
) > _memory
->getLength())
2544 if (fMemory
!= _memory
)
2545 fMemory
->removeMapping(this);
2553 struct IOMemoryDescriptorMapAllocRef
2555 ipc_port_t sharedMem
;
2557 mach_vm_offset_t src_address
;
2558 mach_vm_address_t mapped
;
2559 mach_vm_size_t size
;
2560 mach_vm_size_t sourceOffset
;
2561 IOOptionBits options
;
2564 static kern_return_t
IOMemoryDescriptorMapAlloc(vm_map_t map
, void * _ref
)
2566 IOMemoryDescriptorMapAllocRef
* ref
= (IOMemoryDescriptorMapAllocRef
*)_ref
;
2572 vm_prot_t prot
= VM_PROT_READ
2573 | ((ref
->options
& kIOMapReadOnly
) ? 0 : VM_PROT_WRITE
);
2575 // VM system requires write access to change cache mode
2576 if (kIOMapDefaultCache
!= (ref
->options
& kIOMapCacheMask
))
2577 prot
|= VM_PROT_WRITE
;
2579 // set memory entry cache
2580 vm_prot_t memEntryCacheMode
= prot
| MAP_MEM_ONLY
;
2581 switch (ref
->options
& kIOMapCacheMask
)
2583 case kIOMapInhibitCache
:
2584 SET_MAP_MEM(MAP_MEM_IO
, memEntryCacheMode
);
2587 case kIOMapWriteThruCache
:
2588 SET_MAP_MEM(MAP_MEM_WTHRU
, memEntryCacheMode
);
2591 case kIOMapWriteCombineCache
:
2592 SET_MAP_MEM(MAP_MEM_WCOMB
, memEntryCacheMode
);
2595 case kIOMapCopybackCache
:
2596 SET_MAP_MEM(MAP_MEM_COPYBACK
, memEntryCacheMode
);
2599 case kIOMapDefaultCache
:
2601 SET_MAP_MEM(MAP_MEM_NOOP
, memEntryCacheMode
);
2605 vm_size_t unused
= 0;
2607 err
= mach_make_memory_entry( NULL
/*unused*/, &unused
, 0 /*unused*/,
2608 memEntryCacheMode
, NULL
, ref
->sharedMem
);
2609 if (KERN_SUCCESS
!= err
)
2610 IOLog("MAP_MEM_ONLY failed %d\n", err
);
2612 err
= mach_vm_map( map
,
2614 ref
->size
, 0 /* mask */,
2615 (( ref
->options
& kIOMapAnywhere
) ? VM_FLAGS_ANYWHERE
: VM_FLAGS_FIXED
)
2616 | VM_MAKE_TAG(VM_MEMORY_IOKIT
),
2617 ref
->sharedMem
, ref
->sourceOffset
,
2623 if( KERN_SUCCESS
!= err
) {
2628 else if (ref
->src_map
)
2630 vm_prot_t cur_prot
, max_prot
;
2631 err
= mach_vm_remap(map
, &ref
->mapped
, ref
->size
, PAGE_MASK
,
2632 (ref
->options
& kIOMapAnywhere
) ? TRUE
: FALSE
,
2633 ref
->src_map
, ref
->src_address
,
2638 if (KERN_SUCCESS
== err
)
2640 if ((!(VM_PROT_READ
& cur_prot
))
2641 || (!(kIOMapReadOnly
& ref
->options
) && !(VM_PROT_WRITE
& cur_prot
)))
2643 mach_vm_deallocate(map
, ref
->mapped
, ref
->size
);
2644 err
= KERN_PROTECTION_FAILURE
;
2647 if (KERN_SUCCESS
!= err
)
2652 err
= mach_vm_allocate( map
, &ref
->mapped
, ref
->size
,
2653 ((ref
->options
& kIOMapAnywhere
) ? VM_FLAGS_ANYWHERE
: VM_FLAGS_FIXED
)
2654 | VM_MAKE_TAG(VM_MEMORY_IOKIT
) );
2655 if( KERN_SUCCESS
!= err
) {
2659 // we have to make sure that these guys don't get copied if we fork.
2660 err
= vm_inherit( map
, ref
->mapped
, ref
->size
, VM_INHERIT_NONE
);
2661 assert( KERN_SUCCESS
== err
);
2670 IOMemoryDescriptorMapMemEntry(vm_map_t map
, ipc_port_t entry
, IOOptionBits options
, bool pageable
,
2671 mach_vm_size_t offset
,
2672 mach_vm_address_t
* address
, mach_vm_size_t length
)
2675 IOMemoryDescriptorMapAllocRef ref
;
2677 ref
.sharedMem
= entry
;
2679 ref
.sharedMem
= entry
;
2680 ref
.sourceOffset
= trunc_page_64(offset
);
2681 ref
.options
= options
;
2684 if (options
& kIOMapAnywhere
)
2685 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
2688 ref
.mapped
= *address
;
2690 if( ref
.sharedMem
&& (map
== kernel_map
) && pageable
)
2691 err
= IOIteratePageableMaps( ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
2693 err
= IOMemoryDescriptorMapAlloc( map
, &ref
);
2695 *address
= ref
.mapped
;
2700 IOMemoryDescriptorMapCopy(vm_map_t map
,
2702 mach_vm_offset_t src_address
,
2703 IOOptionBits options
,
2704 mach_vm_size_t offset
,
2705 mach_vm_address_t
* address
, mach_vm_size_t length
)
2708 IOMemoryDescriptorMapAllocRef ref
;
2710 ref
.sharedMem
= NULL
;
2711 ref
.src_map
= src_map
;
2712 ref
.src_address
= src_address
;
2713 ref
.sourceOffset
= trunc_page_64(offset
);
2714 ref
.options
= options
;
2717 if (options
& kIOMapAnywhere
)
2718 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
2721 ref
.mapped
= *address
;
2723 if (map
== kernel_map
)
2724 err
= IOIteratePageableMaps(ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
2726 err
= IOMemoryDescriptorMapAlloc(map
, &ref
);
2728 *address
= ref
.mapped
;
2732 IOReturn
IOMemoryDescriptor::doMap(
2733 vm_map_t __addressMap
,
2734 IOVirtualAddress
* __address
,
2735 IOOptionBits options
,
2736 IOByteCount __offset
,
2737 IOByteCount __length
)
2740 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::doMap !64bit");
2741 #endif /* !__LP64__ */
2743 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
2744 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
2745 mach_vm_size_t length
= mapping
->fLength
;
2747 IOReturn err
= kIOReturnSuccess
;
2748 memory_object_t pager
;
2749 mach_vm_size_t pageOffset
;
2750 IOPhysicalAddress sourceAddr
;
2751 unsigned int lock_count
;
2755 sourceAddr
= getPhysicalSegment( offset
, NULL
, _kIOMemorySourceSegment
);
2756 pageOffset
= sourceAddr
- trunc_page( sourceAddr
);
2759 pager
= (memory_object_t
) reserved
->devicePager
;
2761 pager
= MACH_PORT_NULL
;
2763 if ((kIOMapReference
|kIOMapUnique
) == ((kIOMapReference
|kIOMapUnique
) & options
))
2771 err
= kIOReturnNotReadable
;
2775 size
= round_page(mapping
->fLength
+ pageOffset
);
2776 flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
2777 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
2779 if (KERN_SUCCESS
!= memory_object_iopl_request((ipc_port_t
) _memEntry
, 0, &size
, &redirUPL2
,
2784 for (lock_count
= 0;
2785 IORecursiveLockHaveLock(gIOMemoryLock
);
2789 err
= upl_transpose(redirUPL2
, mapping
->fRedirUPL
);
2796 if (kIOReturnSuccess
!= err
)
2798 IOLog("upl_transpose(%x)\n", err
);
2799 err
= kIOReturnSuccess
;
2804 upl_commit(redirUPL2
, NULL
, 0);
2805 upl_deallocate(redirUPL2
);
2809 // swap the memEntries since they now refer to different vm_objects
2810 void * me
= _memEntry
;
2811 _memEntry
= mapping
->fMemory
->_memEntry
;
2812 mapping
->fMemory
->_memEntry
= me
;
2815 err
= handleFault( reserved
->devicePager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
2819 mach_vm_address_t address
;
2821 if (!(options
& kIOMapAnywhere
))
2823 address
= trunc_page_64(mapping
->fAddress
);
2824 if( (mapping
->fAddress
- address
) != pageOffset
)
2826 err
= kIOReturnVMError
;
2831 err
= IOMemoryDescriptorMapMemEntry(mapping
->fAddressMap
, (ipc_port_t
) _memEntry
,
2832 options
, (kIOMemoryBufferPageable
& _flags
),
2833 offset
, &address
, round_page_64(length
+ pageOffset
));
2834 if( err
!= KERN_SUCCESS
)
2837 if (!_memEntry
|| pager
)
2839 err
= handleFault( pager
, mapping
->fAddressMap
, address
, offset
, length
, options
);
2840 if (err
!= KERN_SUCCESS
)
2841 doUnmap( mapping
->fAddressMap
, (IOVirtualAddress
) mapping
, 0 );
2845 if (kIOLogMapping
& gIOKitDebug
)
2846 IOLog("mapping(%x) desc %p @ %lx, map %p, address %qx, offset %qx, length %qx\n",
2847 err
, this, sourceAddr
, mapping
, address
, offset
, length
);
2850 if (err
== KERN_SUCCESS
)
2851 mapping
->fAddress
= address
+ pageOffset
;
2853 mapping
->fAddress
= NULL
;
2861 IOReturn
IOMemoryDescriptor::handleFault(
2863 vm_map_t addressMap
,
2864 mach_vm_address_t address
,
2865 mach_vm_size_t sourceOffset
,
2866 mach_vm_size_t length
,
2867 IOOptionBits options
)
2869 IOReturn err
= kIOReturnSuccess
;
2870 memory_object_t pager
= (memory_object_t
) _pager
;
2871 mach_vm_size_t size
;
2872 mach_vm_size_t bytes
;
2873 mach_vm_size_t page
;
2874 mach_vm_size_t pageOffset
;
2875 mach_vm_size_t pagerOffset
;
2876 IOPhysicalLength segLen
;
2881 if( kIOMemoryRedirected
& _flags
)
2884 IOLog("sleep mem redirect %p, %qx\n", this, sourceOffset
);
2888 } while( kIOMemoryRedirected
& _flags
);
2891 return( kIOReturnSuccess
);
2894 physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
);
2896 pageOffset
= physAddr
- trunc_page_64( physAddr
);
2897 pagerOffset
= sourceOffset
;
2899 size
= length
+ pageOffset
;
2900 physAddr
-= pageOffset
;
2902 segLen
+= pageOffset
;
2906 // in the middle of the loop only map whole pages
2907 if( segLen
>= bytes
)
2909 else if( segLen
!= trunc_page( segLen
))
2910 err
= kIOReturnVMError
;
2911 if( physAddr
!= trunc_page_64( physAddr
))
2912 err
= kIOReturnBadArgument
;
2913 if (kIOReturnSuccess
!= err
)
2917 if( kIOLogMapping
& gIOKitDebug
)
2918 IOLog("IOMemoryMap::map(%p) 0x%qx->0x%qx:0x%qx\n",
2919 addressMap
, address
+ pageOffset
, physAddr
+ pageOffset
,
2920 segLen
- pageOffset
);
2925 if( reserved
&& reserved
->pagerContig
) {
2926 IOPhysicalLength allLen
;
2929 allPhys
= getPhysicalSegment( 0, &allLen
, kIOMemoryMapperNone
);
2931 err
= device_pager_populate_object( pager
, 0, atop_64(allPhys
), round_page(allLen
) );
2937 (page
< segLen
) && (KERN_SUCCESS
== err
);
2940 err
= device_pager_populate_object(pager
, pagerOffset
,
2941 (ppnum_t
)(atop_64(physAddr
+ page
)), page_size
);
2942 pagerOffset
+= page_size
;
2945 assert( KERN_SUCCESS
== err
);
2950 // This call to vm_fault causes an early pmap level resolution
2951 // of the mappings created above for kernel mappings, since
2952 // faulting in later can't take place from interrupt level.
2954 /* *** Temporary Workaround *** */
2956 if ((addressMap
== kernel_map
) && !(kIOMemoryRedirected
& _flags
))
2958 vm_fault(addressMap
,
2959 (vm_map_offset_t
)address
,
2960 VM_PROT_READ
|VM_PROT_WRITE
,
2961 FALSE
, THREAD_UNINT
, NULL
,
2962 (vm_map_offset_t
)0);
2965 /* *** Temporary Workaround *** */
2968 sourceOffset
+= segLen
- pageOffset
;
2974 while (bytes
&& (physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
)));
2977 err
= kIOReturnBadArgument
;
2982 IOReturn
IOMemoryDescriptor::doUnmap(
2983 vm_map_t addressMap
,
2984 IOVirtualAddress __address
,
2985 IOByteCount __length
)
2988 mach_vm_address_t address
;
2989 mach_vm_size_t length
;
2993 address
= __address
;
2998 addressMap
= ((IOMemoryMap
*) __address
)->fAddressMap
;
2999 address
= ((IOMemoryMap
*) __address
)->fAddress
;
3000 length
= ((IOMemoryMap
*) __address
)->fLength
;
3003 if ((addressMap
== kernel_map
)
3004 && ((kIOMemoryBufferPageable
& _flags
) || !_memEntry
))
3005 addressMap
= IOPageableMapForAddress( address
);
3008 if( kIOLogMapping
& gIOKitDebug
)
3009 IOLog("IOMemoryDescriptor::doUnmap map %p, 0x%qx:0x%qx\n",
3010 addressMap
, address
, length
);
3013 err
= mach_vm_deallocate( addressMap
, address
, length
);
3018 IOReturn
IOMemoryDescriptor::redirect( task_t safeTask
, bool doRedirect
)
3020 IOReturn err
= kIOReturnSuccess
;
3021 IOMemoryMap
* mapping
= 0;
3027 _flags
|= kIOMemoryRedirected
;
3029 _flags
&= ~kIOMemoryRedirected
;
3032 if( (iter
= OSCollectionIterator::withCollection( _mappings
))) {
3033 while( (mapping
= (IOMemoryMap
*) iter
->getNextObject()))
3034 mapping
->redirect( safeTask
, doRedirect
);
3048 // temporary binary compatibility
3049 IOSubMemoryDescriptor
* subMem
;
3050 if( (subMem
= OSDynamicCast( IOSubMemoryDescriptor
, this)))
3051 err
= subMem
->redirect( safeTask
, doRedirect
);
3053 err
= kIOReturnSuccess
;
3054 #endif /* !__LP64__ */
3059 IOReturn
IOMemoryMap::redirect( task_t safeTask
, bool doRedirect
)
3061 IOReturn err
= kIOReturnSuccess
;
3064 // err = ((IOMemoryMap *)superMap)->redirect( safeTask, doRedirect );
3076 if ((!safeTask
|| (get_task_map(safeTask
) != fAddressMap
))
3077 && (0 == (fOptions
& kIOMapStatic
)))
3079 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3080 err
= kIOReturnSuccess
;
3082 IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect
, this, fAddress
, fLength
, fAddressMap
);
3085 else if (kIOMapWriteCombineCache
== (fOptions
& kIOMapCacheMask
))
3087 IOOptionBits newMode
;
3088 newMode
= (fOptions
& ~kIOMapCacheMask
) | (doRedirect
? kIOMapInhibitCache
: kIOMapWriteCombineCache
);
3089 IOProtectCacheMode(fAddressMap
, fAddress
, fLength
, newMode
);
3096 if ((((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3097 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3099 && (doRedirect
!= (0 != (fMemory
->_flags
& kIOMemoryRedirected
))))
3100 fMemory
->redirect(safeTask
, doRedirect
);
3105 IOReturn
IOMemoryMap::unmap( void )
3111 if( fAddress
&& fAddressMap
&& (0 == fSuperMap
) && fMemory
3112 && (0 == (fOptions
& kIOMapStatic
))) {
3114 err
= fMemory
->doUnmap(fAddressMap
, (IOVirtualAddress
) this, 0);
3117 err
= kIOReturnSuccess
;
3121 vm_map_deallocate(fAddressMap
);
3132 void IOMemoryMap::taskDied( void )
3135 if (fUserClientUnmap
)
3138 vm_map_deallocate(fAddressMap
);
3146 IOReturn
IOMemoryMap::userClientUnmap( void )
3148 fUserClientUnmap
= true;
3149 return (kIOReturnSuccess
);
3152 // Overload the release mechanism. All mappings must be a member
3153 // of a memory descriptors _mappings set. This means that we
3154 // always have 2 references on a mapping. When either of these mappings
3155 // are released we need to free ourselves.
3156 void IOMemoryMap::taggedRelease(const void *tag
) const
3159 super::taggedRelease(tag
, 2);
3163 void IOMemoryMap::free()
3170 fMemory
->removeMapping(this);
3175 if (fOwner
&& (fOwner
!= fMemory
))
3178 fOwner
->removeMapping(this);
3183 fSuperMap
->release();
3186 upl_commit(fRedirUPL
, NULL
, 0);
3187 upl_deallocate(fRedirUPL
);
3193 IOByteCount
IOMemoryMap::getLength()
3198 IOVirtualAddress
IOMemoryMap::getVirtualAddress()
3202 fSuperMap
->getVirtualAddress();
3203 else if (fAddressMap
3204 && vm_map_is_64bit(fAddressMap
)
3205 && (sizeof(IOVirtualAddress
) < 8))
3207 OSReportWithBacktrace("IOMemoryMap::getVirtualAddress(0x%qx) called on 64b map; use ::getAddress()", fAddress
);
3209 #endif /* !__LP64__ */
3215 mach_vm_address_t
IOMemoryMap::getAddress()
3220 mach_vm_size_t
IOMemoryMap::getSize()
3224 #endif /* !__LP64__ */
3227 task_t
IOMemoryMap::getAddressTask()
3230 return( fSuperMap
->getAddressTask());
3232 return( fAddressTask
);
3235 IOOptionBits
IOMemoryMap::getMapOptions()
3240 IOMemoryDescriptor
* IOMemoryMap::getMemoryDescriptor()
3245 IOMemoryMap
* IOMemoryMap::copyCompatible(
3246 IOMemoryMap
* newMapping
)
3248 task_t task
= newMapping
->getAddressTask();
3249 mach_vm_address_t toAddress
= newMapping
->fAddress
;
3250 IOOptionBits _options
= newMapping
->fOptions
;
3251 mach_vm_size_t _offset
= newMapping
->fOffset
;
3252 mach_vm_size_t _length
= newMapping
->fLength
;
3254 if( (!task
) || (!fAddressMap
) || (fAddressMap
!= get_task_map(task
)))
3256 if( (fOptions
^ _options
) & kIOMapReadOnly
)
3258 if( (kIOMapDefaultCache
!= (_options
& kIOMapCacheMask
))
3259 && ((fOptions
^ _options
) & kIOMapCacheMask
))
3262 if( (0 == (_options
& kIOMapAnywhere
)) && (fAddress
!= toAddress
))
3265 if( _offset
< fOffset
)
3270 if( (_offset
+ _length
) > fLength
)
3274 if( (fLength
== _length
) && (!_offset
))
3276 newMapping
->release();
3281 newMapping
->fSuperMap
= this;
3282 newMapping
->fOffset
= _offset
;
3283 newMapping
->fAddress
= fAddress
+ _offset
;
3286 return( newMapping
);
3291 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
, IOOptionBits _options
)
3292 #else /* !__LP64__ */
3293 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
)
3294 #endif /* !__LP64__ */
3296 IOPhysicalAddress address
;
3300 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
, _options
);
3301 #else /* !__LP64__ */
3302 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
);
3303 #endif /* !__LP64__ */
3309 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3312 #define super OSObject
3314 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3316 void IOMemoryDescriptor::initialize( void )
3318 if( 0 == gIOMemoryLock
)
3319 gIOMemoryLock
= IORecursiveLockAlloc();
3321 IORegistryEntry::getRegistryRoot()->setProperty(kIOMaximumMappedIOByteCountKey
,
3322 ptoa_64(gIOMaximumMappedIOPageCount
), 64);
3323 gIOLastPage
= IOGetLastPageNumber();
3326 void IOMemoryDescriptor::free( void )
3329 _mappings
->release();
3334 IOMemoryMap
* IOMemoryDescriptor::setMapping(
3336 IOVirtualAddress mapAddress
,
3337 IOOptionBits options
)
3339 return (createMappingInTask( intoTask
, mapAddress
,
3340 options
| kIOMapStatic
,
3344 IOMemoryMap
* IOMemoryDescriptor::map(
3345 IOOptionBits options
)
3347 return (createMappingInTask( kernel_task
, 0,
3348 options
| kIOMapAnywhere
,
3353 IOMemoryMap
* IOMemoryDescriptor::map(
3355 IOVirtualAddress atAddress
,
3356 IOOptionBits options
,
3358 IOByteCount length
)
3360 if ((!(kIOMapAnywhere
& options
)) && vm_map_is_64bit(get_task_map(intoTask
)))
3362 OSReportWithBacktrace("IOMemoryDescriptor::map() in 64b task, use ::createMappingInTask()");
3366 return (createMappingInTask(intoTask
, atAddress
,
3367 options
, offset
, length
));
3369 #endif /* !__LP64__ */
3371 IOMemoryMap
* IOMemoryDescriptor::createMappingInTask(
3373 mach_vm_address_t atAddress
,
3374 IOOptionBits options
,
3375 mach_vm_size_t offset
,
3376 mach_vm_size_t length
)
3378 IOMemoryMap
* result
;
3379 IOMemoryMap
* mapping
;
3382 length
= getLength();
3384 mapping
= new IOMemoryMap
;
3387 && !mapping
->init( intoTask
, atAddress
,
3388 options
, offset
, length
)) {
3394 result
= makeMapping(this, intoTask
, (IOVirtualAddress
) mapping
, options
| kIOMap64Bit
, 0, 0);
3400 IOLog("createMappingInTask failed desc %p, addr %qx, options %lx, offset %qx, length %qx\n",
3401 this, atAddress
, options
, offset
, length
);
3407 #ifndef __LP64__ // there is only a 64 bit version for LP64
3408 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
3409 IOOptionBits options
,
3412 return (redirect(newBackingMemory
, options
, (mach_vm_size_t
)offset
));
3416 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
3417 IOOptionBits options
,
3418 mach_vm_size_t offset
)
3420 IOReturn err
= kIOReturnSuccess
;
3421 IOMemoryDescriptor
* physMem
= 0;
3425 if (fAddress
&& fAddressMap
) do
3427 if (((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3428 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3436 vm_size_t size
= round_page(fLength
);
3437 int flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3438 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
3439 if (KERN_SUCCESS
!= memory_object_iopl_request((ipc_port_t
) fMemory
->_memEntry
, 0, &size
, &fRedirUPL
,
3446 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3448 physMem
->redirect(0, true);
3452 if (newBackingMemory
)
3454 if (newBackingMemory
!= fMemory
)
3457 if (this != newBackingMemory
->makeMapping(newBackingMemory
, fAddressTask
, (IOVirtualAddress
) this,
3458 options
| kIOMapUnique
| kIOMapReference
| kIOMap64Bit
,
3460 err
= kIOReturnError
;
3464 upl_commit(fRedirUPL
, NULL
, 0);
3465 upl_deallocate(fRedirUPL
);
3468 if (false && physMem
)
3469 physMem
->redirect(0, false);
3482 IOMemoryMap
* IOMemoryDescriptor::makeMapping(
3483 IOMemoryDescriptor
* owner
,
3485 IOVirtualAddress __address
,
3486 IOOptionBits options
,
3487 IOByteCount __offset
,
3488 IOByteCount __length
)
3491 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::makeMapping !64bit");
3492 #endif /* !__LP64__ */
3494 IOMemoryDescriptor
* mapDesc
= 0;
3495 IOMemoryMap
* result
= 0;
3498 IOMemoryMap
* mapping
= (IOMemoryMap
*) __address
;
3499 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3500 mach_vm_size_t length
= mapping
->fLength
;
3502 mapping
->fOffset
= offset
;
3508 if (kIOMapStatic
& options
)
3511 addMapping(mapping
);
3512 mapping
->setMemoryDescriptor(this, 0);
3516 if (kIOMapUnique
& options
)
3518 IOPhysicalAddress phys
;
3519 IOByteCount physLen
;
3521 // if (owner != this) continue;
3523 if (((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3524 || ((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3526 phys
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
3527 if (!phys
|| (physLen
< length
))
3530 mapDesc
= IOMemoryDescriptor::withAddressRange(
3531 phys
, length
, getDirection() | kIOMemoryMapperNone
, NULL
);
3535 mapping
->fOffset
= offset
;
3540 // look for a compatible existing mapping
3541 if( (iter
= OSCollectionIterator::withCollection(_mappings
)))
3543 IOMemoryMap
* lookMapping
;
3544 while ((lookMapping
= (IOMemoryMap
*) iter
->getNextObject()))
3546 if ((result
= lookMapping
->copyCompatible(mapping
)))
3549 result
->setMemoryDescriptor(this, offset
);
3555 if (result
|| (options
& kIOMapReference
))
3565 kr
= mapDesc
->doMap( 0, (IOVirtualAddress
*) &mapping
, options
, 0, 0 );
3566 if (kIOReturnSuccess
== kr
)
3569 mapDesc
->addMapping(result
);
3570 result
->setMemoryDescriptor(mapDesc
, offset
);
3588 void IOMemoryDescriptor::addMapping(
3589 IOMemoryMap
* mapping
)
3594 _mappings
= OSSet::withCapacity(1);
3596 _mappings
->setObject( mapping
);
3600 void IOMemoryDescriptor::removeMapping(
3601 IOMemoryMap
* mapping
)
3604 _mappings
->removeObject( mapping
);
3608 // obsolete initializers
3609 // - initWithOptions is the designated initializer
3611 IOMemoryDescriptor::initWithAddress(void * address
,
3613 IODirection direction
)
3619 IOMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
3621 IODirection direction
,
3628 IOMemoryDescriptor::initWithPhysicalAddress(
3629 IOPhysicalAddress address
,
3631 IODirection direction
)
3637 IOMemoryDescriptor::initWithRanges(
3638 IOVirtualRange
* ranges
,
3640 IODirection direction
,
3648 IOMemoryDescriptor::initWithPhysicalRanges( IOPhysicalRange
* ranges
,
3650 IODirection direction
,
3656 void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
3657 IOByteCount
* lengthOfSegment
)
3661 #endif /* !__LP64__ */
3663 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3665 bool IOGeneralMemoryDescriptor::serialize(OSSerialize
* s
) const
3667 OSSymbol
const *keys
[2];
3668 OSObject
*values
[2];
3670 user_addr_t address
;
3673 unsigned int index
, nRanges
;
3676 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3678 if (s
== NULL
) return false;
3679 if (s
->previouslySerialized(this)) return true;
3681 // Pretend we are an array.
3682 if (!s
->addXMLStartTag(this, "array")) return false;
3684 nRanges
= _rangesCount
;
3685 vcopy
= (SerData
*) IOMalloc(sizeof(SerData
) * nRanges
);
3686 if (vcopy
== 0) return false;
3688 keys
[0] = OSSymbol::withCString("address");
3689 keys
[1] = OSSymbol::withCString("length");
3692 values
[0] = values
[1] = 0;
3694 // From this point on we can go to bail.
3696 // Copy the volatile data so we don't have to allocate memory
3697 // while the lock is held.
3699 if (nRanges
== _rangesCount
) {
3700 Ranges vec
= _ranges
;
3701 for (index
= 0; index
< nRanges
; index
++) {
3702 user_addr_t addr
; IOByteCount len
;
3703 getAddrLenForInd(addr
, len
, type
, vec
, index
);
3704 vcopy
[index
].address
= addr
;
3705 vcopy
[index
].length
= len
;
3708 // The descriptor changed out from under us. Give up.
3715 for (index
= 0; index
< nRanges
; index
++)
3717 user_addr_t addr
= vcopy
[index
].address
;
3718 IOByteCount len
= (IOByteCount
) vcopy
[index
].length
;
3720 OSNumber::withNumber(addr
, (((UInt64
) addr
) >> 32)? 64 : 32);
3721 if (values
[0] == 0) {
3725 values
[1] = OSNumber::withNumber(len
, sizeof(len
) * 8);
3726 if (values
[1] == 0) {
3730 OSDictionary
*dict
= OSDictionary::withObjects((const OSObject
**)values
, (const OSSymbol
**)keys
, 2);
3735 values
[0]->release();
3736 values
[1]->release();
3737 values
[0] = values
[1] = 0;
3739 result
= dict
->serialize(s
);
3745 result
= s
->addXMLEndTag("array");
3749 values
[0]->release();
3751 values
[1]->release();
3757 IOFree(vcopy
, sizeof(SerData
) * nRanges
);
3761 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3763 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 0);
3765 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 1);
3766 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 2);
3767 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 3);
3768 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 4);
3769 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 5);
3770 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 6);
3771 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 7);
3772 #else /* !__LP64__ */
3773 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 1);
3774 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 2);
3775 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 3);
3776 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 4);
3777 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 5);
3778 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 6);
3779 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 7);
3780 #endif /* !__LP64__ */
3781 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 8);
3782 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 9);
3783 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 10);
3784 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 11);
3785 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 12);
3786 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 13);
3787 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 14);
3788 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 15);
3790 /* ex-inline function implementation */
3792 IOMemoryDescriptor::getPhysicalAddress()
3793 { return( getPhysicalSegment( 0, 0 )); }