2 * Copyright (c) 1998-2007 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * Copyright (c) 1998 Apple Computer, Inc. All rights reserved.
36 #include <sys/cdefs.h>
38 #include <IOKit/assert.h>
39 #include <IOKit/system.h>
40 #include <IOKit/IOLib.h>
41 #include <IOKit/IOMemoryDescriptor.h>
42 #include <IOKit/IOMapper.h>
43 #include <IOKit/IODMACommand.h>
44 #include <IOKit/IOKitKeysPrivate.h>
47 #include <IOKit/IOSubMemoryDescriptor.h>
48 #endif /* !__LP64__ */
50 #include <IOKit/IOKitDebug.h>
51 #include <libkern/OSDebug.h>
53 #include "IOKitKernelInternal.h"
55 #include <libkern/c++/OSContainers.h>
56 #include <libkern/c++/OSDictionary.h>
57 #include <libkern/c++/OSArray.h>
58 #include <libkern/c++/OSSymbol.h>
59 #include <libkern/c++/OSNumber.h>
65 #include <vm/vm_pageout.h>
66 #include <mach/memory_object_types.h>
67 #include <device/device_port.h>
69 #include <mach/vm_prot.h>
70 #include <mach/mach_vm.h>
71 #include <vm/vm_fault.h>
72 #include <vm/vm_protos.h>
74 extern ppnum_t
pmap_find_phys(pmap_t pmap
, addr64_t va
);
75 extern void ipc_port_release_send(ipc_port_t port
);
78 memory_object_iopl_request(
80 memory_object_offset_t offset
,
83 upl_page_info_array_t user_page_list
,
84 unsigned int *page_list_count
,
87 unsigned int IOTranslateCacheBits(struct phys_entry
*pp
);
91 #define kIOMaximumMappedIOByteCount (512*1024*1024)
93 #define kIOMapperWaitSystem ((IOMapper *) 1)
95 static IOMapper
* gIOSystemMapper
= NULL
;
97 static ppnum_t gIOMaximumMappedIOPageCount
= atop_32(kIOMaximumMappedIOByteCount
);
101 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
103 OSDefineMetaClassAndAbstractStructors( IOMemoryDescriptor
, OSObject
)
105 #define super IOMemoryDescriptor
107 OSDefineMetaClassAndStructors(IOGeneralMemoryDescriptor
, IOMemoryDescriptor
)
109 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
111 static IORecursiveLock
* gIOMemoryLock
;
113 #define LOCK IORecursiveLockLock( gIOMemoryLock)
114 #define UNLOCK IORecursiveLockUnlock( gIOMemoryLock)
115 #define SLEEP IORecursiveLockSleep( gIOMemoryLock, (void *)this, THREAD_UNINT)
117 IORecursiveLockWakeup( gIOMemoryLock, (void *)this, /* one-thread */ false)
120 #define DEBG(fmt, args...) { kprintf(fmt, ## args); }
122 #define DEBG(fmt, args...) {}
125 #define IOMD_DEBUG_DMAACTIVE 1
127 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
129 // Some data structures and accessor macros used by the initWithOptions
132 enum ioPLBlockFlags
{
133 kIOPLOnDevice
= 0x00000001,
134 kIOPLExternUPL
= 0x00000002,
137 struct typePersMDData
139 const IOGeneralMemoryDescriptor
*fMD
;
140 ipc_port_t fMemEntry
;
145 vm_address_t fPageInfo
; // Pointer to page list or index into it
146 uint32_t fIOMDOffset
; // The offset of this iopl in descriptor
147 ppnum_t fMappedPage
; // Page number of first page in this iopl
148 unsigned int fPageOffset
; // Offset within first page of iopl
149 unsigned int fFlags
; // Flags
154 uint8_t fDMAMapNumAddressBits
;
155 uint64_t fDMAMapAlignment
;
156 addr64_t fMappedBase
;
157 uint64_t fPreparationID
;
158 unsigned int fPageCnt
;
160 // align arrays to 8 bytes so following macros work
163 upl_page_info_t fPageList
[1]; /* variable length */
164 ioPLBlock fBlocks
[1]; /* variable length */
167 #define getDataP(osd) ((ioGMDData *) (osd)->getBytesNoCopy())
168 #define getIOPLList(d) ((ioPLBlock *) (void *)&(d->fPageList[d->fPageCnt]))
169 #define getNumIOPL(osd, d) \
170 (((osd)->getLength() - ((char *) getIOPLList(d) - (char *) d)) / sizeof(ioPLBlock))
171 #define getPageList(d) (&(d->fPageList[0]))
172 #define computeDataSize(p, u) \
173 (offsetof(ioGMDData, fPageList) + p * sizeof(upl_page_info_t) + u * sizeof(ioPLBlock))
176 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
178 #define next_page(a) ( trunc_page(a) + PAGE_SIZE )
183 kern_return_t
device_data_action(
184 uintptr_t device_handle
,
185 ipc_port_t device_pager
,
186 vm_prot_t protection
,
187 vm_object_offset_t offset
,
191 IOMemoryDescriptorReserved
* ref
= (IOMemoryDescriptorReserved
*) device_handle
;
192 IOMemoryDescriptor
* memDesc
;
195 memDesc
= ref
->dp
.memory
;
199 kr
= memDesc
->handleFault( device_pager
, 0, 0,
200 offset
, size
, kIOMapDefaultCache
/*?*/);
210 kern_return_t
device_close(
211 uintptr_t device_handle
)
213 IOMemoryDescriptorReserved
* ref
= (IOMemoryDescriptorReserved
*) device_handle
;
215 IODelete( ref
, IOMemoryDescriptorReserved
, 1 );
217 return( kIOReturnSuccess
);
221 // Note this inline function uses C++ reference arguments to return values
222 // This means that pointers are not passed and NULLs don't have to be
223 // checked for as a NULL reference is illegal.
225 getAddrLenForInd(user_addr_t
&addr
, IOPhysicalLength
&len
, // Output variables
226 UInt32 type
, IOGeneralMemoryDescriptor::Ranges r
, UInt32 ind
)
228 assert(kIOMemoryTypeUIO
== type
229 || kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
230 || kIOMemoryTypePhysical
== type
|| kIOMemoryTypePhysical64
== type
);
231 if (kIOMemoryTypeUIO
== type
) {
233 uio_getiov((uio_t
) r
.uio
, ind
, &addr
, &us
); len
= us
;
236 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
)) {
237 IOAddressRange cur
= r
.v64
[ind
];
241 #endif /* !__LP64__ */
243 IOVirtualRange cur
= r
.v
[ind
];
249 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
252 IOMemoryDescriptor::withAddress(void * address
,
254 IODirection direction
)
256 return IOMemoryDescriptor::
257 withAddressRange((IOVirtualAddress
) address
, length
, direction
| kIOMemoryAutoPrepare
, kernel_task
);
262 IOMemoryDescriptor::withAddress(IOVirtualAddress address
,
264 IODirection direction
,
267 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
270 if (that
->initWithAddress(address
, length
, direction
, task
))
277 #endif /* !__LP64__ */
280 IOMemoryDescriptor::withPhysicalAddress(
281 IOPhysicalAddress address
,
283 IODirection direction
)
285 return (IOMemoryDescriptor::withAddressRange(address
, length
, direction
, TASK_NULL
));
290 IOMemoryDescriptor::withRanges( IOVirtualRange
* ranges
,
292 IODirection direction
,
296 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
299 if (that
->initWithRanges(ranges
, withCount
, direction
, task
, asReference
))
306 #endif /* !__LP64__ */
309 IOMemoryDescriptor::withAddressRange(mach_vm_address_t address
,
310 mach_vm_size_t length
,
311 IOOptionBits options
,
314 IOAddressRange range
= { address
, length
};
315 return (IOMemoryDescriptor::withAddressRanges(&range
, 1, options
, task
));
319 IOMemoryDescriptor::withAddressRanges(IOAddressRange
* ranges
,
321 IOOptionBits options
,
324 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
328 options
|= kIOMemoryTypeVirtual64
;
330 options
|= kIOMemoryTypePhysical64
;
332 if (that
->initWithOptions(ranges
, rangeCount
, 0, task
, options
, /* mapper */ 0))
345 * Create a new IOMemoryDescriptor. The buffer is made up of several
346 * virtual address ranges, from a given task.
348 * Passing the ranges as a reference will avoid an extra allocation.
351 IOMemoryDescriptor::withOptions(void * buffers
,
358 IOGeneralMemoryDescriptor
*self
= new IOGeneralMemoryDescriptor
;
361 && !self
->initWithOptions(buffers
, count
, offset
, task
, opts
, mapper
))
370 bool IOMemoryDescriptor::initWithOptions(void * buffers
,
374 IOOptionBits options
,
382 IOMemoryDescriptor::withPhysicalRanges( IOPhysicalRange
* ranges
,
384 IODirection direction
,
387 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
390 if (that
->initWithPhysicalRanges(ranges
, withCount
, direction
, asReference
))
399 IOMemoryDescriptor::withSubRange(IOMemoryDescriptor
* of
,
402 IODirection direction
)
404 return (IOSubMemoryDescriptor::withSubRange(of
, offset
, length
, direction
| kIOMemoryThreadSafe
));
406 #endif /* !__LP64__ */
409 IOMemoryDescriptor::withPersistentMemoryDescriptor(IOMemoryDescriptor
*originalMD
)
411 IOGeneralMemoryDescriptor
*origGenMD
=
412 OSDynamicCast(IOGeneralMemoryDescriptor
, originalMD
);
415 return IOGeneralMemoryDescriptor::
416 withPersistentMemoryDescriptor(origGenMD
);
422 IOGeneralMemoryDescriptor::withPersistentMemoryDescriptor(IOGeneralMemoryDescriptor
*originalMD
)
424 ipc_port_t sharedMem
= (ipc_port_t
) originalMD
->createNamedEntry();
429 if (sharedMem
== originalMD
->_memEntry
) {
430 originalMD
->retain(); // Add a new reference to ourselves
431 ipc_port_release_send(sharedMem
); // Remove extra send right
435 IOGeneralMemoryDescriptor
* self
= new IOGeneralMemoryDescriptor
;
436 typePersMDData initData
= { originalMD
, sharedMem
};
439 && !self
->initWithOptions(&initData
, 1, 0, 0, kIOMemoryTypePersistentMD
, 0)) {
446 void *IOGeneralMemoryDescriptor::createNamedEntry()
449 ipc_port_t sharedMem
;
451 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
453 user_addr_t range0Addr
;
454 IOByteCount range0Len
;
455 getAddrLenForInd(range0Addr
, range0Len
, type
, _ranges
, 0);
456 range0Addr
= trunc_page_64(range0Addr
);
458 vm_size_t size
= ptoa_32(_pages
);
459 vm_address_t kernelPage
= (vm_address_t
) range0Addr
;
461 vm_map_t theMap
= ((_task
== kernel_task
)
462 && (kIOMemoryBufferPageable
& _flags
))
463 ? IOPageableMapForAddress(kernelPage
)
464 : get_task_map(_task
);
466 memory_object_size_t actualSize
= size
;
467 vm_prot_t prot
= VM_PROT_READ
;
468 if (kIODirectionOut
!= (kIODirectionOutIn
& _flags
))
469 prot
|= VM_PROT_WRITE
;
472 prot
|= MAP_MEM_NAMED_REUSE
;
474 error
= mach_make_memory_entry_64(theMap
,
475 &actualSize
, range0Addr
, prot
, &sharedMem
, (ipc_port_t
) _memEntry
);
477 if (KERN_SUCCESS
== error
) {
478 if (actualSize
== size
) {
482 IOLog("IOGMD::mach_make_memory_entry_64 (%08llx) size (%08llx:%08llx)\n",
483 (UInt64
)range0Addr
, (UInt64
)actualSize
, (UInt64
)size
);
485 ipc_port_release_send( sharedMem
);
489 return MACH_PORT_NULL
;
494 IOGeneralMemoryDescriptor::initWithAddress(void * address
,
495 IOByteCount withLength
,
496 IODirection withDirection
)
498 _singleRange
.v
.address
= (vm_offset_t
) address
;
499 _singleRange
.v
.length
= withLength
;
501 return initWithRanges(&_singleRange
.v
, 1, withDirection
, kernel_task
, true);
505 IOGeneralMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
506 IOByteCount withLength
,
507 IODirection withDirection
,
510 _singleRange
.v
.address
= address
;
511 _singleRange
.v
.length
= withLength
;
513 return initWithRanges(&_singleRange
.v
, 1, withDirection
, withTask
, true);
517 IOGeneralMemoryDescriptor::initWithPhysicalAddress(
518 IOPhysicalAddress address
,
519 IOByteCount withLength
,
520 IODirection withDirection
)
522 _singleRange
.p
.address
= address
;
523 _singleRange
.p
.length
= withLength
;
525 return initWithPhysicalRanges( &_singleRange
.p
, 1, withDirection
, true);
529 IOGeneralMemoryDescriptor::initWithPhysicalRanges(
530 IOPhysicalRange
* ranges
,
532 IODirection direction
,
535 IOOptionBits mdOpts
= direction
| kIOMemoryTypePhysical
;
538 mdOpts
|= kIOMemoryAsReference
;
540 return initWithOptions(ranges
, count
, 0, 0, mdOpts
, /* mapper */ 0);
544 IOGeneralMemoryDescriptor::initWithRanges(
545 IOVirtualRange
* ranges
,
547 IODirection direction
,
551 IOOptionBits mdOpts
= direction
;
554 mdOpts
|= kIOMemoryAsReference
;
557 mdOpts
|= kIOMemoryTypeVirtual
;
559 // Auto-prepare if this is a kernel memory descriptor as very few
560 // clients bother to prepare() kernel memory.
561 // But it was not enforced so what are you going to do?
562 if (task
== kernel_task
)
563 mdOpts
|= kIOMemoryAutoPrepare
;
566 mdOpts
|= kIOMemoryTypePhysical
;
568 return initWithOptions(ranges
, count
, 0, task
, mdOpts
, /* mapper */ 0);
570 #endif /* !__LP64__ */
575 * IOMemoryDescriptor. The buffer is made up of several virtual address ranges,
576 * from a given task, several physical ranges, an UPL from the ubc
577 * system or a uio (may be 64bit) from the BSD subsystem.
579 * Passing the ranges as a reference will avoid an extra allocation.
581 * An IOMemoryDescriptor can be re-used by calling initWithOptions again on an
582 * existing instance -- note this behavior is not commonly supported in other
583 * I/O Kit classes, although it is supported here.
587 IOGeneralMemoryDescriptor::initWithOptions(void * buffers
,
591 IOOptionBits options
,
594 IOOptionBits type
= options
& kIOMemoryTypeMask
;
598 && (kIOMemoryTypeVirtual
== type
)
599 && vm_map_is_64bit(get_task_map(task
))
600 && ((IOVirtualRange
*) buffers
)->address
)
602 OSReportWithBacktrace("IOMemoryDescriptor: attempt to create 32b virtual in 64b task, use ::withAddressRange()");
605 #endif /* !__LP64__ */
607 // Grab the original MD's configuation data to initialse the
608 // arguments to this function.
609 if (kIOMemoryTypePersistentMD
== type
) {
611 typePersMDData
*initData
= (typePersMDData
*) buffers
;
612 const IOGeneralMemoryDescriptor
*orig
= initData
->fMD
;
613 ioGMDData
*dataP
= getDataP(orig
->_memoryEntries
);
615 // Only accept persistent memory descriptors with valid dataP data.
616 assert(orig
->_rangesCount
== 1);
617 if ( !(orig
->_flags
& kIOMemoryPersistent
) || !dataP
)
620 _memEntry
= initData
->fMemEntry
; // Grab the new named entry
621 options
= orig
->_flags
& ~kIOMemoryAsReference
;
622 type
= options
& kIOMemoryTypeMask
;
623 buffers
= orig
->_ranges
.v
;
624 count
= orig
->_rangesCount
;
626 // Now grab the original task and whatever mapper was previously used
628 mapper
= dataP
->fMapper
;
630 // We are ready to go through the original initialisation now
634 case kIOMemoryTypeUIO
:
635 case kIOMemoryTypeVirtual
:
637 case kIOMemoryTypeVirtual64
:
638 #endif /* !__LP64__ */
644 case kIOMemoryTypePhysical
: // Neither Physical nor UPL should have a task
646 case kIOMemoryTypePhysical64
:
647 #endif /* !__LP64__ */
648 case kIOMemoryTypeUPL
:
652 return false; /* bad argument */
659 * We can check the _initialized instance variable before having ever set
660 * it to an initial value because I/O Kit guarantees that all our instance
661 * variables are zeroed on an object's allocation.
666 * An existing memory descriptor is being retargeted to point to
667 * somewhere else. Clean up our present state.
669 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
670 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
675 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
677 if (kIOMemoryTypeUIO
== type
)
678 uio_free((uio_t
) _ranges
.v
);
680 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
681 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
682 #endif /* !__LP64__ */
684 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
689 ipc_port_release_send((ipc_port_t
) _memEntry
);
693 _mappings
->flushCollection();
701 // Grab the appropriate mapper
702 if (kIOMemoryHostOnly
& options
) options
|= kIOMemoryMapperNone
;
703 if (kIOMemoryMapperNone
& options
)
704 mapper
= 0; // No Mapper
705 else if (mapper
== kIOMapperSystem
) {
706 IOMapper::checkForSystemMapper();
707 gIOSystemMapper
= mapper
= IOMapper::gSystem
;
710 // Temp binary compatibility for kIOMemoryThreadSafe
711 if (kIOMemoryReserved6156215
& options
)
713 options
&= ~kIOMemoryReserved6156215
;
714 options
|= kIOMemoryThreadSafe
;
716 // Remove the dynamic internal use flags from the initial setting
717 options
&= ~(kIOMemoryPreparedReadOnly
);
722 _direction
= (IODirection
) (_flags
& kIOMemoryDirectionMask
);
723 #endif /* !__LP64__ */
725 __iomd_reservedA
= 0;
726 __iomd_reservedB
= 0;
729 if (kIOMemoryThreadSafe
& options
)
732 _prepareLock
= IOLockAlloc();
734 else if (_prepareLock
)
736 IOLockFree(_prepareLock
);
740 if (kIOMemoryTypeUPL
== type
) {
743 unsigned int dataSize
= computeDataSize(/* pages */ 0, /* upls */ 1);
745 if (!initMemoryEntries(dataSize
, mapper
)) return (false);
746 dataP
= getDataP(_memoryEntries
);
749 // _wireCount++; // UPLs start out life wired
752 _pages
+= atop_32(offset
+ count
+ PAGE_MASK
) - atop_32(offset
);
755 iopl
.fIOPL
= (upl_t
) buffers
;
756 upl_set_referenced(iopl
.fIOPL
, true);
757 upl_page_info_t
*pageList
= UPL_GET_INTERNAL_PAGE_LIST(iopl
.fIOPL
);
759 if (upl_get_size(iopl
.fIOPL
) < (count
+ offset
))
760 panic("short external upl");
762 _highestPage
= upl_get_highest_page(iopl
.fIOPL
);
764 // Set the flag kIOPLOnDevice convieniently equal to 1
765 iopl
.fFlags
= pageList
->device
| kIOPLExternUPL
;
766 if (!pageList
->device
) {
767 // Pre-compute the offset into the UPL's page list
768 pageList
= &pageList
[atop_32(offset
)];
771 iopl
.fIOMDOffset
= 0;
772 iopl
.fMappedPage
= 0;
773 iopl
.fPageInfo
= (vm_address_t
) pageList
;
774 iopl
.fPageOffset
= offset
;
775 _memoryEntries
->appendBytes(&iopl
, sizeof(iopl
));
778 // kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO
779 // kIOMemoryTypePhysical | kIOMemoryTypePhysical64
781 // Initialize the memory descriptor
782 if (options
& kIOMemoryAsReference
) {
784 _rangesIsAllocated
= false;
785 #endif /* !__LP64__ */
787 // Hack assignment to get the buffer arg into _ranges.
788 // I'd prefer to do _ranges = (Ranges) buffers, but that doesn't
790 // This also initialises the uio & physical ranges.
791 _ranges
.v
= (IOVirtualRange
*) buffers
;
795 _rangesIsAllocated
= true;
796 #endif /* !__LP64__ */
799 case kIOMemoryTypeUIO
:
800 _ranges
.v
= (IOVirtualRange
*) uio_duplicate((uio_t
) buffers
);
804 case kIOMemoryTypeVirtual64
:
805 case kIOMemoryTypePhysical64
:
807 && (((IOAddressRange
*) buffers
)->address
+ ((IOAddressRange
*) buffers
)->length
) <= 0x100000000ULL
809 if (kIOMemoryTypeVirtual64
== type
)
810 type
= kIOMemoryTypeVirtual
;
812 type
= kIOMemoryTypePhysical
;
813 _flags
= (_flags
& ~kIOMemoryTypeMask
) | type
| kIOMemoryAsReference
;
814 _rangesIsAllocated
= false;
815 _ranges
.v
= &_singleRange
.v
;
816 _singleRange
.v
.address
= ((IOAddressRange
*) buffers
)->address
;
817 _singleRange
.v
.length
= ((IOAddressRange
*) buffers
)->length
;
820 _ranges
.v64
= IONew(IOAddressRange
, count
);
823 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOAddressRange
));
825 #endif /* !__LP64__ */
826 case kIOMemoryTypeVirtual
:
827 case kIOMemoryTypePhysical
:
829 _flags
|= kIOMemoryAsReference
;
831 _rangesIsAllocated
= false;
832 #endif /* !__LP64__ */
833 _ranges
.v
= &_singleRange
.v
;
835 _ranges
.v
= IONew(IOVirtualRange
, count
);
839 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOVirtualRange
));
844 // Find starting address within the vector of ranges
845 Ranges vec
= _ranges
;
848 for (unsigned ind
= 0; ind
< count
; ind
++) {
850 IOPhysicalLength len
;
852 // addr & len are returned by this function
853 getAddrLenForInd(addr
, len
, type
, vec
, ind
);
854 pages
+= (atop_64(addr
+ len
+ PAGE_MASK
) - atop_64(addr
));
856 assert(len
>= length
); // Check for 32 bit wrap around
859 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
861 ppnum_t highPage
= atop_64(addr
+ len
- 1);
862 if (highPage
> _highestPage
)
863 _highestPage
= highPage
;
868 _rangesCount
= count
;
870 // Auto-prepare memory at creation time.
871 // Implied completion when descriptor is free-ed
872 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
873 _wireCount
++; // Physical MDs are, by definition, wired
874 else { /* kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO */
876 unsigned dataSize
= computeDataSize(_pages
, /* upls */ count
* 2);
878 if (!initMemoryEntries(dataSize
, mapper
)) return false;
879 dataP
= getDataP(_memoryEntries
);
880 dataP
->fPageCnt
= _pages
;
882 if ( (kIOMemoryPersistent
& _flags
) && !_memEntry
)
883 _memEntry
= createNamedEntry();
885 if ((_flags
& kIOMemoryAutoPrepare
)
886 && prepare() != kIOReturnSuccess
)
899 void IOGeneralMemoryDescriptor::free()
901 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
906 reserved
->dp
.memory
= 0;
910 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
916 _memoryEntries
->release();
918 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
920 if (kIOMemoryTypeUIO
== type
)
921 uio_free((uio_t
) _ranges
.v
);
923 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
924 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
925 #endif /* !__LP64__ */
927 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
934 if (reserved
->dp
.devicePager
)
936 // memEntry holds a ref on the device pager which owns reserved
937 // (IOMemoryDescriptorReserved) so no reserved access after this point
938 device_pager_deallocate( (memory_object_t
) reserved
->dp
.devicePager
);
941 IODelete(reserved
, IOMemoryDescriptorReserved
, 1);
946 ipc_port_release_send( (ipc_port_t
) _memEntry
);
949 IOLockFree(_prepareLock
);
955 void IOGeneralMemoryDescriptor::unmapFromKernel()
957 panic("IOGMD::unmapFromKernel deprecated");
960 void IOGeneralMemoryDescriptor::mapIntoKernel(unsigned rangeIndex
)
962 panic("IOGMD::mapIntoKernel deprecated");
964 #endif /* !__LP64__ */
969 * Get the direction of the transfer.
971 IODirection
IOMemoryDescriptor::getDirection() const
976 #endif /* !__LP64__ */
977 return (IODirection
) (_flags
& kIOMemoryDirectionMask
);
983 * Get the length of the transfer (over all ranges).
985 IOByteCount
IOMemoryDescriptor::getLength() const
990 void IOMemoryDescriptor::setTag( IOOptionBits tag
)
995 IOOptionBits
IOMemoryDescriptor::getTag( void )
1001 // @@@ gvdl: who is using this API? Seems like a wierd thing to implement.
1003 IOMemoryDescriptor::getSourceSegment( IOByteCount offset
, IOByteCount
* length
)
1005 addr64_t physAddr
= 0;
1007 if( prepare() == kIOReturnSuccess
) {
1008 physAddr
= getPhysicalSegment64( offset
, length
);
1012 return( (IOPhysicalAddress
) physAddr
); // truncated but only page offset is used
1014 #endif /* !__LP64__ */
1016 IOByteCount
IOMemoryDescriptor::readBytes
1017 (IOByteCount offset
, void *bytes
, IOByteCount length
)
1019 addr64_t dstAddr
= CAST_DOWN(addr64_t
, bytes
);
1020 IOByteCount remaining
;
1022 // Assert that this entire I/O is withing the available range
1023 assert(offset
< _length
);
1024 assert(offset
+ length
<= _length
);
1025 if (offset
>= _length
) {
1029 if (kIOMemoryThreadSafe
& _flags
)
1032 remaining
= length
= min(length
, _length
- offset
);
1033 while (remaining
) { // (process another target segment?)
1037 srcAddr64
= getPhysicalSegment(offset
, &srcLen
, kIOMemoryMapperNone
);
1041 // Clip segment length to remaining
1042 if (srcLen
> remaining
)
1045 copypv(srcAddr64
, dstAddr
, srcLen
,
1046 cppvPsrc
| cppvNoRefSrc
| cppvFsnk
| cppvKmap
);
1050 remaining
-= srcLen
;
1053 if (kIOMemoryThreadSafe
& _flags
)
1058 return length
- remaining
;
1061 IOByteCount
IOMemoryDescriptor::writeBytes
1062 (IOByteCount offset
, const void *bytes
, IOByteCount length
)
1064 addr64_t srcAddr
= CAST_DOWN(addr64_t
, bytes
);
1065 IOByteCount remaining
;
1067 // Assert that this entire I/O is withing the available range
1068 assert(offset
< _length
);
1069 assert(offset
+ length
<= _length
);
1071 assert( !(kIOMemoryPreparedReadOnly
& _flags
) );
1073 if ( (kIOMemoryPreparedReadOnly
& _flags
) || offset
>= _length
) {
1077 if (kIOMemoryThreadSafe
& _flags
)
1080 remaining
= length
= min(length
, _length
- offset
);
1081 while (remaining
) { // (process another target segment?)
1085 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1089 // Clip segment length to remaining
1090 if (dstLen
> remaining
)
1093 copypv(srcAddr
, (addr64_t
) dstAddr64
, dstLen
,
1094 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
1098 remaining
-= dstLen
;
1101 if (kIOMemoryThreadSafe
& _flags
)
1106 return length
- remaining
;
1109 // osfmk/device/iokit_rpc.c
1110 extern "C" unsigned int IODefaultCacheBits(addr64_t pa
);
1113 void IOGeneralMemoryDescriptor::setPosition(IOByteCount position
)
1115 panic("IOGMD::setPosition deprecated");
1117 #endif /* !__LP64__ */
1119 static volatile SInt64 gIOMDPreparationID
__attribute__((aligned(8))) = (1ULL << 32);
1122 IOGeneralMemoryDescriptor::getPreparationID( void )
1127 return (kIOPreparationIDUnprepared
);
1129 if (((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical
)
1130 || ((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical64
))
1132 IOMemoryDescriptor::setPreparationID();
1133 return (IOMemoryDescriptor::getPreparationID());
1136 if (!_memoryEntries
|| !(dataP
= getDataP(_memoryEntries
)))
1137 return (kIOPreparationIDUnprepared
);
1139 if (kIOPreparationIDUnprepared
== dataP
->fPreparationID
)
1141 dataP
->fPreparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1143 return (dataP
->fPreparationID
);
1146 IOMemoryDescriptorReserved
* IOMemoryDescriptor::getKernelReserved( void )
1150 reserved
= IONew(IOMemoryDescriptorReserved
, 1);
1152 bzero(reserved
, sizeof(IOMemoryDescriptorReserved
));
1157 void IOMemoryDescriptor::setPreparationID( void )
1159 if (getKernelReserved() && (kIOPreparationIDUnprepared
== reserved
->preparationID
))
1161 #if defined(__ppc__ )
1162 reserved
->preparationID
= gIOMDPreparationID
++;
1164 reserved
->preparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1169 uint64_t IOMemoryDescriptor::getPreparationID( void )
1172 return (reserved
->preparationID
);
1174 return (kIOPreparationIDUnsupported
);
1177 IOReturn
IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1179 IOReturn err
= kIOReturnSuccess
;
1180 DMACommandOps params
;
1181 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
1184 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
1185 op
&= kIOMDDMACommandOperationMask
;
1187 if (kIOMDDMAMap
== op
)
1189 if (dataSize
< sizeof(IOMDDMAMapArgs
))
1190 return kIOReturnUnderrun
;
1192 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
1195 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1197 if (_memoryEntries
&& data
->fMapper
)
1200 bool whole
= ((data
->fOffset
== 0) && (data
->fLength
== _length
));
1201 dataP
= getDataP(_memoryEntries
);
1202 if (data
->fMapSpec
.numAddressBits
< dataP
->fDMAMapNumAddressBits
)
1204 dataP
->fDMAMapNumAddressBits
= data
->fMapSpec
.numAddressBits
;
1205 remap
= ((dataP
->fMappedBase
+ _length
) > (1ULL << dataP
->fDMAMapNumAddressBits
));
1207 if (data
->fMapSpec
.alignment
> dataP
->fDMAMapAlignment
)
1209 dataP
->fDMAMapAlignment
= data
->fMapSpec
.alignment
;
1210 remap
|= (dataP
->fDMAMapAlignment
> page_size
);
1213 if (remap
|| !dataP
->fMappedBase
)
1215 // if (dataP->fMappedBase) OSReportWithBacktrace("kIOMDDMAMap whole %d remap %d params %d\n", whole, remap, params);
1216 err
= md
->dmaMap(data
->fMapper
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocCount
);
1217 if ((kIOReturnSuccess
== err
) && whole
&& !dataP
->fMappedBase
)
1219 dataP
->fMappedBase
= data
->fAlloc
;
1220 data
->fAllocCount
= 0; // IOMD owns the alloc now
1225 data
->fAlloc
= dataP
->fMappedBase
;
1226 data
->fAllocCount
= 0; // IOMD owns the alloc
1233 if (kIOMDAddDMAMapSpec
== op
)
1235 if (dataSize
< sizeof(IODMAMapSpecification
))
1236 return kIOReturnUnderrun
;
1238 IODMAMapSpecification
* data
= (IODMAMapSpecification
*) vData
;
1241 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1245 dataP
= getDataP(_memoryEntries
);
1246 if (data
->numAddressBits
< dataP
->fDMAMapNumAddressBits
)
1247 dataP
->fDMAMapNumAddressBits
= data
->numAddressBits
;
1248 if (data
->alignment
> dataP
->fDMAMapAlignment
)
1249 dataP
->fDMAMapAlignment
= data
->alignment
;
1251 return kIOReturnSuccess
;
1254 if (kIOMDGetCharacteristics
== op
) {
1256 if (dataSize
< sizeof(IOMDDMACharacteristics
))
1257 return kIOReturnUnderrun
;
1259 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
1260 data
->fLength
= _length
;
1261 data
->fSGCount
= _rangesCount
;
1262 data
->fPages
= _pages
;
1263 data
->fDirection
= getDirection();
1265 data
->fIsPrepared
= false;
1267 data
->fIsPrepared
= true;
1268 data
->fHighestPage
= _highestPage
;
1271 dataP
= getDataP(_memoryEntries
);
1272 ioPLBlock
*ioplList
= getIOPLList(dataP
);
1273 UInt count
= getNumIOPL(_memoryEntries
, dataP
);
1275 data
->fPageAlign
= (ioplList
[0].fPageOffset
& PAGE_MASK
) | ~PAGE_MASK
;
1279 return kIOReturnSuccess
;
1281 #if IOMD_DEBUG_DMAACTIVE
1282 } else if (kIOMDDMAActive
== op
) {
1283 if (params
) OSIncrementAtomic(&md
->__iomd_reservedA
);
1285 if (md
->__iomd_reservedA
)
1286 OSDecrementAtomic(&md
->__iomd_reservedA
);
1288 panic("kIOMDSetDMAInactive");
1290 #endif /* IOMD_DEBUG_DMAACTIVE */
1292 } else if (kIOMDWalkSegments
!= op
)
1293 return kIOReturnBadArgument
;
1295 // Get the next segment
1296 struct InternalState
{
1297 IOMDDMAWalkSegmentArgs fIO
;
1303 // Find the next segment
1304 if (dataSize
< sizeof(*isP
))
1305 return kIOReturnUnderrun
;
1307 isP
= (InternalState
*) vData
;
1308 UInt offset
= isP
->fIO
.fOffset
;
1309 bool mapped
= isP
->fIO
.fMapped
;
1311 if (IOMapper::gSystem
&& mapped
1312 && (!(kIOMemoryHostOnly
& _flags
))
1313 && (!_memoryEntries
|| !getDataP(_memoryEntries
)->fMappedBase
))
1314 // && (_memoryEntries && !getDataP(_memoryEntries)->fMappedBase))
1317 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1319 dataP
= getDataP(_memoryEntries
);
1322 IODMAMapSpecification mapSpec
;
1323 bzero(&mapSpec
, sizeof(mapSpec
));
1324 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
1325 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
1326 err
= md
->dmaMap(dataP
->fMapper
, &mapSpec
, 0, _length
, &dataP
->fMappedBase
, NULL
);
1327 if (kIOReturnSuccess
!= err
) return (err
);
1331 if (offset
>= _length
)
1332 return (offset
== _length
)? kIOReturnOverrun
: kIOReturnInternalError
;
1334 // Validate the previous offset
1335 UInt ind
, off2Ind
= isP
->fOffset2Index
;
1338 && (offset
== isP
->fNextOffset
|| off2Ind
<= offset
))
1341 ind
= off2Ind
= 0; // Start from beginning
1347 if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
) {
1349 // Physical address based memory descriptor
1350 const IOPhysicalRange
*physP
= (IOPhysicalRange
*) &_ranges
.p
[0];
1352 // Find the range after the one that contains the offset
1354 for (len
= 0; off2Ind
<= offset
; ind
++) {
1355 len
= physP
[ind
].length
;
1359 // Calculate length within range and starting address
1360 length
= off2Ind
- offset
;
1361 address
= physP
[ind
- 1].address
+ len
- length
;
1363 if (true && mapped
&& _memoryEntries
1364 && (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
1366 address
= dataP
->fMappedBase
+ offset
;
1370 // see how far we can coalesce ranges
1371 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
1372 len
= physP
[ind
].length
;
1379 // correct contiguous check overshoot
1384 else if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
) {
1386 // Physical address based memory descriptor
1387 const IOAddressRange
*physP
= (IOAddressRange
*) &_ranges
.v64
[0];
1389 // Find the range after the one that contains the offset
1391 for (len
= 0; off2Ind
<= offset
; ind
++) {
1392 len
= physP
[ind
].length
;
1396 // Calculate length within range and starting address
1397 length
= off2Ind
- offset
;
1398 address
= physP
[ind
- 1].address
+ len
- length
;
1400 if (true && mapped
&& _memoryEntries
1401 && (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
1403 address
= dataP
->fMappedBase
+ offset
;
1407 // see how far we can coalesce ranges
1408 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
1409 len
= physP
[ind
].length
;
1415 // correct contiguous check overshoot
1419 #endif /* !__LP64__ */
1422 panic("IOGMD: not wired for the IODMACommand");
1424 assert(_memoryEntries
);
1426 dataP
= getDataP(_memoryEntries
);
1427 const ioPLBlock
*ioplList
= getIOPLList(dataP
);
1428 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
1429 upl_page_info_t
*pageList
= getPageList(dataP
);
1431 assert(numIOPLs
> 0);
1433 // Scan through iopl info blocks looking for block containing offset
1434 while (ind
< numIOPLs
&& offset
>= ioplList
[ind
].fIOMDOffset
)
1437 // Go back to actual range as search goes past it
1438 ioPLBlock ioplInfo
= ioplList
[ind
- 1];
1439 off2Ind
= ioplInfo
.fIOMDOffset
;
1442 length
= ioplList
[ind
].fIOMDOffset
;
1445 length
-= offset
; // Remainder within iopl
1447 // Subtract offset till this iopl in total list
1450 // If a mapped address is requested and this is a pre-mapped IOPL
1451 // then just need to compute an offset relative to the mapped base.
1452 if (mapped
&& dataP
->fMappedBase
) {
1453 offset
+= (ioplInfo
.fPageOffset
& PAGE_MASK
);
1454 address
= trunc_page_64(dataP
->fMappedBase
) + ptoa_64(ioplInfo
.fMappedPage
) + offset
;
1455 continue; // Done leave do/while(false) now
1458 // The offset is rebased into the current iopl.
1459 // Now add the iopl 1st page offset.
1460 offset
+= ioplInfo
.fPageOffset
;
1462 // For external UPLs the fPageInfo field points directly to
1463 // the upl's upl_page_info_t array.
1464 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
1465 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
1467 pageList
= &pageList
[ioplInfo
.fPageInfo
];
1469 // Check for direct device non-paged memory
1470 if ( ioplInfo
.fFlags
& kIOPLOnDevice
) {
1471 address
= ptoa_64(pageList
->phys_addr
) + offset
;
1472 continue; // Done leave do/while(false) now
1475 // Now we need compute the index into the pageList
1476 UInt pageInd
= atop_32(offset
);
1477 offset
&= PAGE_MASK
;
1479 // Compute the starting address of this segment
1480 IOPhysicalAddress pageAddr
= pageList
[pageInd
].phys_addr
;
1482 panic("!pageList phys_addr");
1485 address
= ptoa_64(pageAddr
) + offset
;
1487 // length is currently set to the length of the remainider of the iopl.
1488 // We need to check that the remainder of the iopl is contiguous.
1489 // This is indicated by pageList[ind].phys_addr being sequential.
1490 IOByteCount contigLength
= PAGE_SIZE
- offset
;
1491 while (contigLength
< length
1492 && ++pageAddr
== pageList
[++pageInd
].phys_addr
)
1494 contigLength
+= PAGE_SIZE
;
1497 if (contigLength
< length
)
1498 length
= contigLength
;
1506 // Update return values and state
1507 isP
->fIO
.fIOVMAddr
= address
;
1508 isP
->fIO
.fLength
= length
;
1510 isP
->fOffset2Index
= off2Ind
;
1511 isP
->fNextOffset
= isP
->fIO
.fOffset
+ length
;
1513 return kIOReturnSuccess
;
1517 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
1520 addr64_t address
= 0;
1521 IOByteCount length
= 0;
1522 IOMapper
* mapper
= gIOSystemMapper
;
1523 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1525 if (lengthOfSegment
)
1526 *lengthOfSegment
= 0;
1528 if (offset
>= _length
)
1531 // IOMemoryDescriptor::doMap() cannot use getPhysicalSegment() to obtain the page offset, since it must
1532 // support the unwired memory case in IOGeneralMemoryDescriptor, and hibernate_write_image() cannot use
1533 // map()->getVirtualAddress() to obtain the kernel pointer, since it must prevent the memory allocation
1534 // due to IOMemoryMap, so _kIOMemorySourceSegment is a necessary evil until all of this gets cleaned up
1536 if ((options
& _kIOMemorySourceSegment
) && (kIOMemoryTypeUPL
!= type
))
1538 unsigned rangesIndex
= 0;
1539 Ranges vec
= _ranges
;
1542 // Find starting address within the vector of ranges
1544 getAddrLenForInd(addr
, length
, type
, vec
, rangesIndex
);
1545 if (offset
< length
)
1547 offset
-= length
; // (make offset relative)
1551 // Now that we have the starting range,
1552 // lets find the last contiguous range
1556 for ( ++rangesIndex
; rangesIndex
< _rangesCount
; rangesIndex
++ ) {
1557 user_addr_t newAddr
;
1558 IOPhysicalLength newLen
;
1560 getAddrLenForInd(newAddr
, newLen
, type
, vec
, rangesIndex
);
1561 if (addr
+ length
!= newAddr
)
1566 address
= (IOPhysicalAddress
) addr
; // Truncate address to 32bit
1570 IOMDDMAWalkSegmentState _state
;
1571 IOMDDMAWalkSegmentArgs
* state
= (IOMDDMAWalkSegmentArgs
*) (void *)&_state
;
1573 state
->fOffset
= offset
;
1574 state
->fLength
= _length
- offset
;
1575 state
->fMapped
= (0 == (options
& kIOMemoryMapperNone
)) && !(_flags
& kIOMemoryHostOnly
);
1577 ret
= dmaCommandOperation(kIOMDFirstSegment
, _state
, sizeof(_state
));
1579 if ((kIOReturnSuccess
!= ret
) && (kIOReturnOverrun
!= ret
))
1580 DEBG("getPhysicalSegment dmaCommandOperation(%lx), %p, offset %qx, addr %qx, len %qx\n",
1581 ret
, this, state
->fOffset
,
1582 state
->fIOVMAddr
, state
->fLength
);
1583 if (kIOReturnSuccess
== ret
)
1585 address
= state
->fIOVMAddr
;
1586 length
= state
->fLength
;
1589 // dmaCommandOperation() does not distinguish between "mapped" and "unmapped" physical memory, even
1590 // with fMapped set correctly, so we must handle the transformation here until this gets cleaned up
1592 if (mapper
&& ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
)))
1594 if ((options
& kIOMemoryMapperNone
) && !(_flags
& kIOMemoryMapperNone
))
1596 addr64_t origAddr
= address
;
1597 IOByteCount origLen
= length
;
1599 address
= mapper
->mapAddr(origAddr
);
1600 length
= page_size
- (address
& (page_size
- 1));
1601 while ((length
< origLen
)
1602 && ((address
+ length
) == mapper
->mapAddr(origAddr
+ length
)))
1603 length
+= page_size
;
1604 if (length
> origLen
)
1613 if (lengthOfSegment
)
1614 *lengthOfSegment
= length
;
1621 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
1623 addr64_t address
= 0;
1625 if (options
& _kIOMemorySourceSegment
)
1627 address
= getSourceSegment(offset
, lengthOfSegment
);
1629 else if (options
& kIOMemoryMapperNone
)
1631 address
= getPhysicalSegment64(offset
, lengthOfSegment
);
1635 address
= getPhysicalSegment(offset
, lengthOfSegment
);
1642 IOGeneralMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1644 return (getPhysicalSegment(offset
, lengthOfSegment
, kIOMemoryMapperNone
));
1648 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1650 addr64_t address
= 0;
1651 IOByteCount length
= 0;
1653 address
= getPhysicalSegment(offset
, lengthOfSegment
, 0);
1655 if (lengthOfSegment
)
1656 length
= *lengthOfSegment
;
1658 if ((address
+ length
) > 0x100000000ULL
)
1660 panic("getPhysicalSegment() out of 32b range 0x%qx, len 0x%lx, class %s",
1661 address
, (long) length
, (getMetaClass())->getClassName());
1664 return ((IOPhysicalAddress
) address
);
1668 IOMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1670 IOPhysicalAddress phys32
;
1673 IOMapper
* mapper
= 0;
1675 phys32
= getPhysicalSegment(offset
, lengthOfSegment
);
1679 if (gIOSystemMapper
)
1680 mapper
= gIOSystemMapper
;
1684 IOByteCount origLen
;
1686 phys64
= mapper
->mapAddr(phys32
);
1687 origLen
= *lengthOfSegment
;
1688 length
= page_size
- (phys64
& (page_size
- 1));
1689 while ((length
< origLen
)
1690 && ((phys64
+ length
) == mapper
->mapAddr(phys32
+ length
)))
1691 length
+= page_size
;
1692 if (length
> origLen
)
1695 *lengthOfSegment
= length
;
1698 phys64
= (addr64_t
) phys32
;
1704 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1706 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, 0));
1710 IOGeneralMemoryDescriptor::getSourceSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1712 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, _kIOMemorySourceSegment
));
1715 void * IOGeneralMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
1716 IOByteCount
* lengthOfSegment
)
1718 if (_task
== kernel_task
)
1719 return (void *) getSourceSegment(offset
, lengthOfSegment
);
1721 panic("IOGMD::getVirtualSegment deprecated");
1725 #endif /* !__LP64__ */
1728 IOMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1730 IOMemoryDescriptor
*md
= const_cast<IOMemoryDescriptor
*>(this);
1731 DMACommandOps params
;
1734 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
1735 op
&= kIOMDDMACommandOperationMask
;
1737 if (kIOMDGetCharacteristics
== op
) {
1738 if (dataSize
< sizeof(IOMDDMACharacteristics
))
1739 return kIOReturnUnderrun
;
1741 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
1742 data
->fLength
= getLength();
1744 data
->fDirection
= getDirection();
1745 data
->fIsPrepared
= true; // Assume prepared - fails safe
1747 else if (kIOMDWalkSegments
== op
) {
1748 if (dataSize
< sizeof(IOMDDMAWalkSegmentArgs
))
1749 return kIOReturnUnderrun
;
1751 IOMDDMAWalkSegmentArgs
*data
= (IOMDDMAWalkSegmentArgs
*) vData
;
1752 IOByteCount offset
= (IOByteCount
) data
->fOffset
;
1754 IOPhysicalLength length
;
1755 if (data
->fMapped
&& IOMapper::gSystem
)
1756 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
);
1758 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
, kIOMemoryMapperNone
);
1759 data
->fLength
= length
;
1761 else if (kIOMDAddDMAMapSpec
== op
) return kIOReturnUnsupported
;
1762 else if (kIOMDDMAMap
== op
)
1764 if (dataSize
< sizeof(IOMDDMAMapArgs
))
1765 return kIOReturnUnderrun
;
1766 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
1768 if (params
) panic("class %s does not support IODMACommand::kIterateOnly", getMetaClass()->getClassName());
1770 err
= md
->dmaMap(data
->fMapper
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocCount
);
1773 else return kIOReturnBadArgument
;
1775 return kIOReturnSuccess
;
1779 purgeableControlBits(IOOptionBits newState
, vm_purgable_t
* control
, int * state
)
1781 IOReturn err
= kIOReturnSuccess
;
1783 *control
= VM_PURGABLE_SET_STATE
;
1786 case kIOMemoryPurgeableKeepCurrent
:
1787 *control
= VM_PURGABLE_GET_STATE
;
1790 case kIOMemoryPurgeableNonVolatile
:
1791 *state
= VM_PURGABLE_NONVOLATILE
;
1793 case kIOMemoryPurgeableVolatile
:
1794 *state
= VM_PURGABLE_VOLATILE
;
1796 case kIOMemoryPurgeableEmpty
:
1797 *state
= VM_PURGABLE_EMPTY
;
1800 err
= kIOReturnBadArgument
;
1807 purgeableStateBits(int * state
)
1809 IOReturn err
= kIOReturnSuccess
;
1813 case VM_PURGABLE_NONVOLATILE
:
1814 *state
= kIOMemoryPurgeableNonVolatile
;
1816 case VM_PURGABLE_VOLATILE
:
1817 *state
= kIOMemoryPurgeableVolatile
;
1819 case VM_PURGABLE_EMPTY
:
1820 *state
= kIOMemoryPurgeableEmpty
;
1823 *state
= kIOMemoryPurgeableNonVolatile
;
1824 err
= kIOReturnNotReady
;
1831 IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState
,
1832 IOOptionBits
* oldState
)
1834 IOReturn err
= kIOReturnSuccess
;
1835 vm_purgable_t control
;
1840 err
= super::setPurgeable(newState
, oldState
);
1844 if (kIOMemoryThreadSafe
& _flags
)
1848 // Find the appropriate vm_map for the given task
1850 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
1852 err
= kIOReturnNotReady
;
1856 curMap
= get_task_map(_task
);
1858 // can only do one range
1859 Ranges vec
= _ranges
;
1860 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1863 getAddrLenForInd(addr
, len
, type
, vec
, 0);
1865 err
= purgeableControlBits(newState
, &control
, &state
);
1866 if (kIOReturnSuccess
!= err
)
1868 err
= mach_vm_purgable_control(curMap
, addr
, control
, &state
);
1871 if (kIOReturnSuccess
== err
)
1873 err
= purgeableStateBits(&state
);
1879 if (kIOMemoryThreadSafe
& _flags
)
1885 IOReturn
IOMemoryDescriptor::setPurgeable( IOOptionBits newState
,
1886 IOOptionBits
* oldState
)
1888 IOReturn err
= kIOReturnSuccess
;
1889 vm_purgable_t control
;
1892 if (kIOMemoryThreadSafe
& _flags
)
1899 err
= kIOReturnNotReady
;
1902 err
= purgeableControlBits(newState
, &control
, &state
);
1903 if (kIOReturnSuccess
!= err
)
1905 err
= mach_memory_entry_purgable_control((ipc_port_t
) _memEntry
, control
, &state
);
1908 if (kIOReturnSuccess
== err
)
1910 err
= purgeableStateBits(&state
);
1917 if (kIOMemoryThreadSafe
& _flags
)
1923 extern "C" void dcache_incoherent_io_flush64(addr64_t pa
, unsigned int count
);
1924 extern "C" void dcache_incoherent_io_store64(addr64_t pa
, unsigned int count
);
1926 static void SetEncryptOp(addr64_t pa
, unsigned int count
)
1930 page
= atop_64(round_page_64(pa
));
1931 end
= atop_64(trunc_page_64(pa
+ count
));
1932 for (; page
< end
; page
++)
1934 pmap_clear_noencrypt(page
);
1938 static void ClearEncryptOp(addr64_t pa
, unsigned int count
)
1942 page
= atop_64(round_page_64(pa
));
1943 end
= atop_64(trunc_page_64(pa
+ count
));
1944 for (; page
< end
; page
++)
1946 pmap_set_noencrypt(page
);
1950 IOReturn
IOMemoryDescriptor::performOperation( IOOptionBits options
,
1951 IOByteCount offset
, IOByteCount length
)
1953 IOByteCount remaining
;
1955 void (*func
)(addr64_t pa
, unsigned int count
) = 0;
1959 case kIOMemoryIncoherentIOFlush
:
1960 func
= &dcache_incoherent_io_flush64
;
1962 case kIOMemoryIncoherentIOStore
:
1963 func
= &dcache_incoherent_io_store64
;
1966 case kIOMemorySetEncrypted
:
1967 func
= &SetEncryptOp
;
1969 case kIOMemoryClearEncrypted
:
1970 func
= &ClearEncryptOp
;
1975 return (kIOReturnUnsupported
);
1977 if (kIOMemoryThreadSafe
& _flags
)
1981 remaining
= length
= min(length
, getLength() - offset
);
1983 // (process another target segment?)
1988 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1992 // Clip segment length to remaining
1993 if (dstLen
> remaining
)
1996 (*func
)(dstAddr64
, dstLen
);
1999 remaining
-= dstLen
;
2002 if (kIOMemoryThreadSafe
& _flags
)
2005 return (remaining
? kIOReturnUnderrun
: kIOReturnSuccess
);
2008 #if defined(__i386__) || defined(__x86_64__)
2009 extern vm_offset_t first_avail
;
2010 #define io_kernel_static_end first_avail
2012 #error io_kernel_static_end is undefined for this architecture
2015 static kern_return_t
2016 io_get_kernel_static_upl(
2019 vm_size_t
*upl_size
,
2021 upl_page_info_array_t page_list
,
2022 unsigned int *count
,
2023 ppnum_t
*highest_page
)
2025 unsigned int pageCount
, page
;
2027 ppnum_t highestPage
= 0;
2029 pageCount
= atop_32(*upl_size
);
2030 if (pageCount
> *count
)
2035 for (page
= 0; page
< pageCount
; page
++)
2037 phys
= pmap_find_phys(kernel_pmap
, ((addr64_t
)offset
) + ptoa_64(page
));
2040 page_list
[page
].phys_addr
= phys
;
2041 page_list
[page
].pageout
= 0;
2042 page_list
[page
].absent
= 0;
2043 page_list
[page
].dirty
= 0;
2044 page_list
[page
].precious
= 0;
2045 page_list
[page
].device
= 0;
2046 if (phys
> highestPage
)
2050 *highest_page
= highestPage
;
2052 return ((page
>= pageCount
) ? kIOReturnSuccess
: kIOReturnVMError
);
2055 IOReturn
IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection
)
2057 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2058 IOReturn error
= kIOReturnCannotWire
;
2060 upl_page_info_array_t pageInfo
;
2061 ppnum_t mapBase
= 0;
2062 ipc_port_t sharedMem
= (ipc_port_t
) _memEntry
;
2064 assert(!_wireCount
);
2065 assert(kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
);
2067 if (_pages
> gIOMaximumMappedIOPageCount
)
2068 return kIOReturnNoResources
;
2070 dataP
= getDataP(_memoryEntries
);
2072 mapper
= dataP
->fMapper
;
2073 dataP
->fMappedBase
= 0;
2075 if (forDirection
== kIODirectionNone
)
2076 forDirection
= getDirection();
2078 int uplFlags
; // This Mem Desc's default flags for upl creation
2079 switch (kIODirectionOutIn
& forDirection
)
2081 case kIODirectionOut
:
2082 // Pages do not need to be marked as dirty on commit
2083 uplFlags
= UPL_COPYOUT_FROM
;
2084 _flags
|= kIOMemoryPreparedReadOnly
;
2087 case kIODirectionIn
:
2089 uplFlags
= 0; // i.e. ~UPL_COPYOUT_FROM
2092 uplFlags
|= UPL_SET_IO_WIRE
| UPL_SET_LITE
;
2094 #ifdef UPL_NEED_32BIT_ADDR
2095 if (kIODirectionPrepareToPhys32
& forDirection
)
2097 if (!mapper
) uplFlags
|= UPL_NEED_32BIT_ADDR
;
2098 if (dataP
->fDMAMapNumAddressBits
> 32) dataP
->fDMAMapNumAddressBits
= 32;
2102 // Note that appendBytes(NULL) zeros the data up to the desired length.
2103 _memoryEntries
->appendBytes(0, dataP
->fPageCnt
* sizeof(upl_page_info_t
));
2106 // Find the appropriate vm_map for the given task
2108 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
2111 { curMap
= get_task_map(_task
); }
2113 // Iterate over the vector of virtual ranges
2114 Ranges vec
= _ranges
;
2115 unsigned int pageIndex
= 0;
2116 IOByteCount mdOffset
= 0;
2117 ppnum_t highestPage
= 0;
2119 for (UInt range
= 0; range
< _rangesCount
; range
++) {
2121 user_addr_t startPage
;
2122 IOByteCount numBytes
;
2123 ppnum_t highPage
= 0;
2125 // Get the startPage address and length of vec[range]
2126 getAddrLenForInd(startPage
, numBytes
, type
, vec
, range
);
2127 iopl
.fPageOffset
= startPage
& PAGE_MASK
;
2128 numBytes
+= iopl
.fPageOffset
;
2129 startPage
= trunc_page_64(startPage
);
2132 iopl
.fMappedPage
= mapBase
+ pageIndex
;
2134 iopl
.fMappedPage
= 0;
2136 // Iterate over the current range, creating UPLs
2138 vm_address_t kernelStart
= (vm_address_t
) startPage
;
2142 else if (!sharedMem
) {
2143 assert(_task
== kernel_task
);
2144 theMap
= IOPageableMapForAddress(kernelStart
);
2149 int ioplFlags
= uplFlags
;
2150 dataP
= getDataP(_memoryEntries
);
2151 pageInfo
= getPageList(dataP
);
2152 upl_page_list_ptr_t baseInfo
= &pageInfo
[pageIndex
];
2154 vm_size_t ioplSize
= round_page(numBytes
);
2155 unsigned int numPageInfo
= atop_32(ioplSize
);
2157 if (theMap
== kernel_map
&& kernelStart
< io_kernel_static_end
) {
2158 error
= io_get_kernel_static_upl(theMap
,
2166 else if (sharedMem
) {
2167 error
= memory_object_iopl_request(sharedMem
,
2177 error
= vm_map_create_upl(theMap
,
2179 (upl_size_t
*)&ioplSize
,
2187 if (error
!= KERN_SUCCESS
)
2191 highPage
= upl_get_highest_page(iopl
.fIOPL
);
2192 if (highPage
> highestPage
)
2193 highestPage
= highPage
;
2195 error
= kIOReturnCannotWire
;
2197 if (baseInfo
->device
) {
2199 iopl
.fFlags
= kIOPLOnDevice
;
2205 iopl
.fIOMDOffset
= mdOffset
;
2206 iopl
.fPageInfo
= pageIndex
;
2209 // used to remove the upl for auto prepares here, for some errant code
2210 // that freed memory before the descriptor pointing at it
2211 if ((_flags
& kIOMemoryAutoPrepare
) && iopl
.fIOPL
)
2213 upl_commit(iopl
.fIOPL
, 0, 0);
2214 upl_deallocate(iopl
.fIOPL
);
2219 if (!_memoryEntries
->appendBytes(&iopl
, sizeof(iopl
))) {
2220 // Clean up partial created and unsaved iopl
2222 upl_abort(iopl
.fIOPL
, 0);
2223 upl_deallocate(iopl
.fIOPL
);
2229 // Check for a multiple iopl's in one virtual range
2230 pageIndex
+= numPageInfo
;
2231 mdOffset
-= iopl
.fPageOffset
;
2232 if (ioplSize
< numBytes
) {
2233 numBytes
-= ioplSize
;
2234 startPage
+= ioplSize
;
2235 mdOffset
+= ioplSize
;
2236 iopl
.fPageOffset
= 0;
2237 if (mapper
) iopl
.fMappedPage
= mapBase
+ pageIndex
;
2240 mdOffset
+= numBytes
;
2246 _highestPage
= highestPage
;
2248 return kIOReturnSuccess
;
2252 dataP
= getDataP(_memoryEntries
);
2253 UInt done
= getNumIOPL(_memoryEntries
, dataP
);
2254 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2256 for (UInt range
= 0; range
< done
; range
++)
2258 if (ioplList
[range
].fIOPL
) {
2259 upl_abort(ioplList
[range
].fIOPL
, 0);
2260 upl_deallocate(ioplList
[range
].fIOPL
);
2263 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
2266 if (error
== KERN_FAILURE
)
2267 error
= kIOReturnCannotWire
;
2272 bool IOGeneralMemoryDescriptor::initMemoryEntries(size_t size
, IOMapper
* mapper
)
2275 unsigned dataSize
= size
;
2277 if (!_memoryEntries
) {
2278 _memoryEntries
= OSData::withCapacity(dataSize
);
2279 if (!_memoryEntries
)
2282 else if (!_memoryEntries
->initWithCapacity(dataSize
))
2285 _memoryEntries
->appendBytes(0, computeDataSize(0, 0));
2286 dataP
= getDataP(_memoryEntries
);
2288 if (mapper
== kIOMapperWaitSystem
) {
2289 IOMapper::checkForSystemMapper();
2290 mapper
= IOMapper::gSystem
;
2292 dataP
->fMapper
= mapper
;
2293 dataP
->fPageCnt
= 0;
2294 dataP
->fMappedBase
= 0;
2295 dataP
->fDMAMapNumAddressBits
= 64;
2296 dataP
->fDMAMapAlignment
= 0;
2297 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
2302 IOReturn
IOMemoryDescriptor::dmaMap(
2304 const IODMAMapSpecification
* mapSpec
,
2310 IOMDDMAWalkSegmentState walkState
;
2311 IOMDDMAWalkSegmentArgs
* walkArgs
= (IOMDDMAWalkSegmentArgs
*) (void *)&walkState
;
2314 IOPhysicalLength segLen
;
2315 addr64_t phys
, align
, pageOffset
;
2316 ppnum_t base
, pageIndex
, pageCount
;
2318 uint32_t mapOptions
= 0;
2320 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
2322 walkArgs
->fMapped
= false;
2323 mdOp
= kIOMDFirstSegment
;
2325 for (index
= 0; index
< length
; )
2327 if (index
&& (page_mask
& (index
+ pageOffset
))) break;
2329 walkArgs
->fOffset
= offset
+ index
;
2330 ret
= dmaCommandOperation(mdOp
, &walkState
, sizeof(walkState
));
2331 mdOp
= kIOMDWalkSegments
;
2332 if (ret
!= kIOReturnSuccess
) break;
2333 phys
= walkArgs
->fIOVMAddr
;
2334 segLen
= walkArgs
->fLength
;
2336 align
= (phys
& page_mask
);
2337 if (!index
) pageOffset
= align
;
2338 else if (align
) break;
2339 pageCount
+= atop_64(round_page_64(align
+ segLen
));
2343 if (index
< length
) return (kIOReturnVMError
);
2345 base
= mapper
->iovmMapMemory(this, offset
, pageCount
,
2346 mapOptions
, NULL
, mapSpec
);
2348 if (!base
) return (kIOReturnNoResources
);
2350 mdOp
= kIOMDFirstSegment
;
2351 for (pageIndex
= 0, index
= 0; index
< length
; )
2353 walkArgs
->fOffset
= offset
+ index
;
2354 ret
= dmaCommandOperation(mdOp
, &walkState
, sizeof(walkState
));
2355 mdOp
= kIOMDWalkSegments
;
2356 if (ret
!= kIOReturnSuccess
) break;
2357 phys
= walkArgs
->fIOVMAddr
;
2358 segLen
= walkArgs
->fLength
;
2360 ppnum_t page
= atop_64(phys
);
2361 ppnum_t count
= atop_64(round_page_64(phys
+ segLen
)) - page
;
2364 mapper
->iovmInsert(base
, pageIndex
, page
);
2370 if (pageIndex
!= pageCount
) panic("pageIndex");
2372 *address
= ptoa_64(base
) + pageOffset
;
2373 if (mapPages
) *mapPages
= pageCount
;
2375 return (kIOReturnSuccess
);
2378 IOReturn
IOGeneralMemoryDescriptor::dmaMap(
2380 const IODMAMapSpecification
* mapSpec
,
2386 IOReturn err
= kIOReturnSuccess
;
2388 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2391 if (kIOMemoryHostOnly
& _flags
) return (kIOReturnSuccess
);
2393 if ((type
== kIOMemoryTypePhysical
) || (type
== kIOMemoryTypePhysical64
)
2394 || offset
|| (length
!= _length
))
2396 err
= super::dmaMap(mapper
, mapSpec
, offset
, length
, address
, mapPages
);
2398 else if (_memoryEntries
&& _pages
&& (dataP
= getDataP(_memoryEntries
)))
2400 const ioPLBlock
* ioplList
= getIOPLList(dataP
);
2401 upl_page_info_t
* pageList
;
2402 uint32_t mapOptions
= 0;
2405 IODMAMapSpecification mapSpec
;
2406 bzero(&mapSpec
, sizeof(mapSpec
));
2407 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
2408 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
2410 // For external UPLs the fPageInfo field points directly to
2411 // the upl's upl_page_info_t array.
2412 if (ioplList
->fFlags
& kIOPLExternUPL
)
2414 pageList
= (upl_page_info_t
*) ioplList
->fPageInfo
;
2415 mapOptions
|= kIODMAMapPagingPath
;
2418 pageList
= getPageList(dataP
);
2420 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
2422 // Check for direct device non-paged memory
2423 if (ioplList
->fFlags
& kIOPLOnDevice
) mapOptions
|= kIODMAMapPhysicallyContiguous
;
2425 base
= mapper
->iovmMapMemory(
2426 this, offset
, _pages
, mapOptions
, &pageList
[0], &mapSpec
);
2427 *address
= ptoa_64(base
) + (ioplList
->fPageOffset
& PAGE_MASK
);
2428 if (mapPages
) *mapPages
= _pages
;
2437 * Prepare the memory for an I/O transfer. This involves paging in
2438 * the memory, if necessary, and wiring it down for the duration of
2439 * the transfer. The complete() method completes the processing of
2440 * the memory after the I/O transfer finishes. This method needn't
2441 * called for non-pageable memory.
2444 IOReturn
IOGeneralMemoryDescriptor::prepare(IODirection forDirection
)
2446 IOReturn error
= kIOReturnSuccess
;
2447 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2449 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
2450 return kIOReturnSuccess
;
2453 IOLockLock(_prepareLock
);
2456 && (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) ) {
2457 error
= wireVirtual(forDirection
);
2460 if (kIOReturnSuccess
== error
)
2462 if (1 == ++_wireCount
)
2464 if (kIOMemoryClearEncrypt
& _flags
)
2466 performOperation(kIOMemoryClearEncrypted
, 0, _length
);
2472 IOLockUnlock(_prepareLock
);
2480 * Complete processing of the memory after an I/O transfer finishes.
2481 * This method should not be called unless a prepare was previously
2482 * issued; the prepare() and complete() must occur in pairs, before
2483 * before and after an I/O transfer involving pageable memory.
2486 IOReturn
IOGeneralMemoryDescriptor::complete(IODirection
/* forDirection */)
2488 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2490 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
2491 return kIOReturnSuccess
;
2494 IOLockLock(_prepareLock
);
2500 if ((kIOMemoryClearEncrypt
& _flags
) && (1 == _wireCount
))
2502 performOperation(kIOMemorySetEncrypted
, 0, _length
);
2508 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2509 ioGMDData
* dataP
= getDataP(_memoryEntries
);
2510 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2511 UInt count
= getNumIOPL(_memoryEntries
, dataP
);
2513 #if IOMD_DEBUG_DMAACTIVE
2514 if (__iomd_reservedA
) panic("complete() while dma active");
2515 #endif /* IOMD_DEBUG_DMAACTIVE */
2517 if (dataP
->fMappedBase
) {
2518 dataP
->fMapper
->iovmFree(atop_64(dataP
->fMappedBase
), _pages
);
2519 dataP
->fMappedBase
= 0;
2521 // Only complete iopls that we created which are for TypeVirtual
2522 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) {
2523 for (UInt ind
= 0; ind
< count
; ind
++)
2524 if (ioplList
[ind
].fIOPL
) {
2525 upl_commit(ioplList
[ind
].fIOPL
, 0, 0);
2526 upl_deallocate(ioplList
[ind
].fIOPL
);
2528 } else if (kIOMemoryTypeUPL
== type
) {
2529 upl_set_referenced(ioplList
[0].fIOPL
, false);
2532 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
2534 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
2539 IOLockUnlock(_prepareLock
);
2541 return kIOReturnSuccess
;
2544 IOReturn
IOGeneralMemoryDescriptor::doMap(
2545 vm_map_t __addressMap
,
2546 IOVirtualAddress
* __address
,
2547 IOOptionBits options
,
2548 IOByteCount __offset
,
2549 IOByteCount __length
)
2553 if (!(kIOMap64Bit
& options
)) panic("IOGeneralMemoryDescriptor::doMap !64bit");
2554 #endif /* !__LP64__ */
2556 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
2557 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
2558 mach_vm_size_t length
= mapping
->fLength
;
2560 kern_return_t kr
= kIOReturnVMError
;
2561 ipc_port_t sharedMem
= (ipc_port_t
) _memEntry
;
2563 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2564 Ranges vec
= _ranges
;
2566 user_addr_t range0Addr
= 0;
2567 IOByteCount range0Len
= 0;
2569 if ((offset
>= _length
) || ((offset
+ length
) > _length
))
2570 return( kIOReturnBadArgument
);
2573 getAddrLenForInd(range0Addr
, range0Len
, type
, vec
, 0);
2575 // mapping source == dest? (could be much better)
2577 && (mapping
->fAddressMap
== get_task_map(_task
)) && (options
& kIOMapAnywhere
)
2578 && (1 == _rangesCount
) && (0 == offset
)
2579 && range0Addr
&& (length
<= range0Len
) )
2581 mapping
->fAddress
= range0Addr
;
2582 mapping
->fOptions
|= kIOMapStatic
;
2584 return( kIOReturnSuccess
);
2587 if( 0 == sharedMem
) {
2589 vm_size_t size
= ptoa_32(_pages
);
2593 memory_object_size_t actualSize
= size
;
2594 vm_prot_t prot
= VM_PROT_READ
;
2595 if (!(kIOMapReadOnly
& options
))
2596 prot
|= VM_PROT_WRITE
;
2597 else if (kIOMapDefaultCache
!= (options
& kIOMapCacheMask
))
2598 prot
|= VM_PROT_WRITE
;
2600 if (_rangesCount
== 1)
2602 kr
= mach_make_memory_entry_64(get_task_map(_task
),
2603 &actualSize
, range0Addr
,
2607 if( (_rangesCount
!= 1)
2608 || ((KERN_SUCCESS
== kr
) && (actualSize
!= round_page(size
))))
2612 IOLog("mach_vm_remap path for ranges %d size (%08llx:%08llx)\n",
2613 _rangesCount
, (UInt64
)actualSize
, (UInt64
)size
);
2615 kr
= kIOReturnVMError
;
2618 ipc_port_release_send(sharedMem
);
2619 sharedMem
= MACH_PORT_NULL
;
2622 mach_vm_address_t address
, segDestAddr
;
2623 mach_vm_size_t mapLength
;
2624 unsigned rangesIndex
;
2625 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2626 user_addr_t srcAddr
;
2627 IOPhysicalLength segLen
= 0;
2629 // Find starting address within the vector of ranges
2630 for (rangesIndex
= 0; rangesIndex
< _rangesCount
; rangesIndex
++) {
2631 getAddrLenForInd(srcAddr
, segLen
, type
, _ranges
, rangesIndex
);
2632 if (offset
< segLen
)
2634 offset
-= segLen
; // (make offset relative)
2637 mach_vm_size_t pageOffset
= (srcAddr
& PAGE_MASK
);
2638 address
= trunc_page_64(mapping
->fAddress
);
2640 if ((options
& kIOMapAnywhere
) || ((mapping
->fAddress
- address
) == pageOffset
))
2642 vm_map_t map
= mapping
->fAddressMap
;
2643 kr
= IOMemoryDescriptorMapCopy(&map
,
2645 offset
, &address
, round_page_64(length
+ pageOffset
));
2646 if (kr
== KERN_SUCCESS
)
2648 segDestAddr
= address
;
2655 vm_prot_t cur_prot
, max_prot
;
2657 if (segLen
> length
) segLen
= length
;
2658 kr
= mach_vm_remap(map
, &segDestAddr
, round_page_64(segLen
), PAGE_MASK
,
2659 VM_FLAGS_FIXED
| VM_FLAGS_OVERWRITE
,
2660 get_task_map(_task
), trunc_page_64(srcAddr
),
2665 if (KERN_SUCCESS
== kr
)
2667 if ((!(VM_PROT_READ
& cur_prot
))
2668 || (!(kIOMapReadOnly
& options
) && !(VM_PROT_WRITE
& cur_prot
)))
2670 kr
= KERN_PROTECTION_FAILURE
;
2673 if (KERN_SUCCESS
!= kr
)
2675 segDestAddr
+= segLen
;
2676 mapLength
-= segLen
;
2680 if (rangesIndex
>= _rangesCount
)
2682 kr
= kIOReturnBadArgument
;
2685 getAddrLenForInd(srcAddr
, segLen
, type
, vec
, rangesIndex
);
2686 if (srcAddr
& PAGE_MASK
)
2688 kr
= kIOReturnBadArgument
;
2691 if (segLen
> mapLength
)
2694 if (KERN_SUCCESS
!= kr
)
2696 mach_vm_deallocate(mapping
->fAddressMap
, address
, round_page_64(length
+ pageOffset
));
2700 if (KERN_SUCCESS
== kr
)
2701 mapping
->fAddress
= address
+ pageOffset
;
2703 mapping
->fAddress
= NULL
;
2709 { // _task == 0, must be physical
2711 memory_object_t pager
;
2712 unsigned int flags
= 0;
2714 IOPhysicalLength segLen
;
2716 pa
= getPhysicalSegment( offset
, &segLen
, kIOMemoryMapperNone
);
2718 if( !getKernelReserved())
2720 reserved
->dp
.pagerContig
= (1 == _rangesCount
);
2721 reserved
->dp
.memory
= this;
2723 /*What cache mode do we need*/
2724 switch(options
& kIOMapCacheMask
) {
2726 case kIOMapDefaultCache
:
2728 flags
= IODefaultCacheBits(pa
);
2729 if (DEVICE_PAGER_CACHE_INHIB
& flags
)
2731 if (DEVICE_PAGER_GUARDED
& flags
)
2732 mapping
->fOptions
|= kIOMapInhibitCache
;
2734 mapping
->fOptions
|= kIOMapWriteCombineCache
;
2736 else if (DEVICE_PAGER_WRITE_THROUGH
& flags
)
2737 mapping
->fOptions
|= kIOMapWriteThruCache
;
2739 mapping
->fOptions
|= kIOMapCopybackCache
;
2742 case kIOMapInhibitCache
:
2743 flags
= DEVICE_PAGER_CACHE_INHIB
|
2744 DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
2747 case kIOMapWriteThruCache
:
2748 flags
= DEVICE_PAGER_WRITE_THROUGH
|
2749 DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
2752 case kIOMapCopybackCache
:
2753 flags
= DEVICE_PAGER_COHERENT
;
2756 case kIOMapWriteCombineCache
:
2757 flags
= DEVICE_PAGER_CACHE_INHIB
|
2758 DEVICE_PAGER_COHERENT
;
2762 flags
|= reserved
->dp
.pagerContig
? DEVICE_PAGER_CONTIGUOUS
: 0;
2764 pager
= device_pager_setup( (memory_object_t
) 0, (uintptr_t) reserved
,
2769 kr
= mach_memory_object_memory_entry_64( (host_t
) 1, false /*internal*/,
2770 size
, VM_PROT_READ
| VM_PROT_WRITE
, pager
, &sharedMem
);
2772 assert( KERN_SUCCESS
== kr
);
2773 if( KERN_SUCCESS
!= kr
)
2775 device_pager_deallocate( pager
);
2776 pager
= MACH_PORT_NULL
;
2777 sharedMem
= MACH_PORT_NULL
;
2780 if( pager
&& sharedMem
)
2781 reserved
->dp
.devicePager
= pager
;
2785 _memEntry
= (void *) sharedMem
;
2792 result
= super::doMap( __addressMap
, __address
,
2793 options
, __offset
, __length
);
2798 IOReturn
IOGeneralMemoryDescriptor::doUnmap(
2799 vm_map_t addressMap
,
2800 IOVirtualAddress __address
,
2801 IOByteCount __length
)
2803 return (super::doUnmap(addressMap
, __address
, __length
));
2806 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2809 #define super OSObject
2811 OSDefineMetaClassAndStructors( IOMemoryMap
, OSObject
)
2813 OSMetaClassDefineReservedUnused(IOMemoryMap
, 0);
2814 OSMetaClassDefineReservedUnused(IOMemoryMap
, 1);
2815 OSMetaClassDefineReservedUnused(IOMemoryMap
, 2);
2816 OSMetaClassDefineReservedUnused(IOMemoryMap
, 3);
2817 OSMetaClassDefineReservedUnused(IOMemoryMap
, 4);
2818 OSMetaClassDefineReservedUnused(IOMemoryMap
, 5);
2819 OSMetaClassDefineReservedUnused(IOMemoryMap
, 6);
2820 OSMetaClassDefineReservedUnused(IOMemoryMap
, 7);
2822 /* ex-inline function implementation */
2823 IOPhysicalAddress
IOMemoryMap::getPhysicalAddress()
2824 { return( getPhysicalSegment( 0, 0 )); }
2826 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2828 bool IOMemoryMap::init(
2830 mach_vm_address_t toAddress
,
2831 IOOptionBits _options
,
2832 mach_vm_size_t _offset
,
2833 mach_vm_size_t _length
)
2841 fAddressMap
= get_task_map(intoTask
);
2844 vm_map_reference(fAddressMap
);
2846 fAddressTask
= intoTask
;
2847 fOptions
= _options
;
2850 fAddress
= toAddress
;
2855 bool IOMemoryMap::setMemoryDescriptor(IOMemoryDescriptor
* _memory
, mach_vm_size_t _offset
)
2862 if( (_offset
+ fLength
) > _memory
->getLength())
2870 if (fMemory
!= _memory
)
2871 fMemory
->removeMapping(this);
2879 struct IOMemoryDescriptorMapAllocRef
2881 ipc_port_t sharedMem
;
2883 mach_vm_address_t mapped
;
2884 mach_vm_size_t size
;
2885 mach_vm_size_t sourceOffset
;
2886 IOOptionBits options
;
2889 static kern_return_t
IOMemoryDescriptorMapAlloc(vm_map_t map
, void * _ref
)
2891 IOMemoryDescriptorMapAllocRef
* ref
= (IOMemoryDescriptorMapAllocRef
*)_ref
;
2897 vm_prot_t prot
= VM_PROT_READ
2898 | ((ref
->options
& kIOMapReadOnly
) ? 0 : VM_PROT_WRITE
);
2900 // VM system requires write access to change cache mode
2901 if (kIOMapDefaultCache
!= (ref
->options
& kIOMapCacheMask
))
2902 prot
|= VM_PROT_WRITE
;
2904 // set memory entry cache
2905 vm_prot_t memEntryCacheMode
= prot
| MAP_MEM_ONLY
;
2906 switch (ref
->options
& kIOMapCacheMask
)
2908 case kIOMapInhibitCache
:
2909 SET_MAP_MEM(MAP_MEM_IO
, memEntryCacheMode
);
2912 case kIOMapWriteThruCache
:
2913 SET_MAP_MEM(MAP_MEM_WTHRU
, memEntryCacheMode
);
2916 case kIOMapWriteCombineCache
:
2917 SET_MAP_MEM(MAP_MEM_WCOMB
, memEntryCacheMode
);
2920 case kIOMapCopybackCache
:
2921 SET_MAP_MEM(MAP_MEM_COPYBACK
, memEntryCacheMode
);
2924 case kIOMapCopybackInnerCache
:
2925 SET_MAP_MEM(MAP_MEM_INNERWBACK
, memEntryCacheMode
);
2928 case kIOMapDefaultCache
:
2930 SET_MAP_MEM(MAP_MEM_NOOP
, memEntryCacheMode
);
2934 vm_size_t unused
= 0;
2936 err
= mach_make_memory_entry( NULL
/*unused*/, &unused
, 0 /*unused*/,
2937 memEntryCacheMode
, NULL
, ref
->sharedMem
);
2938 if (KERN_SUCCESS
!= err
)
2939 IOLog("MAP_MEM_ONLY failed %d\n", err
);
2941 err
= mach_vm_map( map
,
2943 ref
->size
, 0 /* mask */,
2944 (( ref
->options
& kIOMapAnywhere
) ? VM_FLAGS_ANYWHERE
: VM_FLAGS_FIXED
)
2945 | VM_MAKE_TAG(VM_MEMORY_IOKIT
),
2946 ref
->sharedMem
, ref
->sourceOffset
,
2952 if( KERN_SUCCESS
!= err
) {
2960 err
= mach_vm_allocate(map
, &ref
->mapped
, ref
->size
,
2961 ((ref
->options
& kIOMapAnywhere
) ? VM_FLAGS_ANYWHERE
: VM_FLAGS_FIXED
)
2962 | VM_MAKE_TAG(VM_MEMORY_IOKIT
) );
2963 if( KERN_SUCCESS
!= err
) {
2968 // we have to make sure that these guys don't get copied if we fork.
2969 err
= vm_inherit(map
, ref
->mapped
, ref
->size
, VM_INHERIT_NONE
);
2970 assert( KERN_SUCCESS
== err
);
2979 IOMemoryDescriptorMapMemEntry(vm_map_t
* map
, ipc_port_t entry
, IOOptionBits options
, bool pageable
,
2980 mach_vm_size_t offset
,
2981 mach_vm_address_t
* address
, mach_vm_size_t length
)
2984 IOMemoryDescriptorMapAllocRef ref
;
2987 ref
.sharedMem
= entry
;
2988 ref
.sourceOffset
= trunc_page_64(offset
);
2989 ref
.options
= options
;
2992 if (options
& kIOMapAnywhere
)
2993 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
2996 ref
.mapped
= *address
;
2998 if( ref
.sharedMem
&& (ref
.map
== kernel_map
) && pageable
)
2999 err
= IOIteratePageableMaps( ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
3001 err
= IOMemoryDescriptorMapAlloc( ref
.map
, &ref
);
3003 *address
= ref
.mapped
;
3010 IOMemoryDescriptorMapCopy(vm_map_t
* map
,
3011 IOOptionBits options
,
3012 mach_vm_size_t offset
,
3013 mach_vm_address_t
* address
, mach_vm_size_t length
)
3016 IOMemoryDescriptorMapAllocRef ref
;
3019 ref
.sharedMem
= NULL
;
3020 ref
.sourceOffset
= trunc_page_64(offset
);
3021 ref
.options
= options
;
3024 if (options
& kIOMapAnywhere
)
3025 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
3028 ref
.mapped
= *address
;
3030 if (ref
.map
== kernel_map
)
3031 err
= IOIteratePageableMaps(ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
3033 err
= IOMemoryDescriptorMapAlloc(ref
.map
, &ref
);
3035 *address
= ref
.mapped
;
3041 IOReturn
IOMemoryDescriptor::doMap(
3042 vm_map_t __addressMap
,
3043 IOVirtualAddress
* __address
,
3044 IOOptionBits options
,
3045 IOByteCount __offset
,
3046 IOByteCount __length
)
3049 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::doMap !64bit");
3050 #endif /* !__LP64__ */
3052 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
3053 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3054 mach_vm_size_t length
= mapping
->fLength
;
3056 IOReturn err
= kIOReturnSuccess
;
3057 memory_object_t pager
;
3058 mach_vm_size_t pageOffset
;
3059 IOPhysicalAddress sourceAddr
;
3060 unsigned int lock_count
;
3064 sourceAddr
= getPhysicalSegment( offset
, NULL
, _kIOMemorySourceSegment
);
3065 pageOffset
= sourceAddr
- trunc_page( sourceAddr
);
3068 pager
= (memory_object_t
) reserved
->dp
.devicePager
;
3070 pager
= MACH_PORT_NULL
;
3072 if ((kIOMapReference
|kIOMapUnique
) == ((kIOMapReference
|kIOMapUnique
) & options
))
3080 err
= kIOReturnNotReadable
;
3084 size
= round_page(mapping
->fLength
+ pageOffset
);
3085 flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3086 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
3088 if (KERN_SUCCESS
!= memory_object_iopl_request((ipc_port_t
) _memEntry
, 0, &size
, &redirUPL2
,
3093 for (lock_count
= 0;
3094 IORecursiveLockHaveLock(gIOMemoryLock
);
3098 err
= upl_transpose(redirUPL2
, mapping
->fRedirUPL
);
3105 if (kIOReturnSuccess
!= err
)
3107 IOLog("upl_transpose(%x)\n", err
);
3108 err
= kIOReturnSuccess
;
3113 upl_commit(redirUPL2
, NULL
, 0);
3114 upl_deallocate(redirUPL2
);
3118 // swap the memEntries since they now refer to different vm_objects
3119 void * me
= _memEntry
;
3120 _memEntry
= mapping
->fMemory
->_memEntry
;
3121 mapping
->fMemory
->_memEntry
= me
;
3124 err
= handleFault( pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
3128 mach_vm_address_t address
;
3130 if (!(options
& kIOMapAnywhere
))
3132 address
= trunc_page_64(mapping
->fAddress
);
3133 if( (mapping
->fAddress
- address
) != pageOffset
)
3135 err
= kIOReturnVMError
;
3140 vm_map_t map
= mapping
->fAddressMap
;
3141 err
= IOMemoryDescriptorMapMemEntry(&map
, (ipc_port_t
) _memEntry
,
3142 options
, (kIOMemoryBufferPageable
& _flags
),
3143 offset
, &address
, round_page_64(length
+ pageOffset
));
3144 if( err
!= KERN_SUCCESS
)
3147 if (!_memEntry
|| pager
)
3149 err
= handleFault( pager
, mapping
->fAddressMap
, address
, offset
, length
, options
);
3150 if (err
!= KERN_SUCCESS
)
3151 doUnmap( mapping
->fAddressMap
, (IOVirtualAddress
) mapping
, 0 );
3155 if (kIOLogMapping
& gIOKitDebug
)
3156 IOLog("mapping(%x) desc %p @ %qx, map %p, address %qx, offset %qx, length %qx\n",
3157 err
, this, (uint64_t)sourceAddr
, mapping
, address
, offset
, length
);
3160 if (err
== KERN_SUCCESS
)
3161 mapping
->fAddress
= address
+ pageOffset
;
3163 mapping
->fAddress
= NULL
;
3171 IOReturn
IOMemoryDescriptor::handleFault(
3173 vm_map_t addressMap
,
3174 mach_vm_address_t address
,
3175 mach_vm_size_t sourceOffset
,
3176 mach_vm_size_t length
,
3177 IOOptionBits options
)
3179 IOReturn err
= kIOReturnSuccess
;
3180 memory_object_t pager
= (memory_object_t
) _pager
;
3181 mach_vm_size_t size
;
3182 mach_vm_size_t bytes
;
3183 mach_vm_size_t page
;
3184 mach_vm_size_t pageOffset
;
3185 mach_vm_size_t pagerOffset
;
3186 IOPhysicalLength segLen
;
3191 if( kIOMemoryRedirected
& _flags
)
3194 IOLog("sleep mem redirect %p, %qx\n", this, sourceOffset
);
3198 } while( kIOMemoryRedirected
& _flags
);
3201 return( kIOReturnSuccess
);
3204 physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
);
3206 pageOffset
= physAddr
- trunc_page_64( physAddr
);
3207 pagerOffset
= sourceOffset
;
3209 size
= length
+ pageOffset
;
3210 physAddr
-= pageOffset
;
3212 segLen
+= pageOffset
;
3216 // in the middle of the loop only map whole pages
3217 if( segLen
>= bytes
)
3219 else if( segLen
!= trunc_page( segLen
))
3220 err
= kIOReturnVMError
;
3221 if( physAddr
!= trunc_page_64( physAddr
))
3222 err
= kIOReturnBadArgument
;
3223 if (kIOReturnSuccess
!= err
)
3227 if( kIOLogMapping
& gIOKitDebug
)
3228 IOLog("IOMemoryMap::map(%p) 0x%qx->0x%qx:0x%qx\n",
3229 addressMap
, address
+ pageOffset
, physAddr
+ pageOffset
,
3230 segLen
- pageOffset
);
3235 if( reserved
&& reserved
->dp
.pagerContig
) {
3236 IOPhysicalLength allLen
;
3239 allPhys
= getPhysicalSegment( 0, &allLen
, kIOMemoryMapperNone
);
3241 err
= device_pager_populate_object( pager
, 0, atop_64(allPhys
), round_page(allLen
) );
3247 (page
< segLen
) && (KERN_SUCCESS
== err
);
3250 err
= device_pager_populate_object(pager
, pagerOffset
,
3251 (ppnum_t
)(atop_64(physAddr
+ page
)), page_size
);
3252 pagerOffset
+= page_size
;
3255 assert( KERN_SUCCESS
== err
);
3260 // This call to vm_fault causes an early pmap level resolution
3261 // of the mappings created above for kernel mappings, since
3262 // faulting in later can't take place from interrupt level.
3264 /* *** Temporary Workaround *** */
3266 if ((addressMap
== kernel_map
) && !(kIOMemoryRedirected
& _flags
))
3268 vm_fault(addressMap
,
3269 (vm_map_offset_t
)address
,
3270 VM_PROT_READ
|VM_PROT_WRITE
,
3271 FALSE
, THREAD_UNINT
, NULL
,
3272 (vm_map_offset_t
)0);
3275 /* *** Temporary Workaround *** */
3278 sourceOffset
+= segLen
- pageOffset
;
3284 while (bytes
&& (physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
)));
3287 err
= kIOReturnBadArgument
;
3292 IOReturn
IOMemoryDescriptor::doUnmap(
3293 vm_map_t addressMap
,
3294 IOVirtualAddress __address
,
3295 IOByteCount __length
)
3298 mach_vm_address_t address
;
3299 mach_vm_size_t length
;
3303 address
= __address
;
3308 addressMap
= ((IOMemoryMap
*) __address
)->fAddressMap
;
3309 address
= ((IOMemoryMap
*) __address
)->fAddress
;
3310 length
= ((IOMemoryMap
*) __address
)->fLength
;
3313 if ((addressMap
== kernel_map
)
3314 && ((kIOMemoryBufferPageable
& _flags
) || !_memEntry
))
3315 addressMap
= IOPageableMapForAddress( address
);
3318 if( kIOLogMapping
& gIOKitDebug
)
3319 IOLog("IOMemoryDescriptor::doUnmap map %p, 0x%qx:0x%qx\n",
3320 addressMap
, address
, length
);
3323 err
= mach_vm_deallocate( addressMap
, address
, length
);
3328 IOReturn
IOMemoryDescriptor::redirect( task_t safeTask
, bool doRedirect
)
3330 IOReturn err
= kIOReturnSuccess
;
3331 IOMemoryMap
* mapping
= 0;
3337 _flags
|= kIOMemoryRedirected
;
3339 _flags
&= ~kIOMemoryRedirected
;
3342 if( (iter
= OSCollectionIterator::withCollection( _mappings
))) {
3343 while( (mapping
= (IOMemoryMap
*) iter
->getNextObject()))
3344 mapping
->redirect( safeTask
, doRedirect
);
3358 // temporary binary compatibility
3359 IOSubMemoryDescriptor
* subMem
;
3360 if( (subMem
= OSDynamicCast( IOSubMemoryDescriptor
, this)))
3361 err
= subMem
->redirect( safeTask
, doRedirect
);
3363 err
= kIOReturnSuccess
;
3364 #endif /* !__LP64__ */
3369 IOReturn
IOMemoryMap::redirect( task_t safeTask
, bool doRedirect
)
3371 IOReturn err
= kIOReturnSuccess
;
3374 // err = ((IOMemoryMap *)superMap)->redirect( safeTask, doRedirect );
3386 if ((!safeTask
|| (get_task_map(safeTask
) != fAddressMap
))
3387 && (0 == (fOptions
& kIOMapStatic
)))
3389 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3390 err
= kIOReturnSuccess
;
3392 IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect
, this, fAddress
, fLength
, fAddressMap
);
3395 else if (kIOMapWriteCombineCache
== (fOptions
& kIOMapCacheMask
))
3397 IOOptionBits newMode
;
3398 newMode
= (fOptions
& ~kIOMapCacheMask
) | (doRedirect
? kIOMapInhibitCache
: kIOMapWriteCombineCache
);
3399 IOProtectCacheMode(fAddressMap
, fAddress
, fLength
, newMode
);
3406 if ((((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3407 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3409 && (doRedirect
!= (0 != (fMemory
->_flags
& kIOMemoryRedirected
))))
3410 fMemory
->redirect(safeTask
, doRedirect
);
3415 IOReturn
IOMemoryMap::unmap( void )
3421 if( fAddress
&& fAddressMap
&& (0 == fSuperMap
) && fMemory
3422 && (0 == (fOptions
& kIOMapStatic
))) {
3424 err
= fMemory
->doUnmap(fAddressMap
, (IOVirtualAddress
) this, 0);
3427 err
= kIOReturnSuccess
;
3431 vm_map_deallocate(fAddressMap
);
3442 void IOMemoryMap::taskDied( void )
3445 if (fUserClientUnmap
)
3448 vm_map_deallocate(fAddressMap
);
3456 IOReturn
IOMemoryMap::userClientUnmap( void )
3458 fUserClientUnmap
= true;
3459 return (kIOReturnSuccess
);
3462 // Overload the release mechanism. All mappings must be a member
3463 // of a memory descriptors _mappings set. This means that we
3464 // always have 2 references on a mapping. When either of these mappings
3465 // are released we need to free ourselves.
3466 void IOMemoryMap::taggedRelease(const void *tag
) const
3469 super::taggedRelease(tag
, 2);
3473 void IOMemoryMap::free()
3480 fMemory
->removeMapping(this);
3485 if (fOwner
&& (fOwner
!= fMemory
))
3488 fOwner
->removeMapping(this);
3493 fSuperMap
->release();
3496 upl_commit(fRedirUPL
, NULL
, 0);
3497 upl_deallocate(fRedirUPL
);
3503 IOByteCount
IOMemoryMap::getLength()
3508 IOVirtualAddress
IOMemoryMap::getVirtualAddress()
3512 fSuperMap
->getVirtualAddress();
3513 else if (fAddressMap
3514 && vm_map_is_64bit(fAddressMap
)
3515 && (sizeof(IOVirtualAddress
) < 8))
3517 OSReportWithBacktrace("IOMemoryMap::getVirtualAddress(0x%qx) called on 64b map; use ::getAddress()", fAddress
);
3519 #endif /* !__LP64__ */
3525 mach_vm_address_t
IOMemoryMap::getAddress()
3530 mach_vm_size_t
IOMemoryMap::getSize()
3534 #endif /* !__LP64__ */
3537 task_t
IOMemoryMap::getAddressTask()
3540 return( fSuperMap
->getAddressTask());
3542 return( fAddressTask
);
3545 IOOptionBits
IOMemoryMap::getMapOptions()
3550 IOMemoryDescriptor
* IOMemoryMap::getMemoryDescriptor()
3555 IOMemoryMap
* IOMemoryMap::copyCompatible(
3556 IOMemoryMap
* newMapping
)
3558 task_t task
= newMapping
->getAddressTask();
3559 mach_vm_address_t toAddress
= newMapping
->fAddress
;
3560 IOOptionBits _options
= newMapping
->fOptions
;
3561 mach_vm_size_t _offset
= newMapping
->fOffset
;
3562 mach_vm_size_t _length
= newMapping
->fLength
;
3564 if( (!task
) || (!fAddressMap
) || (fAddressMap
!= get_task_map(task
)))
3566 if( (fOptions
^ _options
) & kIOMapReadOnly
)
3568 if( (kIOMapDefaultCache
!= (_options
& kIOMapCacheMask
))
3569 && ((fOptions
^ _options
) & kIOMapCacheMask
))
3572 if( (0 == (_options
& kIOMapAnywhere
)) && (fAddress
!= toAddress
))
3575 if( _offset
< fOffset
)
3580 if( (_offset
+ _length
) > fLength
)
3584 if( (fLength
== _length
) && (!_offset
))
3590 newMapping
->fSuperMap
= this;
3591 newMapping
->fOffset
= fOffset
+ _offset
;
3592 newMapping
->fAddress
= fAddress
+ _offset
;
3595 return( newMapping
);
3598 IOReturn
IOMemoryMap::wireRange(
3600 mach_vm_size_t offset
,
3601 mach_vm_size_t length
)
3604 mach_vm_address_t start
= trunc_page_64(fAddress
+ offset
);
3605 mach_vm_address_t end
= round_page_64(fAddress
+ offset
+ length
);
3607 if (kIODirectionOutIn
& options
)
3609 kr
= vm_map_wire(fAddressMap
, start
, end
, (kIODirectionOutIn
& options
), FALSE
);
3613 kr
= vm_map_unwire(fAddressMap
, start
, end
, FALSE
);
3622 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
, IOOptionBits _options
)
3623 #else /* !__LP64__ */
3624 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
)
3625 #endif /* !__LP64__ */
3627 IOPhysicalAddress address
;
3631 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
, _options
);
3632 #else /* !__LP64__ */
3633 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
);
3634 #endif /* !__LP64__ */
3640 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3643 #define super OSObject
3645 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3647 void IOMemoryDescriptor::initialize( void )
3649 if( 0 == gIOMemoryLock
)
3650 gIOMemoryLock
= IORecursiveLockAlloc();
3652 IORegistryEntry::getRegistryRoot()->setProperty(kIOMaximumMappedIOByteCountKey
,
3653 ptoa_64(gIOMaximumMappedIOPageCount
), 64);
3654 gIOLastPage
= IOGetLastPageNumber();
3656 gIOPageAllocLock
= IOSimpleLockAlloc();
3657 queue_init(&gIOPageAllocList
);
3660 void IOMemoryDescriptor::free( void )
3663 _mappings
->release();
3668 IOMemoryMap
* IOMemoryDescriptor::setMapping(
3670 IOVirtualAddress mapAddress
,
3671 IOOptionBits options
)
3673 return (createMappingInTask( intoTask
, mapAddress
,
3674 options
| kIOMapStatic
,
3678 IOMemoryMap
* IOMemoryDescriptor::map(
3679 IOOptionBits options
)
3681 return (createMappingInTask( kernel_task
, 0,
3682 options
| kIOMapAnywhere
,
3687 IOMemoryMap
* IOMemoryDescriptor::map(
3689 IOVirtualAddress atAddress
,
3690 IOOptionBits options
,
3692 IOByteCount length
)
3694 if ((!(kIOMapAnywhere
& options
)) && vm_map_is_64bit(get_task_map(intoTask
)))
3696 OSReportWithBacktrace("IOMemoryDescriptor::map() in 64b task, use ::createMappingInTask()");
3700 return (createMappingInTask(intoTask
, atAddress
,
3701 options
, offset
, length
));
3703 #endif /* !__LP64__ */
3705 IOMemoryMap
* IOMemoryDescriptor::createMappingInTask(
3707 mach_vm_address_t atAddress
,
3708 IOOptionBits options
,
3709 mach_vm_size_t offset
,
3710 mach_vm_size_t length
)
3712 IOMemoryMap
* result
;
3713 IOMemoryMap
* mapping
;
3716 length
= getLength();
3718 mapping
= new IOMemoryMap
;
3721 && !mapping
->init( intoTask
, atAddress
,
3722 options
, offset
, length
)) {
3728 result
= makeMapping(this, intoTask
, (IOVirtualAddress
) mapping
, options
| kIOMap64Bit
, 0, 0);
3734 IOLog("createMappingInTask failed desc %p, addr %qx, options %x, offset %qx, length %llx\n",
3735 this, atAddress
, (uint32_t) options
, offset
, length
);
3741 #ifndef __LP64__ // there is only a 64 bit version for LP64
3742 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
3743 IOOptionBits options
,
3746 return (redirect(newBackingMemory
, options
, (mach_vm_size_t
)offset
));
3750 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
3751 IOOptionBits options
,
3752 mach_vm_size_t offset
)
3754 IOReturn err
= kIOReturnSuccess
;
3755 IOMemoryDescriptor
* physMem
= 0;
3759 if (fAddress
&& fAddressMap
) do
3761 if (((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3762 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3770 vm_size_t size
= round_page(fLength
);
3771 int flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3772 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
3773 if (KERN_SUCCESS
!= memory_object_iopl_request((ipc_port_t
) fMemory
->_memEntry
, 0, &size
, &fRedirUPL
,
3780 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3782 physMem
->redirect(0, true);
3786 if (newBackingMemory
)
3788 if (newBackingMemory
!= fMemory
)
3791 if (this != newBackingMemory
->makeMapping(newBackingMemory
, fAddressTask
, (IOVirtualAddress
) this,
3792 options
| kIOMapUnique
| kIOMapReference
| kIOMap64Bit
,
3794 err
= kIOReturnError
;
3798 upl_commit(fRedirUPL
, NULL
, 0);
3799 upl_deallocate(fRedirUPL
);
3802 if (false && physMem
)
3803 physMem
->redirect(0, false);
3816 IOMemoryMap
* IOMemoryDescriptor::makeMapping(
3817 IOMemoryDescriptor
* owner
,
3819 IOVirtualAddress __address
,
3820 IOOptionBits options
,
3821 IOByteCount __offset
,
3822 IOByteCount __length
)
3825 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::makeMapping !64bit");
3826 #endif /* !__LP64__ */
3828 IOMemoryDescriptor
* mapDesc
= 0;
3829 IOMemoryMap
* result
= 0;
3832 IOMemoryMap
* mapping
= (IOMemoryMap
*) __address
;
3833 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3834 mach_vm_size_t length
= mapping
->fLength
;
3836 mapping
->fOffset
= offset
;
3842 if (kIOMapStatic
& options
)
3845 addMapping(mapping
);
3846 mapping
->setMemoryDescriptor(this, 0);
3850 if (kIOMapUnique
& options
)
3853 IOByteCount physLen
;
3855 // if (owner != this) continue;
3857 if (((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3858 || ((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3860 phys
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
3861 if (!phys
|| (physLen
< length
))
3864 mapDesc
= IOMemoryDescriptor::withAddressRange(
3865 phys
, length
, getDirection() | kIOMemoryMapperNone
, NULL
);
3869 mapping
->fOffset
= offset
;
3874 // look for a compatible existing mapping
3875 if( (iter
= OSCollectionIterator::withCollection(_mappings
)))
3877 IOMemoryMap
* lookMapping
;
3878 while ((lookMapping
= (IOMemoryMap
*) iter
->getNextObject()))
3880 if ((result
= lookMapping
->copyCompatible(mapping
)))
3883 result
->setMemoryDescriptor(this, offset
);
3889 if (result
|| (options
& kIOMapReference
))
3891 if (result
!= mapping
)
3906 kr
= mapDesc
->doMap( 0, (IOVirtualAddress
*) &mapping
, options
, 0, 0 );
3907 if (kIOReturnSuccess
== kr
)
3910 mapDesc
->addMapping(result
);
3911 result
->setMemoryDescriptor(mapDesc
, offset
);
3929 void IOMemoryDescriptor::addMapping(
3930 IOMemoryMap
* mapping
)
3935 _mappings
= OSSet::withCapacity(1);
3937 _mappings
->setObject( mapping
);
3941 void IOMemoryDescriptor::removeMapping(
3942 IOMemoryMap
* mapping
)
3945 _mappings
->removeObject( mapping
);
3949 // obsolete initializers
3950 // - initWithOptions is the designated initializer
3952 IOMemoryDescriptor::initWithAddress(void * address
,
3954 IODirection direction
)
3960 IOMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
3962 IODirection direction
,
3969 IOMemoryDescriptor::initWithPhysicalAddress(
3970 IOPhysicalAddress address
,
3972 IODirection direction
)
3978 IOMemoryDescriptor::initWithRanges(
3979 IOVirtualRange
* ranges
,
3981 IODirection direction
,
3989 IOMemoryDescriptor::initWithPhysicalRanges( IOPhysicalRange
* ranges
,
3991 IODirection direction
,
3997 void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
3998 IOByteCount
* lengthOfSegment
)
4002 #endif /* !__LP64__ */
4004 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4006 bool IOGeneralMemoryDescriptor::serialize(OSSerialize
* s
) const
4008 OSSymbol
const *keys
[2];
4009 OSObject
*values
[2];
4011 user_addr_t address
;
4014 unsigned int index
, nRanges
;
4017 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
4019 if (s
== NULL
) return false;
4020 if (s
->previouslySerialized(this)) return true;
4022 // Pretend we are an array.
4023 if (!s
->addXMLStartTag(this, "array")) return false;
4025 nRanges
= _rangesCount
;
4026 vcopy
= (SerData
*) IOMalloc(sizeof(SerData
) * nRanges
);
4027 if (vcopy
== 0) return false;
4029 keys
[0] = OSSymbol::withCString("address");
4030 keys
[1] = OSSymbol::withCString("length");
4033 values
[0] = values
[1] = 0;
4035 // From this point on we can go to bail.
4037 // Copy the volatile data so we don't have to allocate memory
4038 // while the lock is held.
4040 if (nRanges
== _rangesCount
) {
4041 Ranges vec
= _ranges
;
4042 for (index
= 0; index
< nRanges
; index
++) {
4043 user_addr_t addr
; IOByteCount len
;
4044 getAddrLenForInd(addr
, len
, type
, vec
, index
);
4045 vcopy
[index
].address
= addr
;
4046 vcopy
[index
].length
= len
;
4049 // The descriptor changed out from under us. Give up.
4056 for (index
= 0; index
< nRanges
; index
++)
4058 user_addr_t addr
= vcopy
[index
].address
;
4059 IOByteCount len
= (IOByteCount
) vcopy
[index
].length
;
4061 OSNumber::withNumber(addr
, sizeof(addr
) * 8);
4062 if (values
[0] == 0) {
4066 values
[1] = OSNumber::withNumber(len
, sizeof(len
) * 8);
4067 if (values
[1] == 0) {
4071 OSDictionary
*dict
= OSDictionary::withObjects((const OSObject
**)values
, (const OSSymbol
**)keys
, 2);
4076 values
[0]->release();
4077 values
[1]->release();
4078 values
[0] = values
[1] = 0;
4080 result
= dict
->serialize(s
);
4086 result
= s
->addXMLEndTag("array");
4090 values
[0]->release();
4092 values
[1]->release();
4098 IOFree(vcopy
, sizeof(SerData
) * nRanges
);
4102 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4104 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 0);
4106 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 1);
4107 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 2);
4108 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 3);
4109 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 4);
4110 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 5);
4111 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 6);
4112 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 7);
4113 #else /* !__LP64__ */
4114 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 1);
4115 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 2);
4116 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 3);
4117 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 4);
4118 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 5);
4119 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 6);
4120 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 7);
4121 #endif /* !__LP64__ */
4122 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 8);
4123 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 9);
4124 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 10);
4125 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 11);
4126 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 12);
4127 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 13);
4128 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 14);
4129 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 15);
4131 /* ex-inline function implementation */
4133 IOMemoryDescriptor::getPhysicalAddress()
4134 { return( getPhysicalSegment( 0, 0 )); }