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"
53 #include "IOCopyMapper.h"
55 #include <libkern/c++/OSContainers.h>
56 #include <libkern/c++/OSDictionary.h>
57 #include <libkern/c++/OSArray.h>
58 #include <libkern/c++/OSSymbol.h>
59 #include <libkern/c++/OSNumber.h>
65 #include <vm/vm_pageout.h>
66 #include <mach/memory_object_types.h>
67 #include <device/device_port.h>
69 #include <mach/vm_prot.h>
70 #include <mach/mach_vm.h>
71 #include <vm/vm_fault.h>
72 #include <vm/vm_protos.h>
74 extern ppnum_t
pmap_find_phys(pmap_t pmap
, addr64_t va
);
75 void ipc_port_release_send(ipc_port_t port
);
77 /* Copy between a physical page and a virtual address in the given vm_map */
78 kern_return_t
copypv(addr64_t source
, addr64_t sink
, unsigned int size
, int which
);
82 memory_object_t pager
,
83 uintptr_t device_handle
,
87 device_pager_deallocate(
90 device_pager_populate_object(
91 memory_object_t pager
,
92 vm_object_offset_t offset
,
96 memory_object_iopl_request(
98 memory_object_offset_t offset
,
101 upl_page_info_array_t user_page_list
,
102 unsigned int *page_list_count
,
105 unsigned int IOTranslateCacheBits(struct phys_entry
*pp
);
109 #define kIOMaximumMappedIOByteCount (512*1024*1024)
111 static IOMapper
* gIOSystemMapper
= NULL
;
113 IOCopyMapper
* gIOCopyMapper
= NULL
;
115 static ppnum_t gIOMaximumMappedIOPageCount
= atop_32(kIOMaximumMappedIOByteCount
);
119 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
121 OSDefineMetaClassAndAbstractStructors( IOMemoryDescriptor
, OSObject
)
123 #define super IOMemoryDescriptor
125 OSDefineMetaClassAndStructors(IOGeneralMemoryDescriptor
, IOMemoryDescriptor
)
127 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
129 static IORecursiveLock
* gIOMemoryLock
;
131 #define LOCK IORecursiveLockLock( gIOMemoryLock)
132 #define UNLOCK IORecursiveLockUnlock( gIOMemoryLock)
133 #define SLEEP IORecursiveLockSleep( gIOMemoryLock, (void *)this, THREAD_UNINT)
135 IORecursiveLockWakeup( gIOMemoryLock, (void *)this, /* one-thread */ false)
138 #define DEBG(fmt, args...) { kprintf(fmt, ## args); }
140 #define DEBG(fmt, args...) {}
143 #define IOMD_DEBUG_DMAACTIVE 1
145 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
147 // Some data structures and accessor macros used by the initWithOptions
150 enum ioPLBlockFlags
{
151 kIOPLOnDevice
= 0x00000001,
152 kIOPLExternUPL
= 0x00000002,
155 struct typePersMDData
157 const IOGeneralMemoryDescriptor
*fMD
;
158 ipc_port_t fMemEntry
;
163 vm_address_t fPageInfo
; // Pointer to page list or index into it
164 uint32_t fIOMDOffset
; // The offset of this iopl in descriptor
165 ppnum_t fMappedBase
; // Page number of first page in this iopl
166 unsigned int fPageOffset
; // Offset within first page of iopl
167 unsigned int fFlags
; // Flags
172 uint64_t fPreparationID
;
173 unsigned int fPageCnt
;
175 // align arrays to 8 bytes so following macros work
178 upl_page_info_t fPageList
[];
182 #define getDataP(osd) ((ioGMDData *) (osd)->getBytesNoCopy())
183 #define getIOPLList(d) ((ioPLBlock *) &(d->fPageList[d->fPageCnt]))
184 #define getNumIOPL(osd, d) \
185 (((osd)->getLength() - ((char *) getIOPLList(d) - (char *) d)) / sizeof(ioPLBlock))
186 #define getPageList(d) (&(d->fPageList[0]))
187 #define computeDataSize(p, u) \
188 (sizeof(ioGMDData) + p * sizeof(upl_page_info_t) + u * sizeof(ioPLBlock))
191 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
193 #define next_page(a) ( trunc_page(a) + PAGE_SIZE )
198 kern_return_t
device_data_action(
199 uintptr_t device_handle
,
200 ipc_port_t device_pager
,
201 vm_prot_t protection
,
202 vm_object_offset_t offset
,
205 struct ExpansionData
{
207 unsigned int pagerContig
:1;
208 unsigned int unused
:31;
209 IOMemoryDescriptor
* memory
;
212 ExpansionData
* ref
= (ExpansionData
*) device_handle
;
213 IOMemoryDescriptor
* memDesc
;
216 memDesc
= ref
->memory
;
220 kr
= memDesc
->handleFault( device_pager
, 0, 0,
221 offset
, size
, kIOMapDefaultCache
/*?*/);
231 kern_return_t
device_close(
232 uintptr_t device_handle
)
234 struct ExpansionData
{
236 unsigned int pagerContig
:1;
237 unsigned int unused
:31;
238 IOMemoryDescriptor
* memory
;
240 ExpansionData
* ref
= (ExpansionData
*) device_handle
;
242 IODelete( ref
, ExpansionData
, 1 );
244 return( kIOReturnSuccess
);
248 // Note this inline function uses C++ reference arguments to return values
249 // This means that pointers are not passed and NULLs don't have to be
250 // checked for as a NULL reference is illegal.
252 getAddrLenForInd(user_addr_t
&addr
, IOPhysicalLength
&len
, // Output variables
253 UInt32 type
, IOGeneralMemoryDescriptor::Ranges r
, UInt32 ind
)
255 assert(kIOMemoryTypeUIO
== type
256 || kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
257 || kIOMemoryTypePhysical
== type
|| kIOMemoryTypePhysical64
== type
);
258 if (kIOMemoryTypeUIO
== type
) {
260 uio_getiov((uio_t
) r
.uio
, ind
, &addr
, &us
); len
= us
;
263 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
)) {
264 IOAddressRange cur
= r
.v64
[ind
];
268 #endif /* !__LP64__ */
270 IOVirtualRange cur
= r
.v
[ind
];
276 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
279 IOMemoryDescriptor::withAddress(void * address
,
281 IODirection direction
)
283 return IOMemoryDescriptor::
284 withAddressRange((IOVirtualAddress
) address
, length
, direction
| kIOMemoryAutoPrepare
, kernel_task
);
289 IOMemoryDescriptor::withAddress(IOVirtualAddress address
,
291 IODirection direction
,
294 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
297 if (that
->initWithAddress(address
, length
, direction
, task
))
304 #endif /* !__LP64__ */
307 IOMemoryDescriptor::withPhysicalAddress(
308 IOPhysicalAddress address
,
310 IODirection direction
)
313 return (IOMemoryDescriptor::withAddressRange(address
, length
, direction
, TASK_NULL
));
314 #else /* !__LP64__ */
315 IOGeneralMemoryDescriptor
*self
= new IOGeneralMemoryDescriptor
;
317 && !self
->initWithPhysicalAddress(address
, length
, direction
)) {
323 #endif /* !__LP64__ */
328 IOMemoryDescriptor::withRanges( IOVirtualRange
* ranges
,
330 IODirection direction
,
334 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
337 if (that
->initWithRanges(ranges
, withCount
, direction
, task
, asReference
))
344 #endif /* !__LP64__ */
347 IOMemoryDescriptor::withAddressRange(mach_vm_address_t address
,
348 mach_vm_size_t length
,
349 IOOptionBits options
,
352 IOAddressRange range
= { address
, length
};
353 return (IOMemoryDescriptor::withAddressRanges(&range
, 1, options
, task
));
357 IOMemoryDescriptor::withAddressRanges(IOAddressRange
* ranges
,
359 IOOptionBits options
,
362 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
366 options
|= kIOMemoryTypeVirtual64
;
368 options
|= kIOMemoryTypePhysical64
;
370 if (that
->initWithOptions(ranges
, rangeCount
, 0, task
, options
, /* mapper */ 0))
383 * Create a new IOMemoryDescriptor. The buffer is made up of several
384 * virtual address ranges, from a given task.
386 * Passing the ranges as a reference will avoid an extra allocation.
389 IOMemoryDescriptor::withOptions(void * buffers
,
396 IOGeneralMemoryDescriptor
*self
= new IOGeneralMemoryDescriptor
;
399 && !self
->initWithOptions(buffers
, count
, offset
, task
, opts
, mapper
))
408 bool IOMemoryDescriptor::initWithOptions(void * buffers
,
412 IOOptionBits options
,
420 IOMemoryDescriptor::withPhysicalRanges( IOPhysicalRange
* ranges
,
422 IODirection direction
,
425 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
428 if (that
->initWithPhysicalRanges(ranges
, withCount
, direction
, asReference
))
437 IOMemoryDescriptor::withSubRange(IOMemoryDescriptor
* of
,
440 IODirection direction
)
442 return (IOSubMemoryDescriptor::withSubRange(of
, offset
, length
, direction
| kIOMemoryThreadSafe
));
444 #endif /* !__LP64__ */
447 IOMemoryDescriptor::withPersistentMemoryDescriptor(IOMemoryDescriptor
*originalMD
)
449 IOGeneralMemoryDescriptor
*origGenMD
=
450 OSDynamicCast(IOGeneralMemoryDescriptor
, originalMD
);
453 return IOGeneralMemoryDescriptor::
454 withPersistentMemoryDescriptor(origGenMD
);
460 IOGeneralMemoryDescriptor::withPersistentMemoryDescriptor(IOGeneralMemoryDescriptor
*originalMD
)
462 ipc_port_t sharedMem
= (ipc_port_t
) originalMD
->createNamedEntry();
467 if (sharedMem
== originalMD
->_memEntry
) {
468 originalMD
->retain(); // Add a new reference to ourselves
469 ipc_port_release_send(sharedMem
); // Remove extra send right
473 IOGeneralMemoryDescriptor
* self
= new IOGeneralMemoryDescriptor
;
474 typePersMDData initData
= { originalMD
, sharedMem
};
477 && !self
->initWithOptions(&initData
, 1, 0, 0, kIOMemoryTypePersistentMD
, 0)) {
484 void *IOGeneralMemoryDescriptor::createNamedEntry()
487 ipc_port_t sharedMem
;
489 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
491 user_addr_t range0Addr
;
492 IOByteCount range0Len
;
493 getAddrLenForInd(range0Addr
, range0Len
, type
, _ranges
, 0);
494 range0Addr
= trunc_page_64(range0Addr
);
496 vm_size_t size
= ptoa_32(_pages
);
497 vm_address_t kernelPage
= (vm_address_t
) range0Addr
;
499 vm_map_t theMap
= ((_task
== kernel_task
)
500 && (kIOMemoryBufferPageable
& _flags
))
501 ? IOPageableMapForAddress(kernelPage
)
502 : get_task_map(_task
);
504 memory_object_size_t actualSize
= size
;
505 vm_prot_t prot
= VM_PROT_READ
;
507 if (kIODirectionOut
!= (kIODirectionOutIn
& _flags
))
509 prot
|= VM_PROT_WRITE
;
512 prot
|= MAP_MEM_NAMED_REUSE
;
514 error
= mach_make_memory_entry_64(theMap
,
515 &actualSize
, range0Addr
, prot
, &sharedMem
, (ipc_port_t
) _memEntry
);
517 if (KERN_SUCCESS
== error
) {
518 if (actualSize
== size
) {
522 IOLog("IOGMD::mach_make_memory_entry_64 (%08llx) size (%08llx:%08llx)\n",
523 (UInt64
)range0Addr
, (UInt64
)actualSize
, (UInt64
)size
);
525 ipc_port_release_send( sharedMem
);
529 return MACH_PORT_NULL
;
534 IOGeneralMemoryDescriptor::initWithAddress(void * address
,
535 IOByteCount withLength
,
536 IODirection withDirection
)
538 _singleRange
.v
.address
= (vm_offset_t
) address
;
539 _singleRange
.v
.length
= withLength
;
541 return initWithRanges(&_singleRange
.v
, 1, withDirection
, kernel_task
, true);
545 IOGeneralMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
546 IOByteCount withLength
,
547 IODirection withDirection
,
550 _singleRange
.v
.address
= address
;
551 _singleRange
.v
.length
= withLength
;
553 return initWithRanges(&_singleRange
.v
, 1, withDirection
, withTask
, true);
557 IOGeneralMemoryDescriptor::initWithPhysicalAddress(
558 IOPhysicalAddress address
,
559 IOByteCount withLength
,
560 IODirection withDirection
)
562 _singleRange
.p
.address
= address
;
563 _singleRange
.p
.length
= withLength
;
565 return initWithPhysicalRanges( &_singleRange
.p
, 1, withDirection
, true);
569 IOGeneralMemoryDescriptor::initWithPhysicalRanges(
570 IOPhysicalRange
* ranges
,
572 IODirection direction
,
575 IOOptionBits mdOpts
= direction
| kIOMemoryTypePhysical
;
578 mdOpts
|= kIOMemoryAsReference
;
580 return initWithOptions(ranges
, count
, 0, 0, mdOpts
, /* mapper */ 0);
584 IOGeneralMemoryDescriptor::initWithRanges(
585 IOVirtualRange
* ranges
,
587 IODirection direction
,
591 IOOptionBits mdOpts
= direction
;
594 mdOpts
|= kIOMemoryAsReference
;
597 mdOpts
|= kIOMemoryTypeVirtual
;
599 // Auto-prepare if this is a kernel memory descriptor as very few
600 // clients bother to prepare() kernel memory.
601 // But it was not enforced so what are you going to do?
602 if (task
== kernel_task
)
603 mdOpts
|= kIOMemoryAutoPrepare
;
606 mdOpts
|= kIOMemoryTypePhysical
;
608 return initWithOptions(ranges
, count
, 0, task
, mdOpts
, /* mapper */ 0);
610 #endif /* !__LP64__ */
615 * IOMemoryDescriptor. The buffer is made up of several virtual address ranges,
616 * from a given task, several physical ranges, an UPL from the ubc
617 * system or a uio (may be 64bit) from the BSD subsystem.
619 * Passing the ranges as a reference will avoid an extra allocation.
621 * An IOMemoryDescriptor can be re-used by calling initWithOptions again on an
622 * existing instance -- note this behavior is not commonly supported in other
623 * I/O Kit classes, although it is supported here.
627 IOGeneralMemoryDescriptor::initWithOptions(void * buffers
,
631 IOOptionBits options
,
634 IOOptionBits type
= options
& kIOMemoryTypeMask
;
636 // Grab the original MD's configuation data to initialse the
637 // arguments to this function.
638 if (kIOMemoryTypePersistentMD
== type
) {
640 typePersMDData
*initData
= (typePersMDData
*) buffers
;
641 const IOGeneralMemoryDescriptor
*orig
= initData
->fMD
;
642 ioGMDData
*dataP
= getDataP(orig
->_memoryEntries
);
644 // Only accept persistent memory descriptors with valid dataP data.
645 assert(orig
->_rangesCount
== 1);
646 if ( !(orig
->_flags
& kIOMemoryPersistent
) || !dataP
)
649 _memEntry
= initData
->fMemEntry
; // Grab the new named entry
650 options
= orig
->_flags
| kIOMemoryAsReference
;
651 _singleRange
= orig
->_singleRange
; // Initialise our range
652 buffers
= &_singleRange
;
655 // Now grab the original task and whatever mapper was previously used
657 mapper
= dataP
->fMapper
;
659 // We are ready to go through the original initialisation now
663 case kIOMemoryTypeUIO
:
664 case kIOMemoryTypeVirtual
:
666 case kIOMemoryTypeVirtual64
:
667 #endif /* !__LP64__ */
673 if (vm_map_is_64bit(get_task_map(task
))
674 && (kIOMemoryTypeVirtual
== type
)
675 && ((IOVirtualRange
*) buffers
)->address
)
677 OSReportWithBacktrace("IOMemoryDescriptor: attempt to create 32b virtual in 64b task, use ::withAddressRange()");
680 #endif /* !__LP64__ */
683 case kIOMemoryTypePhysical
: // Neither Physical nor UPL should have a task
685 case kIOMemoryTypePhysical64
:
686 #endif /* !__LP64__ */
687 case kIOMemoryTypeUPL
:
691 return false; /* bad argument */
698 * We can check the _initialized instance variable before having ever set
699 * it to an initial value because I/O Kit guarantees that all our instance
700 * variables are zeroed on an object's allocation.
705 * An existing memory descriptor is being retargeted to point to
706 * somewhere else. Clean up our present state.
708 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
709 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
714 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
716 if (kIOMemoryTypeUIO
== type
)
717 uio_free((uio_t
) _ranges
.v
);
719 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
720 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
721 #endif /* !__LP64__ */
723 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
727 { ipc_port_release_send((ipc_port_t
) _memEntry
); _memEntry
= 0; }
729 _mappings
->flushCollection();
737 // Grab the appropriate mapper
738 if (kIOMemoryMapperNone
& options
)
739 mapper
= 0; // No Mapper
740 else if (mapper
== kIOMapperSystem
) {
741 IOMapper::checkForSystemMapper();
742 gIOSystemMapper
= mapper
= IOMapper::gSystem
;
745 // Temp binary compatibility for kIOMemoryThreadSafe
746 if (kIOMemoryReserved6156215
& options
)
748 options
&= ~kIOMemoryReserved6156215
;
749 options
|= kIOMemoryThreadSafe
;
751 // Remove the dynamic internal use flags from the initial setting
752 options
&= ~(kIOMemoryPreparedReadOnly
);
757 _direction
= (IODirection
) (_flags
& kIOMemoryDirectionMask
);
758 #endif /* !__LP64__ */
760 __iomd_reservedA
= 0;
761 __iomd_reservedB
= 0;
764 if (kIOMemoryThreadSafe
& options
)
767 _prepareLock
= IOLockAlloc();
769 else if (_prepareLock
)
771 IOLockFree(_prepareLock
);
775 if (kIOMemoryTypeUPL
== type
) {
778 unsigned int dataSize
= computeDataSize(/* pages */ 0, /* upls */ 1);
780 if (!_memoryEntries
) {
781 _memoryEntries
= OSData::withCapacity(dataSize
);
785 else if (!_memoryEntries
->initWithCapacity(dataSize
))
788 _memoryEntries
->appendBytes(0, sizeof(ioGMDData
));
789 dataP
= getDataP(_memoryEntries
);
790 dataP
->fMapper
= mapper
;
793 // _wireCount++; // UPLs start out life wired
796 _pages
+= atop_32(offset
+ count
+ PAGE_MASK
) - atop_32(offset
);
799 iopl
.fIOPL
= (upl_t
) buffers
;
800 upl_page_info_t
*pageList
= UPL_GET_INTERNAL_PAGE_LIST(iopl
.fIOPL
);
802 if (upl_get_size(iopl
.fIOPL
) < (count
+ offset
))
803 panic("short external upl");
805 // Set the flag kIOPLOnDevice convieniently equal to 1
806 iopl
.fFlags
= pageList
->device
| kIOPLExternUPL
;
807 iopl
.fIOMDOffset
= 0;
809 _highestPage
= upl_get_highest_page(iopl
.fIOPL
);
811 if (!pageList
->device
) {
812 // Pre-compute the offset into the UPL's page list
813 pageList
= &pageList
[atop_32(offset
)];
816 iopl
.fMappedBase
= mapper
->iovmAlloc(_pages
);
817 mapper
->iovmInsert(iopl
.fMappedBase
, 0, pageList
, _pages
);
820 iopl
.fMappedBase
= 0;
823 iopl
.fMappedBase
= 0;
824 iopl
.fPageInfo
= (vm_address_t
) pageList
;
825 iopl
.fPageOffset
= offset
;
827 _memoryEntries
->appendBytes(&iopl
, sizeof(iopl
));
830 // kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO
831 // kIOMemoryTypePhysical | kIOMemoryTypePhysical64
833 // Initialize the memory descriptor
834 if (options
& kIOMemoryAsReference
) {
836 _rangesIsAllocated
= false;
837 #endif /* !__LP64__ */
839 // Hack assignment to get the buffer arg into _ranges.
840 // I'd prefer to do _ranges = (Ranges) buffers, but that doesn't
842 // This also initialises the uio & physical ranges.
843 _ranges
.v
= (IOVirtualRange
*) buffers
;
847 _rangesIsAllocated
= true;
848 #endif /* !__LP64__ */
851 case kIOMemoryTypeUIO
:
852 _ranges
.v
= (IOVirtualRange
*) uio_duplicate((uio_t
) buffers
);
856 case kIOMemoryTypeVirtual64
:
857 case kIOMemoryTypePhysical64
:
859 && (((IOAddressRange
*) buffers
)->address
+ ((IOAddressRange
*) buffers
)->length
) <= 0x100000000ULL
) {
860 if (kIOMemoryTypeVirtual64
== type
)
861 type
= kIOMemoryTypeVirtual
;
863 type
= kIOMemoryTypePhysical
;
864 _flags
= (_flags
& ~kIOMemoryTypeMask
) | type
| kIOMemoryAsReference
;
865 _rangesIsAllocated
= false;
866 _ranges
.v
= &_singleRange
.v
;
867 _singleRange
.v
.address
= ((IOAddressRange
*) buffers
)->address
;
868 _singleRange
.v
.length
= ((IOAddressRange
*) buffers
)->length
;
871 _ranges
.v64
= IONew(IOAddressRange
, count
);
874 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOAddressRange
));
876 #endif /* !__LP64__ */
877 case kIOMemoryTypeVirtual
:
878 case kIOMemoryTypePhysical
:
880 _flags
|= kIOMemoryAsReference
;
882 _rangesIsAllocated
= false;
883 #endif /* !__LP64__ */
884 _ranges
.v
= &_singleRange
.v
;
886 _ranges
.v
= IONew(IOVirtualRange
, count
);
890 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOVirtualRange
));
895 // Find starting address within the vector of ranges
896 Ranges vec
= _ranges
;
899 for (unsigned ind
= 0; ind
< count
; ind
++) {
901 IOPhysicalLength len
;
903 // addr & len are returned by this function
904 getAddrLenForInd(addr
, len
, type
, vec
, ind
);
905 pages
+= (atop_64(addr
+ len
+ PAGE_MASK
) - atop_64(addr
));
907 assert(len
>= length
); // Check for 32 bit wrap around
910 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
912 ppnum_t highPage
= atop_64(addr
+ len
- 1);
913 if (highPage
> _highestPage
)
914 _highestPage
= highPage
;
919 _rangesCount
= count
;
921 // Auto-prepare memory at creation time.
922 // Implied completion when descriptor is free-ed
923 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
924 _wireCount
++; // Physical MDs are, by definition, wired
925 else { /* kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO */
927 unsigned dataSize
= computeDataSize(_pages
, /* upls */ count
* 2);
929 if (!_memoryEntries
) {
930 _memoryEntries
= OSData::withCapacity(dataSize
);
934 else if (!_memoryEntries
->initWithCapacity(dataSize
))
937 _memoryEntries
->appendBytes(0, sizeof(ioGMDData
));
938 dataP
= getDataP(_memoryEntries
);
939 dataP
->fMapper
= mapper
;
940 dataP
->fPageCnt
= _pages
;
942 if ( (kIOMemoryPersistent
& _flags
) && !_memEntry
)
943 _memEntry
= createNamedEntry();
945 if ((_flags
& kIOMemoryAutoPrepare
)
946 && prepare() != kIOReturnSuccess
)
959 void IOGeneralMemoryDescriptor::free()
961 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
966 reserved
->memory
= 0;
970 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
976 _memoryEntries
->release();
978 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
980 if (kIOMemoryTypeUIO
== type
)
981 uio_free((uio_t
) _ranges
.v
);
983 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
984 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
985 #endif /* !__LP64__ */
987 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
992 if (reserved
&& reserved
->devicePager
)
993 device_pager_deallocate( (memory_object_t
) reserved
->devicePager
);
995 // memEntry holds a ref on the device pager which owns reserved
996 // (ExpansionData) so no reserved access after this point
998 ipc_port_release_send( (ipc_port_t
) _memEntry
);
1001 IOLockFree(_prepareLock
);
1007 void IOGeneralMemoryDescriptor::unmapFromKernel()
1009 panic("IOGMD::unmapFromKernel deprecated");
1012 void IOGeneralMemoryDescriptor::mapIntoKernel(unsigned rangeIndex
)
1014 panic("IOGMD::mapIntoKernel deprecated");
1016 #endif /* !__LP64__ */
1021 * Get the direction of the transfer.
1023 IODirection
IOMemoryDescriptor::getDirection() const
1028 #endif /* !__LP64__ */
1029 return (IODirection
) (_flags
& kIOMemoryDirectionMask
);
1035 * Get the length of the transfer (over all ranges).
1037 IOByteCount
IOMemoryDescriptor::getLength() const
1042 void IOMemoryDescriptor::setTag( IOOptionBits tag
)
1047 IOOptionBits
IOMemoryDescriptor::getTag( void )
1053 // @@@ gvdl: who is using this API? Seems like a wierd thing to implement.
1055 IOMemoryDescriptor::getSourceSegment( IOByteCount offset
, IOByteCount
* length
)
1057 addr64_t physAddr
= 0;
1059 if( prepare() == kIOReturnSuccess
) {
1060 physAddr
= getPhysicalSegment64( offset
, length
);
1064 return( (IOPhysicalAddress
) physAddr
); // truncated but only page offset is used
1066 #endif /* !__LP64__ */
1068 IOByteCount
IOMemoryDescriptor::readBytes
1069 (IOByteCount offset
, void *bytes
, IOByteCount length
)
1071 addr64_t dstAddr
= CAST_DOWN(addr64_t
, bytes
);
1072 IOByteCount remaining
;
1074 // Assert that this entire I/O is withing the available range
1075 assert(offset
< _length
);
1076 assert(offset
+ length
<= _length
);
1077 if (offset
>= _length
) {
1081 if (kIOMemoryThreadSafe
& _flags
)
1084 remaining
= length
= min(length
, _length
- offset
);
1085 while (remaining
) { // (process another target segment?)
1089 srcAddr64
= getPhysicalSegment(offset
, &srcLen
, kIOMemoryMapperNone
);
1093 // Clip segment length to remaining
1094 if (srcLen
> remaining
)
1097 copypv(srcAddr64
, dstAddr
, srcLen
,
1098 cppvPsrc
| cppvNoRefSrc
| cppvFsnk
| cppvKmap
);
1102 remaining
-= srcLen
;
1105 if (kIOMemoryThreadSafe
& _flags
)
1110 return length
- remaining
;
1113 IOByteCount
IOMemoryDescriptor::writeBytes
1114 (IOByteCount offset
, const void *bytes
, IOByteCount length
)
1116 addr64_t srcAddr
= CAST_DOWN(addr64_t
, bytes
);
1117 IOByteCount remaining
;
1119 // Assert that this entire I/O is withing the available range
1120 assert(offset
< _length
);
1121 assert(offset
+ length
<= _length
);
1123 assert( !(kIOMemoryPreparedReadOnly
& _flags
) );
1125 if ( (kIOMemoryPreparedReadOnly
& _flags
) || offset
>= _length
) {
1129 if (kIOMemoryThreadSafe
& _flags
)
1132 remaining
= length
= min(length
, _length
- offset
);
1133 while (remaining
) { // (process another target segment?)
1137 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1141 // Clip segment length to remaining
1142 if (dstLen
> remaining
)
1145 copypv(srcAddr
, (addr64_t
) dstAddr64
, dstLen
,
1146 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
1150 remaining
-= dstLen
;
1153 if (kIOMemoryThreadSafe
& _flags
)
1158 return length
- remaining
;
1161 // osfmk/device/iokit_rpc.c
1162 extern "C" unsigned int IODefaultCacheBits(addr64_t pa
);
1165 void IOGeneralMemoryDescriptor::setPosition(IOByteCount position
)
1167 panic("IOGMD::setPosition deprecated");
1169 #endif /* !__LP64__ */
1171 static volatile SInt64 gIOMDPreparationID
__attribute__((aligned(8))) = (1ULL << 32);
1174 IOGeneralMemoryDescriptor::getPreparationID( void )
1177 if (!_wireCount
|| !(dataP
= getDataP(_memoryEntries
)))
1178 return (kIOPreparationIDUnprepared
);
1179 if (kIOPreparationIDUnprepared
== dataP
->fPreparationID
)
1181 #if defined(__ppc__ )
1182 dataP
->fPreparationID
= gIOMDPreparationID
++;
1184 dataP
->fPreparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1187 return (dataP
->fPreparationID
);
1191 IOMemoryDescriptor::getPreparationID( void )
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 md
->__iomd_reservedA
++;
1233 } else if (kIOMDSetDMAInactive
== op
) {
1234 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
1235 if (md
->__iomd_reservedA
)
1236 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 IOReturn
IOMemoryDescriptor::performOperation( IOOptionBits options
,
1830 IOByteCount offset
, IOByteCount length
)
1832 IOByteCount remaining
;
1833 void (*func
)(addr64_t pa
, unsigned int count
) = 0;
1837 case kIOMemoryIncoherentIOFlush
:
1838 func
= &dcache_incoherent_io_flush64
;
1840 case kIOMemoryIncoherentIOStore
:
1841 func
= &dcache_incoherent_io_store64
;
1846 return (kIOReturnUnsupported
);
1848 if (kIOMemoryThreadSafe
& _flags
)
1851 remaining
= length
= min(length
, getLength() - offset
);
1853 // (process another target segment?)
1858 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1862 // Clip segment length to remaining
1863 if (dstLen
> remaining
)
1866 (*func
)(dstAddr64
, dstLen
);
1869 remaining
-= dstLen
;
1872 if (kIOMemoryThreadSafe
& _flags
)
1875 return (remaining
? kIOReturnUnderrun
: kIOReturnSuccess
);
1878 #if defined(__ppc__) || defined(__arm__)
1879 extern vm_offset_t static_memory_end
;
1880 #define io_kernel_static_end static_memory_end
1882 extern vm_offset_t first_avail
;
1883 #define io_kernel_static_end first_avail
1886 static kern_return_t
1887 io_get_kernel_static_upl(
1890 vm_size_t
*upl_size
,
1892 upl_page_info_array_t page_list
,
1893 unsigned int *count
,
1894 ppnum_t
*highest_page
)
1896 unsigned int pageCount
, page
;
1898 ppnum_t highestPage
= 0;
1900 pageCount
= atop_32(*upl_size
);
1901 if (pageCount
> *count
)
1906 for (page
= 0; page
< pageCount
; page
++)
1908 phys
= pmap_find_phys(kernel_pmap
, ((addr64_t
)offset
) + ptoa_64(page
));
1911 page_list
[page
].phys_addr
= phys
;
1912 page_list
[page
].pageout
= 0;
1913 page_list
[page
].absent
= 0;
1914 page_list
[page
].dirty
= 0;
1915 page_list
[page
].precious
= 0;
1916 page_list
[page
].device
= 0;
1917 if (phys
> highestPage
)
1921 *highest_page
= highestPage
;
1923 return ((page
>= pageCount
) ? kIOReturnSuccess
: kIOReturnVMError
);
1926 IOReturn
IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection
)
1928 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1929 IOReturn error
= kIOReturnCannotWire
;
1931 ppnum_t mapBase
= 0;
1933 ipc_port_t sharedMem
= (ipc_port_t
) _memEntry
;
1935 assert(!_wireCount
);
1936 assert(kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
);
1938 if (_pages
>= gIOMaximumMappedIOPageCount
)
1939 return kIOReturnNoResources
;
1941 dataP
= getDataP(_memoryEntries
);
1942 mapper
= dataP
->fMapper
;
1943 if (mapper
&& _pages
)
1944 mapBase
= mapper
->iovmAlloc(_pages
);
1946 // Note that appendBytes(NULL) zeros the data up to the
1948 _memoryEntries
->appendBytes(0, dataP
->fPageCnt
* sizeof(upl_page_info_t
));
1949 dataP
= 0; // May no longer be valid so lets not get tempted.
1951 if (forDirection
== kIODirectionNone
)
1952 forDirection
= getDirection();
1954 int uplFlags
; // This Mem Desc's default flags for upl creation
1955 switch (kIODirectionOutIn
& forDirection
)
1957 case kIODirectionOut
:
1958 // Pages do not need to be marked as dirty on commit
1959 uplFlags
= UPL_COPYOUT_FROM
;
1960 _flags
|= kIOMemoryPreparedReadOnly
;
1963 case kIODirectionIn
:
1965 uplFlags
= 0; // i.e. ~UPL_COPYOUT_FROM
1968 uplFlags
|= UPL_SET_IO_WIRE
| UPL_SET_LITE
;
1970 #ifdef UPL_NEED_32BIT_ADDR
1971 if (kIODirectionPrepareToPhys32
& forDirection
)
1972 uplFlags
|= UPL_NEED_32BIT_ADDR
;
1975 // Find the appropriate vm_map for the given task
1977 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
1980 { curMap
= get_task_map(_task
); }
1982 // Iterate over the vector of virtual ranges
1983 Ranges vec
= _ranges
;
1984 unsigned int pageIndex
= 0;
1985 IOByteCount mdOffset
= 0;
1986 ppnum_t highestPage
= 0;
1987 for (UInt range
= 0; range
< _rangesCount
; range
++) {
1989 user_addr_t startPage
;
1990 IOByteCount numBytes
;
1991 ppnum_t highPage
= 0;
1993 // Get the startPage address and length of vec[range]
1994 getAddrLenForInd(startPage
, numBytes
, type
, vec
, range
);
1995 iopl
.fPageOffset
= startPage
& PAGE_MASK
;
1996 numBytes
+= iopl
.fPageOffset
;
1997 startPage
= trunc_page_64(startPage
);
2000 iopl
.fMappedBase
= mapBase
+ pageIndex
;
2002 iopl
.fMappedBase
= 0;
2004 // Iterate over the current range, creating UPLs
2006 dataP
= getDataP(_memoryEntries
);
2007 vm_address_t kernelStart
= (vm_address_t
) startPage
;
2011 else if (!sharedMem
) {
2012 assert(_task
== kernel_task
);
2013 theMap
= IOPageableMapForAddress(kernelStart
);
2018 upl_page_info_array_t pageInfo
= getPageList(dataP
);
2019 int ioplFlags
= uplFlags
;
2020 upl_page_list_ptr_t baseInfo
= &pageInfo
[pageIndex
];
2022 vm_size_t ioplSize
= round_page(numBytes
);
2023 unsigned int numPageInfo
= atop_32(ioplSize
);
2025 if (theMap
== kernel_map
&& kernelStart
< io_kernel_static_end
) {
2026 error
= io_get_kernel_static_upl(theMap
,
2034 else if (sharedMem
) {
2035 error
= memory_object_iopl_request(sharedMem
,
2045 error
= vm_map_create_upl(theMap
,
2047 (upl_size_t
*)&ioplSize
,
2055 if (error
!= KERN_SUCCESS
)
2059 highPage
= upl_get_highest_page(iopl
.fIOPL
);
2060 if (highPage
> highestPage
)
2061 highestPage
= highPage
;
2063 error
= kIOReturnCannotWire
;
2065 if (baseInfo
->device
) {
2067 iopl
.fFlags
= kIOPLOnDevice
;
2068 // Don't translate device memory at all
2069 if (mapper
&& mapBase
) {
2070 mapper
->iovmFree(mapBase
, _pages
);
2072 iopl
.fMappedBase
= 0;
2078 mapper
->iovmInsert(mapBase
, pageIndex
,
2079 baseInfo
, numPageInfo
);
2082 iopl
.fIOMDOffset
= mdOffset
;
2083 iopl
.fPageInfo
= pageIndex
;
2085 if ((_flags
& kIOMemoryAutoPrepare
) && iopl
.fIOPL
)
2087 upl_commit(iopl
.fIOPL
, 0, 0);
2088 upl_deallocate(iopl
.fIOPL
);
2092 if (!_memoryEntries
->appendBytes(&iopl
, sizeof(iopl
))) {
2093 // Clean up partial created and unsaved iopl
2095 upl_abort(iopl
.fIOPL
, 0);
2096 upl_deallocate(iopl
.fIOPL
);
2101 // Check for a multiple iopl's in one virtual range
2102 pageIndex
+= numPageInfo
;
2103 mdOffset
-= iopl
.fPageOffset
;
2104 if (ioplSize
< numBytes
) {
2105 numBytes
-= ioplSize
;
2106 startPage
+= ioplSize
;
2107 mdOffset
+= ioplSize
;
2108 iopl
.fPageOffset
= 0;
2110 iopl
.fMappedBase
= mapBase
+ pageIndex
;
2113 mdOffset
+= numBytes
;
2119 _highestPage
= highestPage
;
2121 return kIOReturnSuccess
;
2125 dataP
= getDataP(_memoryEntries
);
2126 UInt done
= getNumIOPL(_memoryEntries
, dataP
);
2127 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2129 for (UInt range
= 0; range
< done
; range
++)
2131 if (ioplList
[range
].fIOPL
) {
2132 upl_abort(ioplList
[range
].fIOPL
, 0);
2133 upl_deallocate(ioplList
[range
].fIOPL
);
2136 (void) _memoryEntries
->initWithBytes(dataP
, sizeof(ioGMDData
)); // == setLength()
2138 if (mapper
&& mapBase
)
2139 mapper
->iovmFree(mapBase
, _pages
);
2142 if (error
== KERN_FAILURE
)
2143 error
= kIOReturnCannotWire
;
2151 * Prepare the memory for an I/O transfer. This involves paging in
2152 * the memory, if necessary, and wiring it down for the duration of
2153 * the transfer. The complete() method completes the processing of
2154 * the memory after the I/O transfer finishes. This method needn't
2155 * called for non-pageable memory.
2157 IOReturn
IOGeneralMemoryDescriptor::prepare(IODirection forDirection
)
2159 IOReturn error
= kIOReturnSuccess
;
2160 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2162 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
2163 return kIOReturnSuccess
;
2166 IOLockLock(_prepareLock
);
2169 && (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) ) {
2170 error
= wireVirtual(forDirection
);
2173 if (kIOReturnSuccess
== error
)
2177 IOLockUnlock(_prepareLock
);
2185 * Complete processing of the memory after an I/O transfer finishes.
2186 * This method should not be called unless a prepare was previously
2187 * issued; the prepare() and complete() must occur in pairs, before
2188 * before and after an I/O transfer involving pageable memory.
2191 IOReturn
IOGeneralMemoryDescriptor::complete(IODirection
/* forDirection */)
2193 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2195 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
2196 return kIOReturnSuccess
;
2199 IOLockLock(_prepareLock
);
2208 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2209 ioGMDData
* dataP
= getDataP(_memoryEntries
);
2210 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2211 UInt count
= getNumIOPL(_memoryEntries
, dataP
);
2213 #if IOMD_DEBUG_DMAACTIVE
2214 if (__iomd_reservedA
) panic("complete() while dma active");
2215 #endif /* IOMD_DEBUG_DMAACTIVE */
2217 if (dataP
->fMapper
&& _pages
&& ioplList
[0].fMappedBase
)
2218 dataP
->fMapper
->iovmFree(ioplList
[0].fMappedBase
, _pages
);
2220 // Only complete iopls that we created which are for TypeVirtual
2221 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) {
2222 for (UInt ind
= 0; ind
< count
; ind
++)
2223 if (ioplList
[ind
].fIOPL
) {
2224 upl_commit(ioplList
[ind
].fIOPL
, 0, 0);
2225 upl_deallocate(ioplList
[ind
].fIOPL
);
2228 (void) _memoryEntries
->initWithBytes(dataP
, sizeof(ioGMDData
)); // == setLength()
2230 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
2235 IOLockUnlock(_prepareLock
);
2237 return kIOReturnSuccess
;
2240 IOReturn
IOGeneralMemoryDescriptor::doMap(
2241 vm_map_t __addressMap
,
2242 IOVirtualAddress
* __address
,
2243 IOOptionBits options
,
2244 IOByteCount __offset
,
2245 IOByteCount __length
)
2249 if (!(kIOMap64Bit
& options
)) panic("IOGeneralMemoryDescriptor::doMap !64bit");
2250 #endif /* !__LP64__ */
2252 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
2253 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
2254 mach_vm_size_t length
= mapping
->fLength
;
2256 kern_return_t kr
= kIOReturnVMError
;
2257 ipc_port_t sharedMem
= (ipc_port_t
) _memEntry
;
2259 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2260 Ranges vec
= _ranges
;
2262 user_addr_t range0Addr
= 0;
2263 IOByteCount range0Len
= 0;
2266 getAddrLenForInd(range0Addr
, range0Len
, type
, vec
, 0);
2268 // mapping source == dest? (could be much better)
2270 && (mapping
->fAddressMap
== get_task_map(_task
)) && (options
& kIOMapAnywhere
)
2271 && (1 == _rangesCount
) && (0 == offset
)
2272 && range0Addr
&& (length
<= range0Len
) )
2274 mapping
->fAddress
= range0Addr
;
2275 mapping
->fOptions
|= kIOMapStatic
;
2277 return( kIOReturnSuccess
);
2280 if( 0 == sharedMem
) {
2282 vm_size_t size
= ptoa_32(_pages
);
2286 memory_object_size_t actualSize
= size
;
2287 vm_prot_t prot
= VM_PROT_READ
;
2288 if (!(kIOMapReadOnly
& options
))
2289 prot
|= VM_PROT_WRITE
;
2290 else if (kIOMapDefaultCache
!= (options
& kIOMapCacheMask
))
2291 prot
|= VM_PROT_WRITE
;
2293 kr
= mach_make_memory_entry_64(get_task_map(_task
),
2294 &actualSize
, range0Addr
,
2298 if( (KERN_SUCCESS
== kr
) && (actualSize
!= round_page(size
)))
2300 // map will cross vm objects
2302 IOLog("mach_make_memory_entry_64 (%08llx) size (%08llx:%08llx)\n",
2303 range0Addr
, (UInt64
)actualSize
, (UInt64
)size
);
2305 kr
= kIOReturnVMError
;
2306 ipc_port_release_send( sharedMem
);
2307 sharedMem
= MACH_PORT_NULL
;
2309 mach_vm_address_t address
;
2310 mach_vm_size_t pageOffset
= (range0Addr
& PAGE_MASK
);
2312 address
= trunc_page_64(mapping
->fAddress
);
2313 if ((options
& kIOMapAnywhere
) || ((mapping
->fAddress
- address
) == pageOffset
))
2315 kr
= IOMemoryDescriptorMapCopy(mapping
->fAddressMap
,
2316 get_task_map(_task
), range0Addr
,
2318 offset
, &address
, round_page_64(length
+ pageOffset
));
2319 if (kr
== KERN_SUCCESS
)
2320 mapping
->fAddress
= address
+ pageOffset
;
2322 mapping
->fAddress
= NULL
;
2327 { // _task == 0, must be physical
2329 memory_object_t pager
;
2330 unsigned int flags
= 0;
2332 IOPhysicalLength segLen
;
2334 pa
= getPhysicalSegment( offset
, &segLen
, kIOMemoryMapperNone
);
2337 reserved
= IONew( ExpansionData
, 1 );
2341 reserved
->pagerContig
= (1 == _rangesCount
);
2342 reserved
->memory
= this;
2344 /*What cache mode do we need*/
2345 switch(options
& kIOMapCacheMask
) {
2347 case kIOMapDefaultCache
:
2349 flags
= IODefaultCacheBits(pa
);
2350 if (DEVICE_PAGER_CACHE_INHIB
& flags
)
2352 if (DEVICE_PAGER_GUARDED
& flags
)
2353 mapping
->fOptions
|= kIOMapInhibitCache
;
2355 mapping
->fOptions
|= kIOMapWriteCombineCache
;
2357 else if (DEVICE_PAGER_WRITE_THROUGH
& flags
)
2358 mapping
->fOptions
|= kIOMapWriteThruCache
;
2360 mapping
->fOptions
|= kIOMapCopybackCache
;
2363 case kIOMapInhibitCache
:
2364 flags
= DEVICE_PAGER_CACHE_INHIB
|
2365 DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
2368 case kIOMapWriteThruCache
:
2369 flags
= DEVICE_PAGER_WRITE_THROUGH
|
2370 DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
2373 case kIOMapCopybackCache
:
2374 flags
= DEVICE_PAGER_COHERENT
;
2377 case kIOMapWriteCombineCache
:
2378 flags
= DEVICE_PAGER_CACHE_INHIB
|
2379 DEVICE_PAGER_COHERENT
;
2383 flags
|= reserved
->pagerContig
? DEVICE_PAGER_CONTIGUOUS
: 0;
2385 pager
= device_pager_setup( (memory_object_t
) 0, (uintptr_t) reserved
,
2390 kr
= mach_memory_object_memory_entry_64( (host_t
) 1, false /*internal*/,
2391 size
, VM_PROT_READ
| VM_PROT_WRITE
, pager
, &sharedMem
);
2393 assert( KERN_SUCCESS
== kr
);
2394 if( KERN_SUCCESS
!= kr
)
2396 device_pager_deallocate( pager
);
2397 pager
= MACH_PORT_NULL
;
2398 sharedMem
= MACH_PORT_NULL
;
2401 if( pager
&& sharedMem
)
2402 reserved
->devicePager
= pager
;
2404 IODelete( reserved
, ExpansionData
, 1 );
2410 _memEntry
= (void *) sharedMem
;
2417 result
= super::doMap( __addressMap
, __address
,
2418 options
, __offset
, __length
);
2423 IOReturn
IOGeneralMemoryDescriptor::doUnmap(
2424 vm_map_t addressMap
,
2425 IOVirtualAddress __address
,
2426 IOByteCount __length
)
2428 return (super::doUnmap(addressMap
, __address
, __length
));
2431 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2434 #define super OSObject
2436 OSDefineMetaClassAndStructors( IOMemoryMap
, OSObject
)
2438 OSMetaClassDefineReservedUnused(IOMemoryMap
, 0);
2439 OSMetaClassDefineReservedUnused(IOMemoryMap
, 1);
2440 OSMetaClassDefineReservedUnused(IOMemoryMap
, 2);
2441 OSMetaClassDefineReservedUnused(IOMemoryMap
, 3);
2442 OSMetaClassDefineReservedUnused(IOMemoryMap
, 4);
2443 OSMetaClassDefineReservedUnused(IOMemoryMap
, 5);
2444 OSMetaClassDefineReservedUnused(IOMemoryMap
, 6);
2445 OSMetaClassDefineReservedUnused(IOMemoryMap
, 7);
2447 /* ex-inline function implementation */
2448 IOPhysicalAddress
IOMemoryMap::getPhysicalAddress()
2449 { return( getPhysicalSegment( 0, 0 )); }
2451 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2453 bool IOMemoryMap::init(
2455 mach_vm_address_t toAddress
,
2456 IOOptionBits _options
,
2457 mach_vm_size_t _offset
,
2458 mach_vm_size_t _length
)
2466 fAddressMap
= get_task_map(intoTask
);
2469 vm_map_reference(fAddressMap
);
2471 fAddressTask
= intoTask
;
2472 fOptions
= _options
;
2475 fAddress
= toAddress
;
2480 bool IOMemoryMap::setMemoryDescriptor(IOMemoryDescriptor
* _memory
, mach_vm_size_t _offset
)
2487 if( (_offset
+ fLength
) > _memory
->getLength())
2495 if (fMemory
!= _memory
)
2496 fMemory
->removeMapping(this);
2504 struct IOMemoryDescriptorMapAllocRef
2506 ipc_port_t sharedMem
;
2508 mach_vm_offset_t src_address
;
2509 mach_vm_address_t mapped
;
2510 mach_vm_size_t size
;
2511 mach_vm_size_t sourceOffset
;
2512 IOOptionBits options
;
2515 static kern_return_t
IOMemoryDescriptorMapAlloc(vm_map_t map
, void * _ref
)
2517 IOMemoryDescriptorMapAllocRef
* ref
= (IOMemoryDescriptorMapAllocRef
*)_ref
;
2523 vm_prot_t prot
= VM_PROT_READ
2524 | ((ref
->options
& kIOMapReadOnly
) ? 0 : VM_PROT_WRITE
);
2526 // VM system requires write access to change cache mode
2527 if (kIOMapDefaultCache
!= (ref
->options
& kIOMapCacheMask
))
2528 prot
|= VM_PROT_WRITE
;
2530 // set memory entry cache
2531 vm_prot_t memEntryCacheMode
= prot
| MAP_MEM_ONLY
;
2532 switch (ref
->options
& kIOMapCacheMask
)
2534 case kIOMapInhibitCache
:
2535 SET_MAP_MEM(MAP_MEM_IO
, memEntryCacheMode
);
2538 case kIOMapWriteThruCache
:
2539 SET_MAP_MEM(MAP_MEM_WTHRU
, memEntryCacheMode
);
2542 case kIOMapWriteCombineCache
:
2543 SET_MAP_MEM(MAP_MEM_WCOMB
, memEntryCacheMode
);
2546 case kIOMapCopybackCache
:
2547 SET_MAP_MEM(MAP_MEM_COPYBACK
, memEntryCacheMode
);
2550 case kIOMapDefaultCache
:
2552 SET_MAP_MEM(MAP_MEM_NOOP
, memEntryCacheMode
);
2556 vm_size_t unused
= 0;
2558 err
= mach_make_memory_entry( NULL
/*unused*/, &unused
, 0 /*unused*/,
2559 memEntryCacheMode
, NULL
, ref
->sharedMem
);
2560 if (KERN_SUCCESS
!= err
)
2561 IOLog("MAP_MEM_ONLY failed %d\n", err
);
2563 err
= mach_vm_map( map
,
2565 ref
->size
, 0 /* mask */,
2566 (( ref
->options
& kIOMapAnywhere
) ? VM_FLAGS_ANYWHERE
: VM_FLAGS_FIXED
)
2567 | VM_MAKE_TAG(VM_MEMORY_IOKIT
),
2568 ref
->sharedMem
, ref
->sourceOffset
,
2574 if( KERN_SUCCESS
!= err
) {
2579 else if (ref
->src_map
)
2581 vm_prot_t cur_prot
, max_prot
;
2582 err
= mach_vm_remap(map
, &ref
->mapped
, ref
->size
, PAGE_MASK
,
2583 (ref
->options
& kIOMapAnywhere
) ? TRUE
: FALSE
,
2584 ref
->src_map
, ref
->src_address
,
2589 if (KERN_SUCCESS
== err
)
2591 if ((!(VM_PROT_READ
& cur_prot
))
2592 || (!(kIOMapReadOnly
& ref
->options
) && !(VM_PROT_WRITE
& cur_prot
)))
2594 mach_vm_deallocate(map
, ref
->mapped
, ref
->size
);
2595 err
= KERN_PROTECTION_FAILURE
;
2598 if (KERN_SUCCESS
!= err
)
2603 err
= mach_vm_allocate( map
, &ref
->mapped
, ref
->size
,
2604 ((ref
->options
& kIOMapAnywhere
) ? VM_FLAGS_ANYWHERE
: VM_FLAGS_FIXED
)
2605 | VM_MAKE_TAG(VM_MEMORY_IOKIT
) );
2606 if( KERN_SUCCESS
!= err
) {
2610 // we have to make sure that these guys don't get copied if we fork.
2611 err
= vm_inherit( map
, ref
->mapped
, ref
->size
, VM_INHERIT_NONE
);
2612 assert( KERN_SUCCESS
== err
);
2621 IOMemoryDescriptorMapMemEntry(vm_map_t map
, ipc_port_t entry
, IOOptionBits options
, bool pageable
,
2622 mach_vm_size_t offset
,
2623 mach_vm_address_t
* address
, mach_vm_size_t length
)
2626 IOMemoryDescriptorMapAllocRef ref
;
2628 ref
.sharedMem
= entry
;
2630 ref
.sharedMem
= entry
;
2631 ref
.sourceOffset
= trunc_page_64(offset
);
2632 ref
.options
= options
;
2635 if (options
& kIOMapAnywhere
)
2636 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
2639 ref
.mapped
= *address
;
2641 if( ref
.sharedMem
&& (map
== kernel_map
) && pageable
)
2642 err
= IOIteratePageableMaps( ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
2644 err
= IOMemoryDescriptorMapAlloc( map
, &ref
);
2646 *address
= ref
.mapped
;
2651 IOMemoryDescriptorMapCopy(vm_map_t map
,
2653 mach_vm_offset_t src_address
,
2654 IOOptionBits options
,
2655 mach_vm_size_t offset
,
2656 mach_vm_address_t
* address
, mach_vm_size_t length
)
2659 IOMemoryDescriptorMapAllocRef ref
;
2661 ref
.sharedMem
= NULL
;
2662 ref
.src_map
= src_map
;
2663 ref
.src_address
= src_address
;
2664 ref
.sourceOffset
= trunc_page_64(offset
);
2665 ref
.options
= options
;
2668 if (options
& kIOMapAnywhere
)
2669 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
2672 ref
.mapped
= *address
;
2674 if (map
== kernel_map
)
2675 err
= IOIteratePageableMaps(ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
2677 err
= IOMemoryDescriptorMapAlloc(map
, &ref
);
2679 *address
= ref
.mapped
;
2683 IOReturn
IOMemoryDescriptor::doMap(
2684 vm_map_t __addressMap
,
2685 IOVirtualAddress
* __address
,
2686 IOOptionBits options
,
2687 IOByteCount __offset
,
2688 IOByteCount __length
)
2691 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::doMap !64bit");
2692 #endif /* !__LP64__ */
2694 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
2695 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
2696 mach_vm_size_t length
= mapping
->fLength
;
2698 IOReturn err
= kIOReturnSuccess
;
2699 memory_object_t pager
;
2700 mach_vm_size_t pageOffset
;
2701 IOPhysicalAddress sourceAddr
;
2702 unsigned int lock_count
;
2706 sourceAddr
= getPhysicalSegment( offset
, NULL
, _kIOMemorySourceSegment
);
2707 pageOffset
= sourceAddr
- trunc_page( sourceAddr
);
2710 pager
= (memory_object_t
) reserved
->devicePager
;
2712 pager
= MACH_PORT_NULL
;
2714 if ((kIOMapReference
|kIOMapUnique
) == ((kIOMapReference
|kIOMapUnique
) & options
))
2722 err
= kIOReturnNotReadable
;
2726 size
= round_page(mapping
->fLength
+ pageOffset
);
2727 flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
2728 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
2730 if (KERN_SUCCESS
!= memory_object_iopl_request((ipc_port_t
) _memEntry
, 0, &size
, &redirUPL2
,
2735 for (lock_count
= 0;
2736 IORecursiveLockHaveLock(gIOMemoryLock
);
2740 err
= upl_transpose(redirUPL2
, mapping
->fRedirUPL
);
2747 if (kIOReturnSuccess
!= err
)
2749 IOLog("upl_transpose(%x)\n", err
);
2750 err
= kIOReturnSuccess
;
2755 upl_commit(redirUPL2
, NULL
, 0);
2756 upl_deallocate(redirUPL2
);
2760 // swap the memEntries since they now refer to different vm_objects
2761 void * me
= _memEntry
;
2762 _memEntry
= mapping
->fMemory
->_memEntry
;
2763 mapping
->fMemory
->_memEntry
= me
;
2766 err
= handleFault( reserved
->devicePager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
2770 mach_vm_address_t address
;
2772 if (!(options
& kIOMapAnywhere
))
2774 address
= trunc_page_64(mapping
->fAddress
);
2775 if( (mapping
->fAddress
- address
) != pageOffset
)
2777 err
= kIOReturnVMError
;
2782 err
= IOMemoryDescriptorMapMemEntry(mapping
->fAddressMap
, (ipc_port_t
) _memEntry
,
2783 options
, (kIOMemoryBufferPageable
& _flags
),
2784 offset
, &address
, round_page_64(length
+ pageOffset
));
2785 if( err
!= KERN_SUCCESS
)
2788 if (!_memEntry
|| pager
)
2790 err
= handleFault( pager
, mapping
->fAddressMap
, address
, offset
, length
, options
);
2791 if (err
!= KERN_SUCCESS
)
2792 doUnmap( mapping
->fAddressMap
, (IOVirtualAddress
) mapping
, 0 );
2796 if (kIOLogMapping
& gIOKitDebug
)
2797 IOLog("mapping(%x) desc %p @ %lx, map %p, address %qx, offset %qx, length %qx\n",
2798 err
, this, sourceAddr
, mapping
, address
, offset
, length
);
2801 if (err
== KERN_SUCCESS
)
2802 mapping
->fAddress
= address
+ pageOffset
;
2804 mapping
->fAddress
= NULL
;
2812 IOReturn
IOMemoryDescriptor::handleFault(
2814 vm_map_t addressMap
,
2815 mach_vm_address_t address
,
2816 mach_vm_size_t sourceOffset
,
2817 mach_vm_size_t length
,
2818 IOOptionBits options
)
2820 IOReturn err
= kIOReturnSuccess
;
2821 memory_object_t pager
= (memory_object_t
) _pager
;
2822 mach_vm_size_t size
;
2823 mach_vm_size_t bytes
;
2824 mach_vm_size_t page
;
2825 mach_vm_size_t pageOffset
;
2826 mach_vm_size_t pagerOffset
;
2827 IOPhysicalLength segLen
;
2832 if( kIOMemoryRedirected
& _flags
)
2835 IOLog("sleep mem redirect %p, %qx\n", this, sourceOffset
);
2839 } while( kIOMemoryRedirected
& _flags
);
2842 return( kIOReturnSuccess
);
2845 physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
);
2847 pageOffset
= physAddr
- trunc_page_64( physAddr
);
2848 pagerOffset
= sourceOffset
;
2850 size
= length
+ pageOffset
;
2851 physAddr
-= pageOffset
;
2853 segLen
+= pageOffset
;
2857 // in the middle of the loop only map whole pages
2858 if( segLen
>= bytes
)
2860 else if( segLen
!= trunc_page( segLen
))
2861 err
= kIOReturnVMError
;
2862 if( physAddr
!= trunc_page_64( physAddr
))
2863 err
= kIOReturnBadArgument
;
2864 if (kIOReturnSuccess
!= err
)
2868 if( kIOLogMapping
& gIOKitDebug
)
2869 IOLog("IOMemoryMap::map(%p) 0x%qx->0x%qx:0x%qx\n",
2870 addressMap
, address
+ pageOffset
, physAddr
+ pageOffset
,
2871 segLen
- pageOffset
);
2876 if( reserved
&& reserved
->pagerContig
) {
2877 IOPhysicalLength allLen
;
2880 allPhys
= getPhysicalSegment( 0, &allLen
, kIOMemoryMapperNone
);
2882 err
= device_pager_populate_object( pager
, 0, atop_64(allPhys
), round_page(allLen
) );
2888 (page
< segLen
) && (KERN_SUCCESS
== err
);
2891 err
= device_pager_populate_object(pager
, pagerOffset
,
2892 (ppnum_t
)(atop_64(physAddr
+ page
)), page_size
);
2893 pagerOffset
+= page_size
;
2896 assert( KERN_SUCCESS
== err
);
2901 // This call to vm_fault causes an early pmap level resolution
2902 // of the mappings created above for kernel mappings, since
2903 // faulting in later can't take place from interrupt level.
2905 /* *** Temporary Workaround *** */
2907 if ((addressMap
== kernel_map
) && !(kIOMemoryRedirected
& _flags
))
2909 vm_fault(addressMap
,
2910 (vm_map_offset_t
)address
,
2911 VM_PROT_READ
|VM_PROT_WRITE
,
2912 FALSE
, THREAD_UNINT
, NULL
,
2913 (vm_map_offset_t
)0);
2916 /* *** Temporary Workaround *** */
2919 sourceOffset
+= segLen
- pageOffset
;
2925 while (bytes
&& (physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
)));
2928 err
= kIOReturnBadArgument
;
2933 IOReturn
IOMemoryDescriptor::doUnmap(
2934 vm_map_t addressMap
,
2935 IOVirtualAddress __address
,
2936 IOByteCount __length
)
2939 mach_vm_address_t address
;
2940 mach_vm_size_t length
;
2944 address
= __address
;
2949 addressMap
= ((IOMemoryMap
*) __address
)->fAddressMap
;
2950 address
= ((IOMemoryMap
*) __address
)->fAddress
;
2951 length
= ((IOMemoryMap
*) __address
)->fLength
;
2954 if( _memEntry
&& (addressMap
== kernel_map
) && (kIOMemoryBufferPageable
& _flags
))
2955 addressMap
= IOPageableMapForAddress( address
);
2958 if( kIOLogMapping
& gIOKitDebug
)
2959 IOLog("IOMemoryDescriptor::doUnmap map %p, 0x%qx:0x%qx\n",
2960 addressMap
, address
, length
);
2963 err
= mach_vm_deallocate( addressMap
, address
, length
);
2968 IOReturn
IOMemoryDescriptor::redirect( task_t safeTask
, bool doRedirect
)
2970 IOReturn err
= kIOReturnSuccess
;
2971 IOMemoryMap
* mapping
= 0;
2977 _flags
|= kIOMemoryRedirected
;
2979 _flags
&= ~kIOMemoryRedirected
;
2982 if( (iter
= OSCollectionIterator::withCollection( _mappings
))) {
2983 while( (mapping
= (IOMemoryMap
*) iter
->getNextObject()))
2984 mapping
->redirect( safeTask
, doRedirect
);
2998 // temporary binary compatibility
2999 IOSubMemoryDescriptor
* subMem
;
3000 if( (subMem
= OSDynamicCast( IOSubMemoryDescriptor
, this)))
3001 err
= subMem
->redirect( safeTask
, doRedirect
);
3003 err
= kIOReturnSuccess
;
3004 #endif /* !__LP64__ */
3009 IOReturn
IOMemoryMap::redirect( task_t safeTask
, bool doRedirect
)
3011 IOReturn err
= kIOReturnSuccess
;
3014 // err = ((IOMemoryMap *)superMap)->redirect( safeTask, doRedirect );
3026 if ((!safeTask
|| (get_task_map(safeTask
) != fAddressMap
))
3027 && (0 == (fOptions
& kIOMapStatic
)))
3029 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3030 err
= kIOReturnSuccess
;
3032 IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect
, this, fAddress
, fLength
, fAddressMap
);
3035 else if (kIOMapWriteCombineCache
== (fOptions
& kIOMapCacheMask
))
3037 IOOptionBits newMode
;
3038 newMode
= (fOptions
& ~kIOMapCacheMask
) | (doRedirect
? kIOMapInhibitCache
: kIOMapWriteCombineCache
);
3039 IOProtectCacheMode(fAddressMap
, fAddress
, fLength
, newMode
);
3046 if ((((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3047 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3049 && (doRedirect
!= (0 != (fMemory
->_flags
& kIOMemoryRedirected
))))
3050 fMemory
->redirect(safeTask
, doRedirect
);
3055 IOReturn
IOMemoryMap::unmap( void )
3061 if( fAddress
&& fAddressMap
&& (0 == fSuperMap
) && fMemory
3062 && (0 == (fOptions
& kIOMapStatic
))) {
3064 err
= fMemory
->doUnmap(fAddressMap
, (IOVirtualAddress
) this, 0);
3067 err
= kIOReturnSuccess
;
3071 vm_map_deallocate(fAddressMap
);
3082 void IOMemoryMap::taskDied( void )
3085 if (fUserClientUnmap
)
3088 vm_map_deallocate(fAddressMap
);
3096 IOReturn
IOMemoryMap::userClientUnmap( void )
3098 fUserClientUnmap
= true;
3099 return (kIOReturnSuccess
);
3102 // Overload the release mechanism. All mappings must be a member
3103 // of a memory descriptors _mappings set. This means that we
3104 // always have 2 references on a mapping. When either of these mappings
3105 // are released we need to free ourselves.
3106 void IOMemoryMap::taggedRelease(const void *tag
) const
3109 super::taggedRelease(tag
, 2);
3113 void IOMemoryMap::free()
3120 fMemory
->removeMapping(this);
3125 if (fOwner
&& (fOwner
!= fMemory
))
3128 fOwner
->removeMapping(this);
3133 fSuperMap
->release();
3136 upl_commit(fRedirUPL
, NULL
, 0);
3137 upl_deallocate(fRedirUPL
);
3143 IOByteCount
IOMemoryMap::getLength()
3148 IOVirtualAddress
IOMemoryMap::getVirtualAddress()
3152 fSuperMap
->getVirtualAddress();
3153 else if (fAddressMap
3154 && vm_map_is_64bit(fAddressMap
)
3155 && (sizeof(IOVirtualAddress
) < 8))
3157 OSReportWithBacktrace("IOMemoryMap::getVirtualAddress(0x%qx) called on 64b map; use ::getAddress()", fAddress
);
3159 #endif /* !__LP64__ */
3165 mach_vm_address_t
IOMemoryMap::getAddress()
3170 mach_vm_size_t
IOMemoryMap::getSize()
3174 #endif /* !__LP64__ */
3177 task_t
IOMemoryMap::getAddressTask()
3180 return( fSuperMap
->getAddressTask());
3182 return( fAddressTask
);
3185 IOOptionBits
IOMemoryMap::getMapOptions()
3190 IOMemoryDescriptor
* IOMemoryMap::getMemoryDescriptor()
3195 IOMemoryMap
* IOMemoryMap::copyCompatible(
3196 IOMemoryMap
* newMapping
)
3198 task_t task
= newMapping
->getAddressTask();
3199 mach_vm_address_t toAddress
= newMapping
->fAddress
;
3200 IOOptionBits _options
= newMapping
->fOptions
;
3201 mach_vm_size_t _offset
= newMapping
->fOffset
;
3202 mach_vm_size_t _length
= newMapping
->fLength
;
3204 if( (!task
) || (!fAddressMap
) || (fAddressMap
!= get_task_map(task
)))
3206 if( (fOptions
^ _options
) & kIOMapReadOnly
)
3208 if( (kIOMapDefaultCache
!= (_options
& kIOMapCacheMask
))
3209 && ((fOptions
^ _options
) & kIOMapCacheMask
))
3212 if( (0 == (_options
& kIOMapAnywhere
)) && (fAddress
!= toAddress
))
3215 if( _offset
< fOffset
)
3220 if( (_offset
+ _length
) > fLength
)
3224 if( (fLength
== _length
) && (!_offset
))
3226 newMapping
->release();
3231 newMapping
->fSuperMap
= this;
3232 newMapping
->fOffset
= _offset
;
3233 newMapping
->fAddress
= fAddress
+ _offset
;
3236 return( newMapping
);
3241 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
, IOOptionBits _options
)
3242 #else /* !__LP64__ */
3243 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
)
3244 #endif /* !__LP64__ */
3246 IOPhysicalAddress address
;
3250 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
, _options
);
3251 #else /* !__LP64__ */
3252 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
);
3253 #endif /* !__LP64__ */
3259 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3262 #define super OSObject
3264 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3266 void IOMemoryDescriptor::initialize( void )
3268 if( 0 == gIOMemoryLock
)
3269 gIOMemoryLock
= IORecursiveLockAlloc();
3271 IORegistryEntry::getRegistryRoot()->setProperty(kIOMaximumMappedIOByteCountKey
,
3272 ptoa_64(gIOMaximumMappedIOPageCount
), 64);
3276 mapper
= new IOCopyMapper
;
3279 if (mapper
->init() && mapper
->start(NULL
))
3280 gIOCopyMapper
= (IOCopyMapper
*) mapper
;
3286 gIOLastPage
= IOGetLastPageNumber();
3289 void IOMemoryDescriptor::free( void )
3292 _mappings
->release();
3297 IOMemoryMap
* IOMemoryDescriptor::setMapping(
3299 IOVirtualAddress mapAddress
,
3300 IOOptionBits options
)
3302 return (createMappingInTask( intoTask
, mapAddress
,
3303 options
| kIOMapStatic
,
3307 IOMemoryMap
* IOMemoryDescriptor::map(
3308 IOOptionBits options
)
3310 return (createMappingInTask( kernel_task
, 0,
3311 options
| kIOMapAnywhere
,
3316 IOMemoryMap
* IOMemoryDescriptor::map(
3318 IOVirtualAddress atAddress
,
3319 IOOptionBits options
,
3321 IOByteCount length
)
3323 if ((!(kIOMapAnywhere
& options
)) && vm_map_is_64bit(get_task_map(intoTask
)))
3325 OSReportWithBacktrace("IOMemoryDescriptor::map() in 64b task, use ::createMappingInTask()");
3329 return (createMappingInTask(intoTask
, atAddress
,
3330 options
, offset
, length
));
3332 #endif /* !__LP64__ */
3334 IOMemoryMap
* IOMemoryDescriptor::createMappingInTask(
3336 mach_vm_address_t atAddress
,
3337 IOOptionBits options
,
3338 mach_vm_size_t offset
,
3339 mach_vm_size_t length
)
3341 IOMemoryMap
* result
;
3342 IOMemoryMap
* mapping
;
3345 length
= getLength();
3347 mapping
= new IOMemoryMap
;
3350 && !mapping
->init( intoTask
, atAddress
,
3351 options
, offset
, length
)) {
3357 result
= makeMapping(this, intoTask
, (IOVirtualAddress
) mapping
, options
| kIOMap64Bit
, 0, 0);
3363 IOLog("createMappingInTask failed desc %p, addr %qx, options %lx, offset %qx, length %qx\n",
3364 this, atAddress
, options
, offset
, length
);
3370 #ifndef __LP64__ // there is only a 64 bit version for LP64
3371 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
3372 IOOptionBits options
,
3375 return (redirect(newBackingMemory
, options
, (mach_vm_size_t
)offset
));
3379 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
3380 IOOptionBits options
,
3381 mach_vm_size_t offset
)
3383 IOReturn err
= kIOReturnSuccess
;
3384 IOMemoryDescriptor
* physMem
= 0;
3388 if (fAddress
&& fAddressMap
) do
3390 if (((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3391 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3399 vm_size_t size
= round_page(fLength
);
3400 int flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3401 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
3402 if (KERN_SUCCESS
!= memory_object_iopl_request((ipc_port_t
) fMemory
->_memEntry
, 0, &size
, &fRedirUPL
,
3409 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3411 physMem
->redirect(0, true);
3415 if (newBackingMemory
)
3417 if (newBackingMemory
!= fMemory
)
3420 if (this != newBackingMemory
->makeMapping(newBackingMemory
, fAddressTask
, (IOVirtualAddress
) this,
3421 options
| kIOMapUnique
| kIOMapReference
| kIOMap64Bit
,
3423 err
= kIOReturnError
;
3427 upl_commit(fRedirUPL
, NULL
, 0);
3428 upl_deallocate(fRedirUPL
);
3431 if (false && physMem
)
3432 physMem
->redirect(0, false);
3445 IOMemoryMap
* IOMemoryDescriptor::makeMapping(
3446 IOMemoryDescriptor
* owner
,
3448 IOVirtualAddress __address
,
3449 IOOptionBits options
,
3450 IOByteCount __offset
,
3451 IOByteCount __length
)
3454 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::makeMapping !64bit");
3455 #endif /* !__LP64__ */
3457 IOMemoryDescriptor
* mapDesc
= 0;
3458 IOMemoryMap
* result
= 0;
3461 IOMemoryMap
* mapping
= (IOMemoryMap
*) __address
;
3462 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3463 mach_vm_size_t length
= mapping
->fLength
;
3465 mapping
->fOffset
= offset
;
3471 if (kIOMapStatic
& options
)
3474 addMapping(mapping
);
3475 mapping
->setMemoryDescriptor(this, 0);
3479 if (kIOMapUnique
& options
)
3481 IOPhysicalAddress phys
;
3482 IOByteCount physLen
;
3484 // if (owner != this) continue;
3486 if (((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3487 || ((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3489 phys
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
3490 if (!phys
|| (physLen
< length
))
3493 mapDesc
= IOMemoryDescriptor::withAddressRange(
3494 phys
, length
, getDirection() | kIOMemoryMapperNone
, NULL
);
3498 mapping
->fOffset
= offset
;
3503 // look for a compatible existing mapping
3504 if( (iter
= OSCollectionIterator::withCollection(_mappings
)))
3506 IOMemoryMap
* lookMapping
;
3507 while ((lookMapping
= (IOMemoryMap
*) iter
->getNextObject()))
3509 if ((result
= lookMapping
->copyCompatible(mapping
)))
3512 result
->setMemoryDescriptor(this, offset
);
3518 if (result
|| (options
& kIOMapReference
))
3528 kr
= mapDesc
->doMap( 0, (IOVirtualAddress
*) &mapping
, options
, 0, 0 );
3529 if (kIOReturnSuccess
== kr
)
3532 mapDesc
->addMapping(result
);
3533 result
->setMemoryDescriptor(mapDesc
, offset
);
3551 void IOMemoryDescriptor::addMapping(
3552 IOMemoryMap
* mapping
)
3557 _mappings
= OSSet::withCapacity(1);
3559 _mappings
->setObject( mapping
);
3563 void IOMemoryDescriptor::removeMapping(
3564 IOMemoryMap
* mapping
)
3567 _mappings
->removeObject( mapping
);
3571 // obsolete initializers
3572 // - initWithOptions is the designated initializer
3574 IOMemoryDescriptor::initWithAddress(void * address
,
3576 IODirection direction
)
3582 IOMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
3584 IODirection direction
,
3591 IOMemoryDescriptor::initWithPhysicalAddress(
3592 IOPhysicalAddress address
,
3594 IODirection direction
)
3600 IOMemoryDescriptor::initWithRanges(
3601 IOVirtualRange
* ranges
,
3603 IODirection direction
,
3611 IOMemoryDescriptor::initWithPhysicalRanges( IOPhysicalRange
* ranges
,
3613 IODirection direction
,
3619 void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
3620 IOByteCount
* lengthOfSegment
)
3624 #endif /* !__LP64__ */
3626 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3628 bool IOGeneralMemoryDescriptor::serialize(OSSerialize
* s
) const
3630 OSSymbol
const *keys
[2];
3631 OSObject
*values
[2];
3633 user_addr_t address
;
3636 unsigned int index
, nRanges
;
3639 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3641 if (s
== NULL
) return false;
3642 if (s
->previouslySerialized(this)) return true;
3644 // Pretend we are an array.
3645 if (!s
->addXMLStartTag(this, "array")) return false;
3647 nRanges
= _rangesCount
;
3648 vcopy
= (SerData
*) IOMalloc(sizeof(SerData
) * nRanges
);
3649 if (vcopy
== 0) return false;
3651 keys
[0] = OSSymbol::withCString("address");
3652 keys
[1] = OSSymbol::withCString("length");
3655 values
[0] = values
[1] = 0;
3657 // From this point on we can go to bail.
3659 // Copy the volatile data so we don't have to allocate memory
3660 // while the lock is held.
3662 if (nRanges
== _rangesCount
) {
3663 Ranges vec
= _ranges
;
3664 for (index
= 0; index
< nRanges
; index
++) {
3665 user_addr_t addr
; IOByteCount len
;
3666 getAddrLenForInd(addr
, len
, type
, vec
, index
);
3667 vcopy
[index
].address
= addr
;
3668 vcopy
[index
].length
= len
;
3671 // The descriptor changed out from under us. Give up.
3678 for (index
= 0; index
< nRanges
; index
++)
3680 user_addr_t addr
= vcopy
[index
].address
;
3681 IOByteCount len
= (IOByteCount
) vcopy
[index
].length
;
3683 OSNumber::withNumber(addr
, (((UInt64
) addr
) >> 32)? 64 : 32);
3684 if (values
[0] == 0) {
3688 values
[1] = OSNumber::withNumber(len
, sizeof(len
) * 8);
3689 if (values
[1] == 0) {
3693 OSDictionary
*dict
= OSDictionary::withObjects((const OSObject
**)values
, (const OSSymbol
**)keys
, 2);
3698 values
[0]->release();
3699 values
[1]->release();
3700 values
[0] = values
[1] = 0;
3702 result
= dict
->serialize(s
);
3708 result
= s
->addXMLEndTag("array");
3712 values
[0]->release();
3714 values
[1]->release();
3720 IOFree(vcopy
, sizeof(SerData
) * nRanges
);
3724 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3726 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 0);
3728 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 1);
3729 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 2);
3730 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 3);
3731 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 4);
3732 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 5);
3733 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 6);
3734 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 7);
3735 #else /* !__LP64__ */
3736 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 1);
3737 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 2);
3738 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 3);
3739 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 4);
3740 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 5);
3741 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 6);
3742 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 7);
3743 #endif /* !__LP64__ */
3744 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 8);
3745 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 9);
3746 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 10);
3747 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 11);
3748 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 12);
3749 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 13);
3750 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 14);
3751 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 15);
3753 /* ex-inline function implementation */
3755 IOMemoryDescriptor::getPhysicalAddress()
3756 { return( getPhysicalSegment( 0, 0 )); }