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;
909 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
912 if (_memoryEntries
&& (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
914 dataP
->fMapper
->iovmFree(atop_64(dataP
->fMappedBase
), _pages
);
915 dataP
->fMappedBase
= 0;
920 while (_wireCount
) complete();
923 if (_memoryEntries
) _memoryEntries
->release();
925 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
927 if (kIOMemoryTypeUIO
== type
)
928 uio_free((uio_t
) _ranges
.v
);
930 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
931 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
932 #endif /* !__LP64__ */
934 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
941 if (reserved
->dp
.devicePager
)
943 // memEntry holds a ref on the device pager which owns reserved
944 // (IOMemoryDescriptorReserved) so no reserved access after this point
945 device_pager_deallocate( (memory_object_t
) reserved
->dp
.devicePager
);
948 IODelete(reserved
, IOMemoryDescriptorReserved
, 1);
953 ipc_port_release_send( (ipc_port_t
) _memEntry
);
956 IOLockFree(_prepareLock
);
962 void IOGeneralMemoryDescriptor::unmapFromKernel()
964 panic("IOGMD::unmapFromKernel deprecated");
967 void IOGeneralMemoryDescriptor::mapIntoKernel(unsigned rangeIndex
)
969 panic("IOGMD::mapIntoKernel deprecated");
971 #endif /* !__LP64__ */
976 * Get the direction of the transfer.
978 IODirection
IOMemoryDescriptor::getDirection() const
983 #endif /* !__LP64__ */
984 return (IODirection
) (_flags
& kIOMemoryDirectionMask
);
990 * Get the length of the transfer (over all ranges).
992 IOByteCount
IOMemoryDescriptor::getLength() const
997 void IOMemoryDescriptor::setTag( IOOptionBits tag
)
1002 IOOptionBits
IOMemoryDescriptor::getTag( void )
1008 // @@@ gvdl: who is using this API? Seems like a wierd thing to implement.
1010 IOMemoryDescriptor::getSourceSegment( IOByteCount offset
, IOByteCount
* length
)
1012 addr64_t physAddr
= 0;
1014 if( prepare() == kIOReturnSuccess
) {
1015 physAddr
= getPhysicalSegment64( offset
, length
);
1019 return( (IOPhysicalAddress
) physAddr
); // truncated but only page offset is used
1021 #endif /* !__LP64__ */
1023 IOByteCount
IOMemoryDescriptor::readBytes
1024 (IOByteCount offset
, void *bytes
, IOByteCount length
)
1026 addr64_t dstAddr
= CAST_DOWN(addr64_t
, bytes
);
1027 IOByteCount remaining
;
1029 // Assert that this entire I/O is withing the available range
1030 assert(offset
< _length
);
1031 assert(offset
+ length
<= _length
);
1032 if (offset
>= _length
) {
1036 if (kIOMemoryThreadSafe
& _flags
)
1039 remaining
= length
= min(length
, _length
- offset
);
1040 while (remaining
) { // (process another target segment?)
1044 srcAddr64
= getPhysicalSegment(offset
, &srcLen
, kIOMemoryMapperNone
);
1048 // Clip segment length to remaining
1049 if (srcLen
> remaining
)
1052 copypv(srcAddr64
, dstAddr
, srcLen
,
1053 cppvPsrc
| cppvNoRefSrc
| cppvFsnk
| cppvKmap
);
1057 remaining
-= srcLen
;
1060 if (kIOMemoryThreadSafe
& _flags
)
1065 return length
- remaining
;
1068 IOByteCount
IOMemoryDescriptor::writeBytes
1069 (IOByteCount offset
, const void *bytes
, IOByteCount length
)
1071 addr64_t srcAddr
= CAST_DOWN(addr64_t
, bytes
);
1072 IOByteCount remaining
;
1074 // Assert that this entire I/O is withing the available range
1075 assert(offset
< _length
);
1076 assert(offset
+ length
<= _length
);
1078 assert( !(kIOMemoryPreparedReadOnly
& _flags
) );
1080 if ( (kIOMemoryPreparedReadOnly
& _flags
) || offset
>= _length
) {
1084 if (kIOMemoryThreadSafe
& _flags
)
1087 remaining
= length
= min(length
, _length
- offset
);
1088 while (remaining
) { // (process another target segment?)
1092 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1096 // Clip segment length to remaining
1097 if (dstLen
> remaining
)
1100 copypv(srcAddr
, (addr64_t
) dstAddr64
, dstLen
,
1101 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
1105 remaining
-= dstLen
;
1108 if (kIOMemoryThreadSafe
& _flags
)
1113 return length
- remaining
;
1116 // osfmk/device/iokit_rpc.c
1117 extern "C" unsigned int IODefaultCacheBits(addr64_t pa
);
1120 void IOGeneralMemoryDescriptor::setPosition(IOByteCount position
)
1122 panic("IOGMD::setPosition deprecated");
1124 #endif /* !__LP64__ */
1126 static volatile SInt64 gIOMDPreparationID
__attribute__((aligned(8))) = (1ULL << 32);
1129 IOGeneralMemoryDescriptor::getPreparationID( void )
1134 return (kIOPreparationIDUnprepared
);
1136 if (((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical
)
1137 || ((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical64
))
1139 IOMemoryDescriptor::setPreparationID();
1140 return (IOMemoryDescriptor::getPreparationID());
1143 if (!_memoryEntries
|| !(dataP
= getDataP(_memoryEntries
)))
1144 return (kIOPreparationIDUnprepared
);
1146 if (kIOPreparationIDUnprepared
== dataP
->fPreparationID
)
1148 dataP
->fPreparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1150 return (dataP
->fPreparationID
);
1153 IOMemoryDescriptorReserved
* IOMemoryDescriptor::getKernelReserved( void )
1157 reserved
= IONew(IOMemoryDescriptorReserved
, 1);
1159 bzero(reserved
, sizeof(IOMemoryDescriptorReserved
));
1164 void IOMemoryDescriptor::setPreparationID( void )
1166 if (getKernelReserved() && (kIOPreparationIDUnprepared
== reserved
->preparationID
))
1168 #if defined(__ppc__ )
1169 reserved
->preparationID
= gIOMDPreparationID
++;
1171 reserved
->preparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1176 uint64_t IOMemoryDescriptor::getPreparationID( void )
1179 return (reserved
->preparationID
);
1181 return (kIOPreparationIDUnsupported
);
1184 IOReturn
IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1186 IOReturn err
= kIOReturnSuccess
;
1187 DMACommandOps params
;
1188 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
1191 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
1192 op
&= kIOMDDMACommandOperationMask
;
1194 if (kIOMDDMAMap
== op
)
1196 if (dataSize
< sizeof(IOMDDMAMapArgs
))
1197 return kIOReturnUnderrun
;
1199 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
1202 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1204 if (_memoryEntries
&& data
->fMapper
)
1207 bool whole
= ((data
->fOffset
== 0) && (data
->fLength
== _length
));
1208 dataP
= getDataP(_memoryEntries
);
1209 if (data
->fMapSpec
.numAddressBits
< dataP
->fDMAMapNumAddressBits
)
1211 dataP
->fDMAMapNumAddressBits
= data
->fMapSpec
.numAddressBits
;
1212 remap
= ((dataP
->fMappedBase
+ _length
) > (1ULL << dataP
->fDMAMapNumAddressBits
));
1214 if (data
->fMapSpec
.alignment
> dataP
->fDMAMapAlignment
)
1216 dataP
->fDMAMapAlignment
= data
->fMapSpec
.alignment
;
1217 remap
|= (dataP
->fDMAMapAlignment
> page_size
);
1220 if (remap
|| !dataP
->fMappedBase
)
1222 // if (dataP->fMappedBase) OSReportWithBacktrace("kIOMDDMAMap whole %d remap %d params %d\n", whole, remap, params);
1223 err
= md
->dmaMap(data
->fMapper
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocCount
);
1224 if ((kIOReturnSuccess
== err
) && whole
&& !dataP
->fMappedBase
)
1226 dataP
->fMappedBase
= data
->fAlloc
;
1227 data
->fAllocCount
= 0; // IOMD owns the alloc now
1232 data
->fAlloc
= dataP
->fMappedBase
;
1233 data
->fAllocCount
= 0; // IOMD owns the alloc
1240 if (kIOMDAddDMAMapSpec
== op
)
1242 if (dataSize
< sizeof(IODMAMapSpecification
))
1243 return kIOReturnUnderrun
;
1245 IODMAMapSpecification
* data
= (IODMAMapSpecification
*) vData
;
1248 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1252 dataP
= getDataP(_memoryEntries
);
1253 if (data
->numAddressBits
< dataP
->fDMAMapNumAddressBits
)
1254 dataP
->fDMAMapNumAddressBits
= data
->numAddressBits
;
1255 if (data
->alignment
> dataP
->fDMAMapAlignment
)
1256 dataP
->fDMAMapAlignment
= data
->alignment
;
1258 return kIOReturnSuccess
;
1261 if (kIOMDGetCharacteristics
== op
) {
1263 if (dataSize
< sizeof(IOMDDMACharacteristics
))
1264 return kIOReturnUnderrun
;
1266 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
1267 data
->fLength
= _length
;
1268 data
->fSGCount
= _rangesCount
;
1269 data
->fPages
= _pages
;
1270 data
->fDirection
= getDirection();
1272 data
->fIsPrepared
= false;
1274 data
->fIsPrepared
= true;
1275 data
->fHighestPage
= _highestPage
;
1278 dataP
= getDataP(_memoryEntries
);
1279 ioPLBlock
*ioplList
= getIOPLList(dataP
);
1280 UInt count
= getNumIOPL(_memoryEntries
, dataP
);
1282 data
->fPageAlign
= (ioplList
[0].fPageOffset
& PAGE_MASK
) | ~PAGE_MASK
;
1286 return kIOReturnSuccess
;
1288 #if IOMD_DEBUG_DMAACTIVE
1289 } else if (kIOMDDMAActive
== op
) {
1290 if (params
) OSIncrementAtomic(&md
->__iomd_reservedA
);
1292 if (md
->__iomd_reservedA
)
1293 OSDecrementAtomic(&md
->__iomd_reservedA
);
1295 panic("kIOMDSetDMAInactive");
1297 #endif /* IOMD_DEBUG_DMAACTIVE */
1299 } else if (kIOMDWalkSegments
!= op
)
1300 return kIOReturnBadArgument
;
1302 // Get the next segment
1303 struct InternalState
{
1304 IOMDDMAWalkSegmentArgs fIO
;
1310 // Find the next segment
1311 if (dataSize
< sizeof(*isP
))
1312 return kIOReturnUnderrun
;
1314 isP
= (InternalState
*) vData
;
1315 UInt offset
= isP
->fIO
.fOffset
;
1316 bool mapped
= isP
->fIO
.fMapped
;
1318 if (IOMapper::gSystem
&& mapped
1319 && (!(kIOMemoryHostOnly
& _flags
))
1320 && (!_memoryEntries
|| !getDataP(_memoryEntries
)->fMappedBase
))
1321 // && (_memoryEntries && !getDataP(_memoryEntries)->fMappedBase))
1324 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
1326 dataP
= getDataP(_memoryEntries
);
1329 IODMAMapSpecification mapSpec
;
1330 bzero(&mapSpec
, sizeof(mapSpec
));
1331 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
1332 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
1333 err
= md
->dmaMap(dataP
->fMapper
, &mapSpec
, 0, _length
, &dataP
->fMappedBase
, NULL
);
1334 if (kIOReturnSuccess
!= err
) return (err
);
1338 if (offset
>= _length
)
1339 return (offset
== _length
)? kIOReturnOverrun
: kIOReturnInternalError
;
1341 // Validate the previous offset
1342 UInt ind
, off2Ind
= isP
->fOffset2Index
;
1345 && (offset
== isP
->fNextOffset
|| off2Ind
<= offset
))
1348 ind
= off2Ind
= 0; // Start from beginning
1354 if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
) {
1356 // Physical address based memory descriptor
1357 const IOPhysicalRange
*physP
= (IOPhysicalRange
*) &_ranges
.p
[0];
1359 // Find the range after the one that contains the offset
1361 for (len
= 0; off2Ind
<= offset
; ind
++) {
1362 len
= physP
[ind
].length
;
1366 // Calculate length within range and starting address
1367 length
= off2Ind
- offset
;
1368 address
= physP
[ind
- 1].address
+ len
- length
;
1370 if (true && mapped
&& _memoryEntries
1371 && (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
1373 address
= dataP
->fMappedBase
+ offset
;
1377 // see how far we can coalesce ranges
1378 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
1379 len
= physP
[ind
].length
;
1386 // correct contiguous check overshoot
1391 else if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
) {
1393 // Physical address based memory descriptor
1394 const IOAddressRange
*physP
= (IOAddressRange
*) &_ranges
.v64
[0];
1396 // Find the range after the one that contains the offset
1398 for (len
= 0; off2Ind
<= offset
; ind
++) {
1399 len
= physP
[ind
].length
;
1403 // Calculate length within range and starting address
1404 length
= off2Ind
- offset
;
1405 address
= physP
[ind
- 1].address
+ len
- length
;
1407 if (true && mapped
&& _memoryEntries
1408 && (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBase
)
1410 address
= dataP
->fMappedBase
+ offset
;
1414 // see how far we can coalesce ranges
1415 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
1416 len
= physP
[ind
].length
;
1422 // correct contiguous check overshoot
1426 #endif /* !__LP64__ */
1429 panic("IOGMD: not wired for the IODMACommand");
1431 assert(_memoryEntries
);
1433 dataP
= getDataP(_memoryEntries
);
1434 const ioPLBlock
*ioplList
= getIOPLList(dataP
);
1435 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
1436 upl_page_info_t
*pageList
= getPageList(dataP
);
1438 assert(numIOPLs
> 0);
1440 // Scan through iopl info blocks looking for block containing offset
1441 while (ind
< numIOPLs
&& offset
>= ioplList
[ind
].fIOMDOffset
)
1444 // Go back to actual range as search goes past it
1445 ioPLBlock ioplInfo
= ioplList
[ind
- 1];
1446 off2Ind
= ioplInfo
.fIOMDOffset
;
1449 length
= ioplList
[ind
].fIOMDOffset
;
1452 length
-= offset
; // Remainder within iopl
1454 // Subtract offset till this iopl in total list
1457 // If a mapped address is requested and this is a pre-mapped IOPL
1458 // then just need to compute an offset relative to the mapped base.
1459 if (mapped
&& dataP
->fMappedBase
) {
1460 offset
+= (ioplInfo
.fPageOffset
& PAGE_MASK
);
1461 address
= trunc_page_64(dataP
->fMappedBase
) + ptoa_64(ioplInfo
.fMappedPage
) + offset
;
1462 continue; // Done leave do/while(false) now
1465 // The offset is rebased into the current iopl.
1466 // Now add the iopl 1st page offset.
1467 offset
+= ioplInfo
.fPageOffset
;
1469 // For external UPLs the fPageInfo field points directly to
1470 // the upl's upl_page_info_t array.
1471 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
1472 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
1474 pageList
= &pageList
[ioplInfo
.fPageInfo
];
1476 // Check for direct device non-paged memory
1477 if ( ioplInfo
.fFlags
& kIOPLOnDevice
) {
1478 address
= ptoa_64(pageList
->phys_addr
) + offset
;
1479 continue; // Done leave do/while(false) now
1482 // Now we need compute the index into the pageList
1483 UInt pageInd
= atop_32(offset
);
1484 offset
&= PAGE_MASK
;
1486 // Compute the starting address of this segment
1487 IOPhysicalAddress pageAddr
= pageList
[pageInd
].phys_addr
;
1489 panic("!pageList phys_addr");
1492 address
= ptoa_64(pageAddr
) + offset
;
1494 // length is currently set to the length of the remainider of the iopl.
1495 // We need to check that the remainder of the iopl is contiguous.
1496 // This is indicated by pageList[ind].phys_addr being sequential.
1497 IOByteCount contigLength
= PAGE_SIZE
- offset
;
1498 while (contigLength
< length
1499 && ++pageAddr
== pageList
[++pageInd
].phys_addr
)
1501 contigLength
+= PAGE_SIZE
;
1504 if (contigLength
< length
)
1505 length
= contigLength
;
1513 // Update return values and state
1514 isP
->fIO
.fIOVMAddr
= address
;
1515 isP
->fIO
.fLength
= length
;
1517 isP
->fOffset2Index
= off2Ind
;
1518 isP
->fNextOffset
= isP
->fIO
.fOffset
+ length
;
1520 return kIOReturnSuccess
;
1524 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
1527 addr64_t address
= 0;
1528 IOByteCount length
= 0;
1529 IOMapper
* mapper
= gIOSystemMapper
;
1530 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1532 if (lengthOfSegment
)
1533 *lengthOfSegment
= 0;
1535 if (offset
>= _length
)
1538 // IOMemoryDescriptor::doMap() cannot use getPhysicalSegment() to obtain the page offset, since it must
1539 // support the unwired memory case in IOGeneralMemoryDescriptor, and hibernate_write_image() cannot use
1540 // map()->getVirtualAddress() to obtain the kernel pointer, since it must prevent the memory allocation
1541 // due to IOMemoryMap, so _kIOMemorySourceSegment is a necessary evil until all of this gets cleaned up
1543 if ((options
& _kIOMemorySourceSegment
) && (kIOMemoryTypeUPL
!= type
))
1545 unsigned rangesIndex
= 0;
1546 Ranges vec
= _ranges
;
1549 // Find starting address within the vector of ranges
1551 getAddrLenForInd(addr
, length
, type
, vec
, rangesIndex
);
1552 if (offset
< length
)
1554 offset
-= length
; // (make offset relative)
1558 // Now that we have the starting range,
1559 // lets find the last contiguous range
1563 for ( ++rangesIndex
; rangesIndex
< _rangesCount
; rangesIndex
++ ) {
1564 user_addr_t newAddr
;
1565 IOPhysicalLength newLen
;
1567 getAddrLenForInd(newAddr
, newLen
, type
, vec
, rangesIndex
);
1568 if (addr
+ length
!= newAddr
)
1573 address
= (IOPhysicalAddress
) addr
; // Truncate address to 32bit
1577 IOMDDMAWalkSegmentState _state
;
1578 IOMDDMAWalkSegmentArgs
* state
= (IOMDDMAWalkSegmentArgs
*) (void *)&_state
;
1580 state
->fOffset
= offset
;
1581 state
->fLength
= _length
- offset
;
1582 state
->fMapped
= (0 == (options
& kIOMemoryMapperNone
)) && !(_flags
& kIOMemoryHostOnly
);
1584 ret
= dmaCommandOperation(kIOMDFirstSegment
, _state
, sizeof(_state
));
1586 if ((kIOReturnSuccess
!= ret
) && (kIOReturnOverrun
!= ret
))
1587 DEBG("getPhysicalSegment dmaCommandOperation(%lx), %p, offset %qx, addr %qx, len %qx\n",
1588 ret
, this, state
->fOffset
,
1589 state
->fIOVMAddr
, state
->fLength
);
1590 if (kIOReturnSuccess
== ret
)
1592 address
= state
->fIOVMAddr
;
1593 length
= state
->fLength
;
1596 // dmaCommandOperation() does not distinguish between "mapped" and "unmapped" physical memory, even
1597 // with fMapped set correctly, so we must handle the transformation here until this gets cleaned up
1599 if (mapper
&& ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
)))
1601 if ((options
& kIOMemoryMapperNone
) && !(_flags
& kIOMemoryMapperNone
))
1603 addr64_t origAddr
= address
;
1604 IOByteCount origLen
= length
;
1606 address
= mapper
->mapAddr(origAddr
);
1607 length
= page_size
- (address
& (page_size
- 1));
1608 while ((length
< origLen
)
1609 && ((address
+ length
) == mapper
->mapAddr(origAddr
+ length
)))
1610 length
+= page_size
;
1611 if (length
> origLen
)
1620 if (lengthOfSegment
)
1621 *lengthOfSegment
= length
;
1628 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
1630 addr64_t address
= 0;
1632 if (options
& _kIOMemorySourceSegment
)
1634 address
= getSourceSegment(offset
, lengthOfSegment
);
1636 else if (options
& kIOMemoryMapperNone
)
1638 address
= getPhysicalSegment64(offset
, lengthOfSegment
);
1642 address
= getPhysicalSegment(offset
, lengthOfSegment
);
1649 IOGeneralMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1651 return (getPhysicalSegment(offset
, lengthOfSegment
, kIOMemoryMapperNone
));
1655 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1657 addr64_t address
= 0;
1658 IOByteCount length
= 0;
1660 address
= getPhysicalSegment(offset
, lengthOfSegment
, 0);
1662 if (lengthOfSegment
)
1663 length
= *lengthOfSegment
;
1665 if ((address
+ length
) > 0x100000000ULL
)
1667 panic("getPhysicalSegment() out of 32b range 0x%qx, len 0x%lx, class %s",
1668 address
, (long) length
, (getMetaClass())->getClassName());
1671 return ((IOPhysicalAddress
) address
);
1675 IOMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1677 IOPhysicalAddress phys32
;
1680 IOMapper
* mapper
= 0;
1682 phys32
= getPhysicalSegment(offset
, lengthOfSegment
);
1686 if (gIOSystemMapper
)
1687 mapper
= gIOSystemMapper
;
1691 IOByteCount origLen
;
1693 phys64
= mapper
->mapAddr(phys32
);
1694 origLen
= *lengthOfSegment
;
1695 length
= page_size
- (phys64
& (page_size
- 1));
1696 while ((length
< origLen
)
1697 && ((phys64
+ length
) == mapper
->mapAddr(phys32
+ length
)))
1698 length
+= page_size
;
1699 if (length
> origLen
)
1702 *lengthOfSegment
= length
;
1705 phys64
= (addr64_t
) phys32
;
1711 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1713 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, 0));
1717 IOGeneralMemoryDescriptor::getSourceSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
1719 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, _kIOMemorySourceSegment
));
1722 void * IOGeneralMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
1723 IOByteCount
* lengthOfSegment
)
1725 if (_task
== kernel_task
)
1726 return (void *) getSourceSegment(offset
, lengthOfSegment
);
1728 panic("IOGMD::getVirtualSegment deprecated");
1732 #endif /* !__LP64__ */
1735 IOMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
1737 IOMemoryDescriptor
*md
= const_cast<IOMemoryDescriptor
*>(this);
1738 DMACommandOps params
;
1741 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
1742 op
&= kIOMDDMACommandOperationMask
;
1744 if (kIOMDGetCharacteristics
== op
) {
1745 if (dataSize
< sizeof(IOMDDMACharacteristics
))
1746 return kIOReturnUnderrun
;
1748 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
1749 data
->fLength
= getLength();
1751 data
->fDirection
= getDirection();
1752 data
->fIsPrepared
= true; // Assume prepared - fails safe
1754 else if (kIOMDWalkSegments
== op
) {
1755 if (dataSize
< sizeof(IOMDDMAWalkSegmentArgs
))
1756 return kIOReturnUnderrun
;
1758 IOMDDMAWalkSegmentArgs
*data
= (IOMDDMAWalkSegmentArgs
*) vData
;
1759 IOByteCount offset
= (IOByteCount
) data
->fOffset
;
1761 IOPhysicalLength length
;
1762 if (data
->fMapped
&& IOMapper::gSystem
)
1763 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
);
1765 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
, kIOMemoryMapperNone
);
1766 data
->fLength
= length
;
1768 else if (kIOMDAddDMAMapSpec
== op
) return kIOReturnUnsupported
;
1769 else if (kIOMDDMAMap
== op
)
1771 if (dataSize
< sizeof(IOMDDMAMapArgs
))
1772 return kIOReturnUnderrun
;
1773 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
1775 if (params
) panic("class %s does not support IODMACommand::kIterateOnly", getMetaClass()->getClassName());
1777 err
= md
->dmaMap(data
->fMapper
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocCount
);
1780 else return kIOReturnBadArgument
;
1782 return kIOReturnSuccess
;
1786 purgeableControlBits(IOOptionBits newState
, vm_purgable_t
* control
, int * state
)
1788 IOReturn err
= kIOReturnSuccess
;
1790 *control
= VM_PURGABLE_SET_STATE
;
1793 case kIOMemoryPurgeableKeepCurrent
:
1794 *control
= VM_PURGABLE_GET_STATE
;
1797 case kIOMemoryPurgeableNonVolatile
:
1798 *state
= VM_PURGABLE_NONVOLATILE
;
1800 case kIOMemoryPurgeableVolatile
:
1801 *state
= VM_PURGABLE_VOLATILE
;
1803 case kIOMemoryPurgeableEmpty
:
1804 *state
= VM_PURGABLE_EMPTY
;
1807 err
= kIOReturnBadArgument
;
1814 purgeableStateBits(int * state
)
1816 IOReturn err
= kIOReturnSuccess
;
1820 case VM_PURGABLE_NONVOLATILE
:
1821 *state
= kIOMemoryPurgeableNonVolatile
;
1823 case VM_PURGABLE_VOLATILE
:
1824 *state
= kIOMemoryPurgeableVolatile
;
1826 case VM_PURGABLE_EMPTY
:
1827 *state
= kIOMemoryPurgeableEmpty
;
1830 *state
= kIOMemoryPurgeableNonVolatile
;
1831 err
= kIOReturnNotReady
;
1838 IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState
,
1839 IOOptionBits
* oldState
)
1841 IOReturn err
= kIOReturnSuccess
;
1842 vm_purgable_t control
;
1847 err
= super::setPurgeable(newState
, oldState
);
1851 if (kIOMemoryThreadSafe
& _flags
)
1855 // Find the appropriate vm_map for the given task
1857 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
1859 err
= kIOReturnNotReady
;
1863 curMap
= get_task_map(_task
);
1865 // can only do one range
1866 Ranges vec
= _ranges
;
1867 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1870 getAddrLenForInd(addr
, len
, type
, vec
, 0);
1872 err
= purgeableControlBits(newState
, &control
, &state
);
1873 if (kIOReturnSuccess
!= err
)
1875 err
= mach_vm_purgable_control(curMap
, addr
, control
, &state
);
1878 if (kIOReturnSuccess
== err
)
1880 err
= purgeableStateBits(&state
);
1886 if (kIOMemoryThreadSafe
& _flags
)
1892 IOReturn
IOMemoryDescriptor::setPurgeable( IOOptionBits newState
,
1893 IOOptionBits
* oldState
)
1895 IOReturn err
= kIOReturnSuccess
;
1896 vm_purgable_t control
;
1899 if (kIOMemoryThreadSafe
& _flags
)
1906 err
= kIOReturnNotReady
;
1909 err
= purgeableControlBits(newState
, &control
, &state
);
1910 if (kIOReturnSuccess
!= err
)
1912 err
= mach_memory_entry_purgable_control((ipc_port_t
) _memEntry
, control
, &state
);
1915 if (kIOReturnSuccess
== err
)
1917 err
= purgeableStateBits(&state
);
1924 if (kIOMemoryThreadSafe
& _flags
)
1930 extern "C" void dcache_incoherent_io_flush64(addr64_t pa
, unsigned int count
);
1931 extern "C" void dcache_incoherent_io_store64(addr64_t pa
, unsigned int count
);
1933 static void SetEncryptOp(addr64_t pa
, unsigned int count
)
1937 page
= atop_64(round_page_64(pa
));
1938 end
= atop_64(trunc_page_64(pa
+ count
));
1939 for (; page
< end
; page
++)
1941 pmap_clear_noencrypt(page
);
1945 static void ClearEncryptOp(addr64_t pa
, unsigned int count
)
1949 page
= atop_64(round_page_64(pa
));
1950 end
= atop_64(trunc_page_64(pa
+ count
));
1951 for (; page
< end
; page
++)
1953 pmap_set_noencrypt(page
);
1957 IOReturn
IOMemoryDescriptor::performOperation( IOOptionBits options
,
1958 IOByteCount offset
, IOByteCount length
)
1960 IOByteCount remaining
;
1962 void (*func
)(addr64_t pa
, unsigned int count
) = 0;
1966 case kIOMemoryIncoherentIOFlush
:
1967 func
= &dcache_incoherent_io_flush64
;
1969 case kIOMemoryIncoherentIOStore
:
1970 func
= &dcache_incoherent_io_store64
;
1973 case kIOMemorySetEncrypted
:
1974 func
= &SetEncryptOp
;
1976 case kIOMemoryClearEncrypted
:
1977 func
= &ClearEncryptOp
;
1982 return (kIOReturnUnsupported
);
1984 if (kIOMemoryThreadSafe
& _flags
)
1988 remaining
= length
= min(length
, getLength() - offset
);
1990 // (process another target segment?)
1995 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1999 // Clip segment length to remaining
2000 if (dstLen
> remaining
)
2003 (*func
)(dstAddr64
, dstLen
);
2006 remaining
-= dstLen
;
2009 if (kIOMemoryThreadSafe
& _flags
)
2012 return (remaining
? kIOReturnUnderrun
: kIOReturnSuccess
);
2015 #if defined(__i386__) || defined(__x86_64__)
2016 extern vm_offset_t first_avail
;
2017 #define io_kernel_static_end first_avail
2019 #error io_kernel_static_end is undefined for this architecture
2022 static kern_return_t
2023 io_get_kernel_static_upl(
2026 vm_size_t
*upl_size
,
2028 upl_page_info_array_t page_list
,
2029 unsigned int *count
,
2030 ppnum_t
*highest_page
)
2032 unsigned int pageCount
, page
;
2034 ppnum_t highestPage
= 0;
2036 pageCount
= atop_32(*upl_size
);
2037 if (pageCount
> *count
)
2042 for (page
= 0; page
< pageCount
; page
++)
2044 phys
= pmap_find_phys(kernel_pmap
, ((addr64_t
)offset
) + ptoa_64(page
));
2047 page_list
[page
].phys_addr
= phys
;
2048 page_list
[page
].pageout
= 0;
2049 page_list
[page
].absent
= 0;
2050 page_list
[page
].dirty
= 0;
2051 page_list
[page
].precious
= 0;
2052 page_list
[page
].device
= 0;
2053 if (phys
> highestPage
)
2057 *highest_page
= highestPage
;
2059 return ((page
>= pageCount
) ? kIOReturnSuccess
: kIOReturnVMError
);
2062 IOReturn
IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection
)
2064 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2065 IOReturn error
= kIOReturnCannotWire
;
2067 upl_page_info_array_t pageInfo
;
2068 ppnum_t mapBase
= 0;
2069 ipc_port_t sharedMem
= (ipc_port_t
) _memEntry
;
2071 assert(!_wireCount
);
2072 assert(kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
);
2074 if (_pages
> gIOMaximumMappedIOPageCount
)
2075 return kIOReturnNoResources
;
2077 dataP
= getDataP(_memoryEntries
);
2079 mapper
= dataP
->fMapper
;
2080 dataP
->fMappedBase
= 0;
2082 if (forDirection
== kIODirectionNone
)
2083 forDirection
= getDirection();
2085 int uplFlags
; // This Mem Desc's default flags for upl creation
2086 switch (kIODirectionOutIn
& forDirection
)
2088 case kIODirectionOut
:
2089 // Pages do not need to be marked as dirty on commit
2090 uplFlags
= UPL_COPYOUT_FROM
;
2091 _flags
|= kIOMemoryPreparedReadOnly
;
2094 case kIODirectionIn
:
2096 uplFlags
= 0; // i.e. ~UPL_COPYOUT_FROM
2099 uplFlags
|= UPL_SET_IO_WIRE
| UPL_SET_LITE
;
2101 #ifdef UPL_NEED_32BIT_ADDR
2102 if (kIODirectionPrepareToPhys32
& forDirection
)
2104 if (!mapper
) uplFlags
|= UPL_NEED_32BIT_ADDR
;
2105 if (dataP
->fDMAMapNumAddressBits
> 32) dataP
->fDMAMapNumAddressBits
= 32;
2109 // Note that appendBytes(NULL) zeros the data up to the desired length.
2110 _memoryEntries
->appendBytes(0, dataP
->fPageCnt
* sizeof(upl_page_info_t
));
2113 // Find the appropriate vm_map for the given task
2115 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
2118 { curMap
= get_task_map(_task
); }
2120 // Iterate over the vector of virtual ranges
2121 Ranges vec
= _ranges
;
2122 unsigned int pageIndex
= 0;
2123 IOByteCount mdOffset
= 0;
2124 ppnum_t highestPage
= 0;
2126 for (UInt range
= 0; range
< _rangesCount
; range
++) {
2128 user_addr_t startPage
;
2129 IOByteCount numBytes
;
2130 ppnum_t highPage
= 0;
2132 // Get the startPage address and length of vec[range]
2133 getAddrLenForInd(startPage
, numBytes
, type
, vec
, range
);
2134 iopl
.fPageOffset
= startPage
& PAGE_MASK
;
2135 numBytes
+= iopl
.fPageOffset
;
2136 startPage
= trunc_page_64(startPage
);
2139 iopl
.fMappedPage
= mapBase
+ pageIndex
;
2141 iopl
.fMappedPage
= 0;
2143 // Iterate over the current range, creating UPLs
2145 vm_address_t kernelStart
= (vm_address_t
) startPage
;
2149 else if (!sharedMem
) {
2150 assert(_task
== kernel_task
);
2151 theMap
= IOPageableMapForAddress(kernelStart
);
2156 int ioplFlags
= uplFlags
;
2157 dataP
= getDataP(_memoryEntries
);
2158 pageInfo
= getPageList(dataP
);
2159 upl_page_list_ptr_t baseInfo
= &pageInfo
[pageIndex
];
2161 vm_size_t ioplSize
= round_page(numBytes
);
2162 unsigned int numPageInfo
= atop_32(ioplSize
);
2164 if (theMap
== kernel_map
&& kernelStart
< io_kernel_static_end
) {
2165 error
= io_get_kernel_static_upl(theMap
,
2173 else if (sharedMem
) {
2174 error
= memory_object_iopl_request(sharedMem
,
2184 error
= vm_map_create_upl(theMap
,
2186 (upl_size_t
*)&ioplSize
,
2194 if (error
!= KERN_SUCCESS
)
2198 highPage
= upl_get_highest_page(iopl
.fIOPL
);
2199 if (highPage
> highestPage
)
2200 highestPage
= highPage
;
2202 error
= kIOReturnCannotWire
;
2204 if (baseInfo
->device
) {
2206 iopl
.fFlags
= kIOPLOnDevice
;
2212 iopl
.fIOMDOffset
= mdOffset
;
2213 iopl
.fPageInfo
= pageIndex
;
2216 // used to remove the upl for auto prepares here, for some errant code
2217 // that freed memory before the descriptor pointing at it
2218 if ((_flags
& kIOMemoryAutoPrepare
) && iopl
.fIOPL
)
2220 upl_commit(iopl
.fIOPL
, 0, 0);
2221 upl_deallocate(iopl
.fIOPL
);
2226 if (!_memoryEntries
->appendBytes(&iopl
, sizeof(iopl
))) {
2227 // Clean up partial created and unsaved iopl
2229 upl_abort(iopl
.fIOPL
, 0);
2230 upl_deallocate(iopl
.fIOPL
);
2236 // Check for a multiple iopl's in one virtual range
2237 pageIndex
+= numPageInfo
;
2238 mdOffset
-= iopl
.fPageOffset
;
2239 if (ioplSize
< numBytes
) {
2240 numBytes
-= ioplSize
;
2241 startPage
+= ioplSize
;
2242 mdOffset
+= ioplSize
;
2243 iopl
.fPageOffset
= 0;
2244 if (mapper
) iopl
.fMappedPage
= mapBase
+ pageIndex
;
2247 mdOffset
+= numBytes
;
2253 _highestPage
= highestPage
;
2255 return kIOReturnSuccess
;
2259 dataP
= getDataP(_memoryEntries
);
2260 UInt done
= getNumIOPL(_memoryEntries
, dataP
);
2261 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2263 for (UInt range
= 0; range
< done
; range
++)
2265 if (ioplList
[range
].fIOPL
) {
2266 upl_abort(ioplList
[range
].fIOPL
, 0);
2267 upl_deallocate(ioplList
[range
].fIOPL
);
2270 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
2273 if (error
== KERN_FAILURE
)
2274 error
= kIOReturnCannotWire
;
2279 bool IOGeneralMemoryDescriptor::initMemoryEntries(size_t size
, IOMapper
* mapper
)
2282 unsigned dataSize
= size
;
2284 if (!_memoryEntries
) {
2285 _memoryEntries
= OSData::withCapacity(dataSize
);
2286 if (!_memoryEntries
)
2289 else if (!_memoryEntries
->initWithCapacity(dataSize
))
2292 _memoryEntries
->appendBytes(0, computeDataSize(0, 0));
2293 dataP
= getDataP(_memoryEntries
);
2295 if (mapper
== kIOMapperWaitSystem
) {
2296 IOMapper::checkForSystemMapper();
2297 mapper
= IOMapper::gSystem
;
2299 dataP
->fMapper
= mapper
;
2300 dataP
->fPageCnt
= 0;
2301 dataP
->fMappedBase
= 0;
2302 dataP
->fDMAMapNumAddressBits
= 64;
2303 dataP
->fDMAMapAlignment
= 0;
2304 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
2309 IOReturn
IOMemoryDescriptor::dmaMap(
2311 const IODMAMapSpecification
* mapSpec
,
2317 IOMDDMAWalkSegmentState walkState
;
2318 IOMDDMAWalkSegmentArgs
* walkArgs
= (IOMDDMAWalkSegmentArgs
*) (void *)&walkState
;
2321 IOPhysicalLength segLen
;
2322 addr64_t phys
, align
, pageOffset
;
2323 ppnum_t base
, pageIndex
, pageCount
;
2325 uint32_t mapOptions
= 0;
2327 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
2329 walkArgs
->fMapped
= false;
2330 mdOp
= kIOMDFirstSegment
;
2332 for (index
= 0; index
< length
; )
2334 if (index
&& (page_mask
& (index
+ pageOffset
))) break;
2336 walkArgs
->fOffset
= offset
+ index
;
2337 ret
= dmaCommandOperation(mdOp
, &walkState
, sizeof(walkState
));
2338 mdOp
= kIOMDWalkSegments
;
2339 if (ret
!= kIOReturnSuccess
) break;
2340 phys
= walkArgs
->fIOVMAddr
;
2341 segLen
= walkArgs
->fLength
;
2343 align
= (phys
& page_mask
);
2344 if (!index
) pageOffset
= align
;
2345 else if (align
) break;
2346 pageCount
+= atop_64(round_page_64(align
+ segLen
));
2350 if (index
< length
) return (kIOReturnVMError
);
2352 base
= mapper
->iovmMapMemory(this, offset
, pageCount
,
2353 mapOptions
, NULL
, mapSpec
);
2355 if (!base
) return (kIOReturnNoResources
);
2357 mdOp
= kIOMDFirstSegment
;
2358 for (pageIndex
= 0, index
= 0; index
< length
; )
2360 walkArgs
->fOffset
= offset
+ index
;
2361 ret
= dmaCommandOperation(mdOp
, &walkState
, sizeof(walkState
));
2362 mdOp
= kIOMDWalkSegments
;
2363 if (ret
!= kIOReturnSuccess
) break;
2364 phys
= walkArgs
->fIOVMAddr
;
2365 segLen
= walkArgs
->fLength
;
2367 ppnum_t page
= atop_64(phys
);
2368 ppnum_t count
= atop_64(round_page_64(phys
+ segLen
)) - page
;
2371 mapper
->iovmInsert(base
, pageIndex
, page
);
2377 if (pageIndex
!= pageCount
) panic("pageIndex");
2379 *address
= ptoa_64(base
) + pageOffset
;
2380 if (mapPages
) *mapPages
= pageCount
;
2382 return (kIOReturnSuccess
);
2385 IOReturn
IOGeneralMemoryDescriptor::dmaMap(
2387 const IODMAMapSpecification
* mapSpec
,
2393 IOReturn err
= kIOReturnSuccess
;
2395 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2398 if (kIOMemoryHostOnly
& _flags
) return (kIOReturnSuccess
);
2400 if ((type
== kIOMemoryTypePhysical
) || (type
== kIOMemoryTypePhysical64
)
2401 || offset
|| (length
!= _length
))
2403 err
= super::dmaMap(mapper
, mapSpec
, offset
, length
, address
, mapPages
);
2405 else if (_memoryEntries
&& _pages
&& (dataP
= getDataP(_memoryEntries
)))
2407 const ioPLBlock
* ioplList
= getIOPLList(dataP
);
2408 upl_page_info_t
* pageList
;
2409 uint32_t mapOptions
= 0;
2412 IODMAMapSpecification mapSpec
;
2413 bzero(&mapSpec
, sizeof(mapSpec
));
2414 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
2415 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
2417 // For external UPLs the fPageInfo field points directly to
2418 // the upl's upl_page_info_t array.
2419 if (ioplList
->fFlags
& kIOPLExternUPL
)
2421 pageList
= (upl_page_info_t
*) ioplList
->fPageInfo
;
2422 mapOptions
|= kIODMAMapPagingPath
;
2425 pageList
= getPageList(dataP
);
2427 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
2429 // Check for direct device non-paged memory
2430 if (ioplList
->fFlags
& kIOPLOnDevice
) mapOptions
|= kIODMAMapPhysicallyContiguous
;
2432 base
= mapper
->iovmMapMemory(
2433 this, offset
, _pages
, mapOptions
, &pageList
[0], &mapSpec
);
2434 *address
= ptoa_64(base
) + (ioplList
->fPageOffset
& PAGE_MASK
);
2435 if (mapPages
) *mapPages
= _pages
;
2444 * Prepare the memory for an I/O transfer. This involves paging in
2445 * the memory, if necessary, and wiring it down for the duration of
2446 * the transfer. The complete() method completes the processing of
2447 * the memory after the I/O transfer finishes. This method needn't
2448 * called for non-pageable memory.
2451 IOReturn
IOGeneralMemoryDescriptor::prepare(IODirection forDirection
)
2453 IOReturn error
= kIOReturnSuccess
;
2454 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2456 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
2457 return kIOReturnSuccess
;
2460 IOLockLock(_prepareLock
);
2463 && (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) ) {
2464 error
= wireVirtual(forDirection
);
2467 if (kIOReturnSuccess
== error
)
2469 if (1 == ++_wireCount
)
2471 if (kIOMemoryClearEncrypt
& _flags
)
2473 performOperation(kIOMemoryClearEncrypted
, 0, _length
);
2479 IOLockUnlock(_prepareLock
);
2487 * Complete processing of the memory after an I/O transfer finishes.
2488 * This method should not be called unless a prepare was previously
2489 * issued; the prepare() and complete() must occur in pairs, before
2490 * before and after an I/O transfer involving pageable memory.
2493 IOReturn
IOGeneralMemoryDescriptor::complete(IODirection
/* forDirection */)
2495 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2497 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
2498 return kIOReturnSuccess
;
2501 IOLockLock(_prepareLock
);
2507 if ((kIOMemoryClearEncrypt
& _flags
) && (1 == _wireCount
))
2509 performOperation(kIOMemorySetEncrypted
, 0, _length
);
2515 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2516 ioGMDData
* dataP
= getDataP(_memoryEntries
);
2517 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2518 UInt count
= getNumIOPL(_memoryEntries
, dataP
);
2520 #if IOMD_DEBUG_DMAACTIVE
2521 if (__iomd_reservedA
) panic("complete() while dma active");
2522 #endif /* IOMD_DEBUG_DMAACTIVE */
2524 if (dataP
->fMappedBase
) {
2525 dataP
->fMapper
->iovmFree(atop_64(dataP
->fMappedBase
), _pages
);
2526 dataP
->fMappedBase
= 0;
2528 // Only complete iopls that we created which are for TypeVirtual
2529 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
) {
2530 for (UInt ind
= 0; ind
< count
; ind
++)
2531 if (ioplList
[ind
].fIOPL
) {
2532 upl_commit(ioplList
[ind
].fIOPL
, 0, 0);
2533 upl_deallocate(ioplList
[ind
].fIOPL
);
2535 } else if (kIOMemoryTypeUPL
== type
) {
2536 upl_set_referenced(ioplList
[0].fIOPL
, false);
2539 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
2541 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
2546 IOLockUnlock(_prepareLock
);
2548 return kIOReturnSuccess
;
2551 IOReturn
IOGeneralMemoryDescriptor::doMap(
2552 vm_map_t __addressMap
,
2553 IOVirtualAddress
* __address
,
2554 IOOptionBits options
,
2555 IOByteCount __offset
,
2556 IOByteCount __length
)
2560 if (!(kIOMap64Bit
& options
)) panic("IOGeneralMemoryDescriptor::doMap !64bit");
2561 #endif /* !__LP64__ */
2563 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
2564 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
2565 mach_vm_size_t length
= mapping
->fLength
;
2567 kern_return_t kr
= kIOReturnVMError
;
2568 ipc_port_t sharedMem
= (ipc_port_t
) _memEntry
;
2570 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2571 Ranges vec
= _ranges
;
2573 user_addr_t range0Addr
= 0;
2574 IOByteCount range0Len
= 0;
2576 if ((offset
>= _length
) || ((offset
+ length
) > _length
))
2577 return( kIOReturnBadArgument
);
2580 getAddrLenForInd(range0Addr
, range0Len
, type
, vec
, 0);
2582 // mapping source == dest? (could be much better)
2584 && (mapping
->fAddressMap
== get_task_map(_task
)) && (options
& kIOMapAnywhere
)
2585 && (1 == _rangesCount
) && (0 == offset
)
2586 && range0Addr
&& (length
<= range0Len
) )
2588 mapping
->fAddress
= range0Addr
;
2589 mapping
->fOptions
|= kIOMapStatic
;
2591 return( kIOReturnSuccess
);
2594 if( 0 == sharedMem
) {
2596 vm_size_t size
= ptoa_32(_pages
);
2600 memory_object_size_t actualSize
= size
;
2601 vm_prot_t prot
= VM_PROT_READ
;
2602 if (!(kIOMapReadOnly
& options
))
2603 prot
|= VM_PROT_WRITE
;
2604 else if (kIOMapDefaultCache
!= (options
& kIOMapCacheMask
))
2605 prot
|= VM_PROT_WRITE
;
2607 if (_rangesCount
== 1)
2609 kr
= mach_make_memory_entry_64(get_task_map(_task
),
2610 &actualSize
, range0Addr
,
2614 if( (_rangesCount
!= 1)
2615 || ((KERN_SUCCESS
== kr
) && (actualSize
!= round_page(size
))))
2619 IOLog("mach_vm_remap path for ranges %d size (%08llx:%08llx)\n",
2620 _rangesCount
, (UInt64
)actualSize
, (UInt64
)size
);
2622 kr
= kIOReturnVMError
;
2625 ipc_port_release_send(sharedMem
);
2626 sharedMem
= MACH_PORT_NULL
;
2629 mach_vm_address_t address
, segDestAddr
;
2630 mach_vm_size_t mapLength
;
2631 unsigned rangesIndex
;
2632 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2633 user_addr_t srcAddr
;
2634 IOPhysicalLength segLen
= 0;
2636 // Find starting address within the vector of ranges
2637 for (rangesIndex
= 0; rangesIndex
< _rangesCount
; rangesIndex
++) {
2638 getAddrLenForInd(srcAddr
, segLen
, type
, _ranges
, rangesIndex
);
2639 if (offset
< segLen
)
2641 offset
-= segLen
; // (make offset relative)
2644 mach_vm_size_t pageOffset
= (srcAddr
& PAGE_MASK
);
2645 address
= trunc_page_64(mapping
->fAddress
);
2647 if ((options
& kIOMapAnywhere
) || ((mapping
->fAddress
- address
) == pageOffset
))
2649 vm_map_t map
= mapping
->fAddressMap
;
2650 kr
= IOMemoryDescriptorMapCopy(&map
,
2652 offset
, &address
, round_page_64(length
+ pageOffset
));
2653 if (kr
== KERN_SUCCESS
)
2655 segDestAddr
= address
;
2662 vm_prot_t cur_prot
, max_prot
;
2664 if (segLen
> length
) segLen
= length
;
2665 kr
= mach_vm_remap(map
, &segDestAddr
, round_page_64(segLen
), PAGE_MASK
,
2666 VM_FLAGS_FIXED
| VM_FLAGS_OVERWRITE
,
2667 get_task_map(_task
), trunc_page_64(srcAddr
),
2672 if (KERN_SUCCESS
== kr
)
2674 if ((!(VM_PROT_READ
& cur_prot
))
2675 || (!(kIOMapReadOnly
& options
) && !(VM_PROT_WRITE
& cur_prot
)))
2677 kr
= KERN_PROTECTION_FAILURE
;
2680 if (KERN_SUCCESS
!= kr
)
2682 segDestAddr
+= segLen
;
2683 mapLength
-= segLen
;
2687 if (rangesIndex
>= _rangesCount
)
2689 kr
= kIOReturnBadArgument
;
2692 getAddrLenForInd(srcAddr
, segLen
, type
, vec
, rangesIndex
);
2693 if (srcAddr
& PAGE_MASK
)
2695 kr
= kIOReturnBadArgument
;
2698 if (segLen
> mapLength
)
2701 if (KERN_SUCCESS
!= kr
)
2703 mach_vm_deallocate(mapping
->fAddressMap
, address
, round_page_64(length
+ pageOffset
));
2707 if (KERN_SUCCESS
== kr
)
2708 mapping
->fAddress
= address
+ pageOffset
;
2710 mapping
->fAddress
= NULL
;
2716 { // _task == 0, must be physical
2718 memory_object_t pager
;
2719 unsigned int flags
= 0;
2721 IOPhysicalLength segLen
;
2723 pa
= getPhysicalSegment( offset
, &segLen
, kIOMemoryMapperNone
);
2725 if( !getKernelReserved())
2727 reserved
->dp
.pagerContig
= (1 == _rangesCount
);
2728 reserved
->dp
.memory
= this;
2730 /*What cache mode do we need*/
2731 switch(options
& kIOMapCacheMask
) {
2733 case kIOMapDefaultCache
:
2735 flags
= IODefaultCacheBits(pa
);
2736 if (DEVICE_PAGER_CACHE_INHIB
& flags
)
2738 if (DEVICE_PAGER_GUARDED
& flags
)
2739 mapping
->fOptions
|= kIOMapInhibitCache
;
2741 mapping
->fOptions
|= kIOMapWriteCombineCache
;
2743 else if (DEVICE_PAGER_WRITE_THROUGH
& flags
)
2744 mapping
->fOptions
|= kIOMapWriteThruCache
;
2746 mapping
->fOptions
|= kIOMapCopybackCache
;
2749 case kIOMapInhibitCache
:
2750 flags
= DEVICE_PAGER_CACHE_INHIB
|
2751 DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
2754 case kIOMapWriteThruCache
:
2755 flags
= DEVICE_PAGER_WRITE_THROUGH
|
2756 DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
2759 case kIOMapCopybackCache
:
2760 flags
= DEVICE_PAGER_COHERENT
;
2763 case kIOMapWriteCombineCache
:
2764 flags
= DEVICE_PAGER_CACHE_INHIB
|
2765 DEVICE_PAGER_COHERENT
;
2769 flags
|= reserved
->dp
.pagerContig
? DEVICE_PAGER_CONTIGUOUS
: 0;
2771 pager
= device_pager_setup( (memory_object_t
) 0, (uintptr_t) reserved
,
2776 kr
= mach_memory_object_memory_entry_64( (host_t
) 1, false /*internal*/,
2777 size
, VM_PROT_READ
| VM_PROT_WRITE
, pager
, &sharedMem
);
2779 assert( KERN_SUCCESS
== kr
);
2780 if( KERN_SUCCESS
!= kr
)
2782 device_pager_deallocate( pager
);
2783 pager
= MACH_PORT_NULL
;
2784 sharedMem
= MACH_PORT_NULL
;
2787 if( pager
&& sharedMem
)
2788 reserved
->dp
.devicePager
= pager
;
2792 _memEntry
= (void *) sharedMem
;
2799 result
= super::doMap( __addressMap
, __address
,
2800 options
, __offset
, __length
);
2805 IOReturn
IOGeneralMemoryDescriptor::doUnmap(
2806 vm_map_t addressMap
,
2807 IOVirtualAddress __address
,
2808 IOByteCount __length
)
2810 return (super::doUnmap(addressMap
, __address
, __length
));
2813 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2816 #define super OSObject
2818 OSDefineMetaClassAndStructors( IOMemoryMap
, OSObject
)
2820 OSMetaClassDefineReservedUnused(IOMemoryMap
, 0);
2821 OSMetaClassDefineReservedUnused(IOMemoryMap
, 1);
2822 OSMetaClassDefineReservedUnused(IOMemoryMap
, 2);
2823 OSMetaClassDefineReservedUnused(IOMemoryMap
, 3);
2824 OSMetaClassDefineReservedUnused(IOMemoryMap
, 4);
2825 OSMetaClassDefineReservedUnused(IOMemoryMap
, 5);
2826 OSMetaClassDefineReservedUnused(IOMemoryMap
, 6);
2827 OSMetaClassDefineReservedUnused(IOMemoryMap
, 7);
2829 /* ex-inline function implementation */
2830 IOPhysicalAddress
IOMemoryMap::getPhysicalAddress()
2831 { return( getPhysicalSegment( 0, 0 )); }
2833 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2835 bool IOMemoryMap::init(
2837 mach_vm_address_t toAddress
,
2838 IOOptionBits _options
,
2839 mach_vm_size_t _offset
,
2840 mach_vm_size_t _length
)
2848 fAddressMap
= get_task_map(intoTask
);
2851 vm_map_reference(fAddressMap
);
2853 fAddressTask
= intoTask
;
2854 fOptions
= _options
;
2857 fAddress
= toAddress
;
2862 bool IOMemoryMap::setMemoryDescriptor(IOMemoryDescriptor
* _memory
, mach_vm_size_t _offset
)
2869 if( (_offset
+ fLength
) > _memory
->getLength())
2877 if (fMemory
!= _memory
)
2878 fMemory
->removeMapping(this);
2886 struct IOMemoryDescriptorMapAllocRef
2888 ipc_port_t sharedMem
;
2890 mach_vm_address_t mapped
;
2891 mach_vm_size_t size
;
2892 mach_vm_size_t sourceOffset
;
2893 IOOptionBits options
;
2896 static kern_return_t
IOMemoryDescriptorMapAlloc(vm_map_t map
, void * _ref
)
2898 IOMemoryDescriptorMapAllocRef
* ref
= (IOMemoryDescriptorMapAllocRef
*)_ref
;
2904 vm_prot_t prot
= VM_PROT_READ
2905 | ((ref
->options
& kIOMapReadOnly
) ? 0 : VM_PROT_WRITE
);
2907 // VM system requires write access to change cache mode
2908 if (kIOMapDefaultCache
!= (ref
->options
& kIOMapCacheMask
))
2909 prot
|= VM_PROT_WRITE
;
2911 // set memory entry cache
2912 vm_prot_t memEntryCacheMode
= prot
| MAP_MEM_ONLY
;
2913 switch (ref
->options
& kIOMapCacheMask
)
2915 case kIOMapInhibitCache
:
2916 SET_MAP_MEM(MAP_MEM_IO
, memEntryCacheMode
);
2919 case kIOMapWriteThruCache
:
2920 SET_MAP_MEM(MAP_MEM_WTHRU
, memEntryCacheMode
);
2923 case kIOMapWriteCombineCache
:
2924 SET_MAP_MEM(MAP_MEM_WCOMB
, memEntryCacheMode
);
2927 case kIOMapCopybackCache
:
2928 SET_MAP_MEM(MAP_MEM_COPYBACK
, memEntryCacheMode
);
2931 case kIOMapCopybackInnerCache
:
2932 SET_MAP_MEM(MAP_MEM_INNERWBACK
, memEntryCacheMode
);
2935 case kIOMapDefaultCache
:
2937 SET_MAP_MEM(MAP_MEM_NOOP
, memEntryCacheMode
);
2941 vm_size_t unused
= 0;
2943 err
= mach_make_memory_entry( NULL
/*unused*/, &unused
, 0 /*unused*/,
2944 memEntryCacheMode
, NULL
, ref
->sharedMem
);
2945 if (KERN_SUCCESS
!= err
)
2946 IOLog("MAP_MEM_ONLY failed %d\n", err
);
2948 err
= mach_vm_map( map
,
2950 ref
->size
, 0 /* mask */,
2951 (( ref
->options
& kIOMapAnywhere
) ? VM_FLAGS_ANYWHERE
: VM_FLAGS_FIXED
)
2952 | VM_MAKE_TAG(VM_MEMORY_IOKIT
),
2953 ref
->sharedMem
, ref
->sourceOffset
,
2959 if( KERN_SUCCESS
!= err
) {
2967 err
= mach_vm_allocate(map
, &ref
->mapped
, ref
->size
,
2968 ((ref
->options
& kIOMapAnywhere
) ? VM_FLAGS_ANYWHERE
: VM_FLAGS_FIXED
)
2969 | VM_MAKE_TAG(VM_MEMORY_IOKIT
) );
2970 if( KERN_SUCCESS
!= err
) {
2975 // we have to make sure that these guys don't get copied if we fork.
2976 err
= vm_inherit(map
, ref
->mapped
, ref
->size
, VM_INHERIT_NONE
);
2977 assert( KERN_SUCCESS
== err
);
2986 IOMemoryDescriptorMapMemEntry(vm_map_t
* map
, ipc_port_t entry
, IOOptionBits options
, bool pageable
,
2987 mach_vm_size_t offset
,
2988 mach_vm_address_t
* address
, mach_vm_size_t length
)
2991 IOMemoryDescriptorMapAllocRef ref
;
2994 ref
.sharedMem
= entry
;
2995 ref
.sourceOffset
= trunc_page_64(offset
);
2996 ref
.options
= options
;
2999 if (options
& kIOMapAnywhere
)
3000 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
3003 ref
.mapped
= *address
;
3005 if( ref
.sharedMem
&& (ref
.map
== kernel_map
) && pageable
)
3006 err
= IOIteratePageableMaps( ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
3008 err
= IOMemoryDescriptorMapAlloc( ref
.map
, &ref
);
3010 *address
= ref
.mapped
;
3017 IOMemoryDescriptorMapCopy(vm_map_t
* map
,
3018 IOOptionBits options
,
3019 mach_vm_size_t offset
,
3020 mach_vm_address_t
* address
, mach_vm_size_t length
)
3023 IOMemoryDescriptorMapAllocRef ref
;
3026 ref
.sharedMem
= NULL
;
3027 ref
.sourceOffset
= trunc_page_64(offset
);
3028 ref
.options
= options
;
3031 if (options
& kIOMapAnywhere
)
3032 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
3035 ref
.mapped
= *address
;
3037 if (ref
.map
== kernel_map
)
3038 err
= IOIteratePageableMaps(ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
3040 err
= IOMemoryDescriptorMapAlloc(ref
.map
, &ref
);
3042 *address
= ref
.mapped
;
3048 IOReturn
IOMemoryDescriptor::doMap(
3049 vm_map_t __addressMap
,
3050 IOVirtualAddress
* __address
,
3051 IOOptionBits options
,
3052 IOByteCount __offset
,
3053 IOByteCount __length
)
3056 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::doMap !64bit");
3057 #endif /* !__LP64__ */
3059 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
3060 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3061 mach_vm_size_t length
= mapping
->fLength
;
3063 IOReturn err
= kIOReturnSuccess
;
3064 memory_object_t pager
;
3065 mach_vm_size_t pageOffset
;
3066 IOPhysicalAddress sourceAddr
;
3067 unsigned int lock_count
;
3071 sourceAddr
= getPhysicalSegment( offset
, NULL
, _kIOMemorySourceSegment
);
3072 pageOffset
= sourceAddr
- trunc_page( sourceAddr
);
3075 pager
= (memory_object_t
) reserved
->dp
.devicePager
;
3077 pager
= MACH_PORT_NULL
;
3079 if ((kIOMapReference
|kIOMapUnique
) == ((kIOMapReference
|kIOMapUnique
) & options
))
3087 err
= kIOReturnNotReadable
;
3091 size
= round_page(mapping
->fLength
+ pageOffset
);
3092 flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3093 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
3095 if (KERN_SUCCESS
!= memory_object_iopl_request((ipc_port_t
) _memEntry
, 0, &size
, &redirUPL2
,
3100 for (lock_count
= 0;
3101 IORecursiveLockHaveLock(gIOMemoryLock
);
3105 err
= upl_transpose(redirUPL2
, mapping
->fRedirUPL
);
3112 if (kIOReturnSuccess
!= err
)
3114 IOLog("upl_transpose(%x)\n", err
);
3115 err
= kIOReturnSuccess
;
3120 upl_commit(redirUPL2
, NULL
, 0);
3121 upl_deallocate(redirUPL2
);
3125 // swap the memEntries since they now refer to different vm_objects
3126 void * me
= _memEntry
;
3127 _memEntry
= mapping
->fMemory
->_memEntry
;
3128 mapping
->fMemory
->_memEntry
= me
;
3131 err
= handleFault( pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
3135 mach_vm_address_t address
;
3137 if (!(options
& kIOMapAnywhere
))
3139 address
= trunc_page_64(mapping
->fAddress
);
3140 if( (mapping
->fAddress
- address
) != pageOffset
)
3142 err
= kIOReturnVMError
;
3147 vm_map_t map
= mapping
->fAddressMap
;
3148 err
= IOMemoryDescriptorMapMemEntry(&map
, (ipc_port_t
) _memEntry
,
3149 options
, (kIOMemoryBufferPageable
& _flags
),
3150 offset
, &address
, round_page_64(length
+ pageOffset
));
3151 if( err
!= KERN_SUCCESS
)
3154 if (!_memEntry
|| pager
)
3156 err
= handleFault( pager
, mapping
->fAddressMap
, address
, offset
, length
, options
);
3157 if (err
!= KERN_SUCCESS
)
3158 doUnmap( mapping
->fAddressMap
, (IOVirtualAddress
) mapping
, 0 );
3162 if (kIOLogMapping
& gIOKitDebug
)
3163 IOLog("mapping(%x) desc %p @ %qx, map %p, address %qx, offset %qx, length %qx\n",
3164 err
, this, (uint64_t)sourceAddr
, mapping
, address
, offset
, length
);
3167 if (err
== KERN_SUCCESS
)
3168 mapping
->fAddress
= address
+ pageOffset
;
3170 mapping
->fAddress
= NULL
;
3178 IOReturn
IOMemoryDescriptor::handleFault(
3180 vm_map_t addressMap
,
3181 mach_vm_address_t address
,
3182 mach_vm_size_t sourceOffset
,
3183 mach_vm_size_t length
,
3184 IOOptionBits options
)
3186 IOReturn err
= kIOReturnSuccess
;
3187 memory_object_t pager
= (memory_object_t
) _pager
;
3188 mach_vm_size_t size
;
3189 mach_vm_size_t bytes
;
3190 mach_vm_size_t page
;
3191 mach_vm_size_t pageOffset
;
3192 mach_vm_size_t pagerOffset
;
3193 IOPhysicalLength segLen
;
3198 if( kIOMemoryRedirected
& _flags
)
3201 IOLog("sleep mem redirect %p, %qx\n", this, sourceOffset
);
3205 } while( kIOMemoryRedirected
& _flags
);
3208 return( kIOReturnSuccess
);
3211 physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
);
3213 pageOffset
= physAddr
- trunc_page_64( physAddr
);
3214 pagerOffset
= sourceOffset
;
3216 size
= length
+ pageOffset
;
3217 physAddr
-= pageOffset
;
3219 segLen
+= pageOffset
;
3223 // in the middle of the loop only map whole pages
3224 if( segLen
>= bytes
)
3226 else if( segLen
!= trunc_page( segLen
))
3227 err
= kIOReturnVMError
;
3228 if( physAddr
!= trunc_page_64( physAddr
))
3229 err
= kIOReturnBadArgument
;
3230 if (kIOReturnSuccess
!= err
)
3234 if( kIOLogMapping
& gIOKitDebug
)
3235 IOLog("IOMemoryMap::map(%p) 0x%qx->0x%qx:0x%qx\n",
3236 addressMap
, address
+ pageOffset
, physAddr
+ pageOffset
,
3237 segLen
- pageOffset
);
3242 if( reserved
&& reserved
->dp
.pagerContig
) {
3243 IOPhysicalLength allLen
;
3246 allPhys
= getPhysicalSegment( 0, &allLen
, kIOMemoryMapperNone
);
3248 err
= device_pager_populate_object( pager
, 0, atop_64(allPhys
), round_page(allLen
) );
3254 (page
< segLen
) && (KERN_SUCCESS
== err
);
3257 err
= device_pager_populate_object(pager
, pagerOffset
,
3258 (ppnum_t
)(atop_64(physAddr
+ page
)), page_size
);
3259 pagerOffset
+= page_size
;
3262 assert( KERN_SUCCESS
== err
);
3267 // This call to vm_fault causes an early pmap level resolution
3268 // of the mappings created above for kernel mappings, since
3269 // faulting in later can't take place from interrupt level.
3271 /* *** Temporary Workaround *** */
3273 if ((addressMap
== kernel_map
) && !(kIOMemoryRedirected
& _flags
))
3275 vm_fault(addressMap
,
3276 (vm_map_offset_t
)address
,
3277 VM_PROT_READ
|VM_PROT_WRITE
,
3278 FALSE
, THREAD_UNINT
, NULL
,
3279 (vm_map_offset_t
)0);
3282 /* *** Temporary Workaround *** */
3285 sourceOffset
+= segLen
- pageOffset
;
3291 while (bytes
&& (physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
)));
3294 err
= kIOReturnBadArgument
;
3299 IOReturn
IOMemoryDescriptor::doUnmap(
3300 vm_map_t addressMap
,
3301 IOVirtualAddress __address
,
3302 IOByteCount __length
)
3305 mach_vm_address_t address
;
3306 mach_vm_size_t length
;
3310 address
= __address
;
3315 addressMap
= ((IOMemoryMap
*) __address
)->fAddressMap
;
3316 address
= ((IOMemoryMap
*) __address
)->fAddress
;
3317 length
= ((IOMemoryMap
*) __address
)->fLength
;
3320 if ((addressMap
== kernel_map
)
3321 && ((kIOMemoryBufferPageable
& _flags
) || !_memEntry
))
3322 addressMap
= IOPageableMapForAddress( address
);
3325 if( kIOLogMapping
& gIOKitDebug
)
3326 IOLog("IOMemoryDescriptor::doUnmap map %p, 0x%qx:0x%qx\n",
3327 addressMap
, address
, length
);
3330 err
= mach_vm_deallocate( addressMap
, address
, length
);
3335 IOReturn
IOMemoryDescriptor::redirect( task_t safeTask
, bool doRedirect
)
3337 IOReturn err
= kIOReturnSuccess
;
3338 IOMemoryMap
* mapping
= 0;
3344 _flags
|= kIOMemoryRedirected
;
3346 _flags
&= ~kIOMemoryRedirected
;
3349 if( (iter
= OSCollectionIterator::withCollection( _mappings
))) {
3350 while( (mapping
= (IOMemoryMap
*) iter
->getNextObject()))
3351 mapping
->redirect( safeTask
, doRedirect
);
3365 // temporary binary compatibility
3366 IOSubMemoryDescriptor
* subMem
;
3367 if( (subMem
= OSDynamicCast( IOSubMemoryDescriptor
, this)))
3368 err
= subMem
->redirect( safeTask
, doRedirect
);
3370 err
= kIOReturnSuccess
;
3371 #endif /* !__LP64__ */
3376 IOReturn
IOMemoryMap::redirect( task_t safeTask
, bool doRedirect
)
3378 IOReturn err
= kIOReturnSuccess
;
3381 // err = ((IOMemoryMap *)superMap)->redirect( safeTask, doRedirect );
3393 if ((!safeTask
|| (get_task_map(safeTask
) != fAddressMap
))
3394 && (0 == (fOptions
& kIOMapStatic
)))
3396 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3397 err
= kIOReturnSuccess
;
3399 IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect
, this, fAddress
, fLength
, fAddressMap
);
3402 else if (kIOMapWriteCombineCache
== (fOptions
& kIOMapCacheMask
))
3404 IOOptionBits newMode
;
3405 newMode
= (fOptions
& ~kIOMapCacheMask
) | (doRedirect
? kIOMapInhibitCache
: kIOMapWriteCombineCache
);
3406 IOProtectCacheMode(fAddressMap
, fAddress
, fLength
, newMode
);
3413 if ((((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3414 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3416 && (doRedirect
!= (0 != (fMemory
->_flags
& kIOMemoryRedirected
))))
3417 fMemory
->redirect(safeTask
, doRedirect
);
3422 IOReturn
IOMemoryMap::unmap( void )
3428 if( fAddress
&& fAddressMap
&& (0 == fSuperMap
) && fMemory
3429 && (0 == (fOptions
& kIOMapStatic
))) {
3431 err
= fMemory
->doUnmap(fAddressMap
, (IOVirtualAddress
) this, 0);
3434 err
= kIOReturnSuccess
;
3438 vm_map_deallocate(fAddressMap
);
3449 void IOMemoryMap::taskDied( void )
3452 if (fUserClientUnmap
)
3455 vm_map_deallocate(fAddressMap
);
3463 IOReturn
IOMemoryMap::userClientUnmap( void )
3465 fUserClientUnmap
= true;
3466 return (kIOReturnSuccess
);
3469 // Overload the release mechanism. All mappings must be a member
3470 // of a memory descriptors _mappings set. This means that we
3471 // always have 2 references on a mapping. When either of these mappings
3472 // are released we need to free ourselves.
3473 void IOMemoryMap::taggedRelease(const void *tag
) const
3476 super::taggedRelease(tag
, 2);
3480 void IOMemoryMap::free()
3487 fMemory
->removeMapping(this);
3492 if (fOwner
&& (fOwner
!= fMemory
))
3495 fOwner
->removeMapping(this);
3500 fSuperMap
->release();
3503 upl_commit(fRedirUPL
, NULL
, 0);
3504 upl_deallocate(fRedirUPL
);
3510 IOByteCount
IOMemoryMap::getLength()
3515 IOVirtualAddress
IOMemoryMap::getVirtualAddress()
3519 fSuperMap
->getVirtualAddress();
3520 else if (fAddressMap
3521 && vm_map_is_64bit(fAddressMap
)
3522 && (sizeof(IOVirtualAddress
) < 8))
3524 OSReportWithBacktrace("IOMemoryMap::getVirtualAddress(0x%qx) called on 64b map; use ::getAddress()", fAddress
);
3526 #endif /* !__LP64__ */
3532 mach_vm_address_t
IOMemoryMap::getAddress()
3537 mach_vm_size_t
IOMemoryMap::getSize()
3541 #endif /* !__LP64__ */
3544 task_t
IOMemoryMap::getAddressTask()
3547 return( fSuperMap
->getAddressTask());
3549 return( fAddressTask
);
3552 IOOptionBits
IOMemoryMap::getMapOptions()
3557 IOMemoryDescriptor
* IOMemoryMap::getMemoryDescriptor()
3562 IOMemoryMap
* IOMemoryMap::copyCompatible(
3563 IOMemoryMap
* newMapping
)
3565 task_t task
= newMapping
->getAddressTask();
3566 mach_vm_address_t toAddress
= newMapping
->fAddress
;
3567 IOOptionBits _options
= newMapping
->fOptions
;
3568 mach_vm_size_t _offset
= newMapping
->fOffset
;
3569 mach_vm_size_t _length
= newMapping
->fLength
;
3571 if( (!task
) || (!fAddressMap
) || (fAddressMap
!= get_task_map(task
)))
3573 if( (fOptions
^ _options
) & kIOMapReadOnly
)
3575 if( (kIOMapDefaultCache
!= (_options
& kIOMapCacheMask
))
3576 && ((fOptions
^ _options
) & kIOMapCacheMask
))
3579 if( (0 == (_options
& kIOMapAnywhere
)) && (fAddress
!= toAddress
))
3582 if( _offset
< fOffset
)
3587 if( (_offset
+ _length
) > fLength
)
3591 if( (fLength
== _length
) && (!_offset
))
3597 newMapping
->fSuperMap
= this;
3598 newMapping
->fOffset
= fOffset
+ _offset
;
3599 newMapping
->fAddress
= fAddress
+ _offset
;
3602 return( newMapping
);
3605 IOReturn
IOMemoryMap::wireRange(
3607 mach_vm_size_t offset
,
3608 mach_vm_size_t length
)
3611 mach_vm_address_t start
= trunc_page_64(fAddress
+ offset
);
3612 mach_vm_address_t end
= round_page_64(fAddress
+ offset
+ length
);
3614 if (kIODirectionOutIn
& options
)
3616 kr
= vm_map_wire(fAddressMap
, start
, end
, (kIODirectionOutIn
& options
), FALSE
);
3620 kr
= vm_map_unwire(fAddressMap
, start
, end
, FALSE
);
3629 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
, IOOptionBits _options
)
3630 #else /* !__LP64__ */
3631 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
)
3632 #endif /* !__LP64__ */
3634 IOPhysicalAddress address
;
3638 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
, _options
);
3639 #else /* !__LP64__ */
3640 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
);
3641 #endif /* !__LP64__ */
3647 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3650 #define super OSObject
3652 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3654 void IOMemoryDescriptor::initialize( void )
3656 if( 0 == gIOMemoryLock
)
3657 gIOMemoryLock
= IORecursiveLockAlloc();
3659 IORegistryEntry::getRegistryRoot()->setProperty(kIOMaximumMappedIOByteCountKey
,
3660 ptoa_64(gIOMaximumMappedIOPageCount
), 64);
3661 gIOLastPage
= IOGetLastPageNumber();
3663 gIOPageAllocLock
= IOSimpleLockAlloc();
3664 queue_init(&gIOPageAllocList
);
3667 void IOMemoryDescriptor::free( void )
3670 _mappings
->release();
3675 IOMemoryMap
* IOMemoryDescriptor::setMapping(
3677 IOVirtualAddress mapAddress
,
3678 IOOptionBits options
)
3680 return (createMappingInTask( intoTask
, mapAddress
,
3681 options
| kIOMapStatic
,
3685 IOMemoryMap
* IOMemoryDescriptor::map(
3686 IOOptionBits options
)
3688 return (createMappingInTask( kernel_task
, 0,
3689 options
| kIOMapAnywhere
,
3694 IOMemoryMap
* IOMemoryDescriptor::map(
3696 IOVirtualAddress atAddress
,
3697 IOOptionBits options
,
3699 IOByteCount length
)
3701 if ((!(kIOMapAnywhere
& options
)) && vm_map_is_64bit(get_task_map(intoTask
)))
3703 OSReportWithBacktrace("IOMemoryDescriptor::map() in 64b task, use ::createMappingInTask()");
3707 return (createMappingInTask(intoTask
, atAddress
,
3708 options
, offset
, length
));
3710 #endif /* !__LP64__ */
3712 IOMemoryMap
* IOMemoryDescriptor::createMappingInTask(
3714 mach_vm_address_t atAddress
,
3715 IOOptionBits options
,
3716 mach_vm_size_t offset
,
3717 mach_vm_size_t length
)
3719 IOMemoryMap
* result
;
3720 IOMemoryMap
* mapping
;
3723 length
= getLength();
3725 mapping
= new IOMemoryMap
;
3728 && !mapping
->init( intoTask
, atAddress
,
3729 options
, offset
, length
)) {
3735 result
= makeMapping(this, intoTask
, (IOVirtualAddress
) mapping
, options
| kIOMap64Bit
, 0, 0);
3741 IOLog("createMappingInTask failed desc %p, addr %qx, options %x, offset %qx, length %llx\n",
3742 this, atAddress
, (uint32_t) options
, offset
, length
);
3748 #ifndef __LP64__ // there is only a 64 bit version for LP64
3749 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
3750 IOOptionBits options
,
3753 return (redirect(newBackingMemory
, options
, (mach_vm_size_t
)offset
));
3757 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
3758 IOOptionBits options
,
3759 mach_vm_size_t offset
)
3761 IOReturn err
= kIOReturnSuccess
;
3762 IOMemoryDescriptor
* physMem
= 0;
3766 if (fAddress
&& fAddressMap
) do
3768 if (((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3769 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3777 vm_size_t size
= round_page(fLength
);
3778 int flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3779 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
3780 if (KERN_SUCCESS
!= memory_object_iopl_request((ipc_port_t
) fMemory
->_memEntry
, 0, &size
, &fRedirUPL
,
3787 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
3789 physMem
->redirect(0, true);
3793 if (newBackingMemory
)
3795 if (newBackingMemory
!= fMemory
)
3798 if (this != newBackingMemory
->makeMapping(newBackingMemory
, fAddressTask
, (IOVirtualAddress
) this,
3799 options
| kIOMapUnique
| kIOMapReference
| kIOMap64Bit
,
3801 err
= kIOReturnError
;
3805 upl_commit(fRedirUPL
, NULL
, 0);
3806 upl_deallocate(fRedirUPL
);
3809 if (false && physMem
)
3810 physMem
->redirect(0, false);
3823 IOMemoryMap
* IOMemoryDescriptor::makeMapping(
3824 IOMemoryDescriptor
* owner
,
3826 IOVirtualAddress __address
,
3827 IOOptionBits options
,
3828 IOByteCount __offset
,
3829 IOByteCount __length
)
3832 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::makeMapping !64bit");
3833 #endif /* !__LP64__ */
3835 IOMemoryDescriptor
* mapDesc
= 0;
3836 IOMemoryMap
* result
= 0;
3839 IOMemoryMap
* mapping
= (IOMemoryMap
*) __address
;
3840 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3841 mach_vm_size_t length
= mapping
->fLength
;
3843 mapping
->fOffset
= offset
;
3849 if (kIOMapStatic
& options
)
3852 addMapping(mapping
);
3853 mapping
->setMemoryDescriptor(this, 0);
3857 if (kIOMapUnique
& options
)
3860 IOByteCount physLen
;
3862 // if (owner != this) continue;
3864 if (((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
3865 || ((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
3867 phys
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
3868 if (!phys
|| (physLen
< length
))
3871 mapDesc
= IOMemoryDescriptor::withAddressRange(
3872 phys
, length
, getDirection() | kIOMemoryMapperNone
, NULL
);
3876 mapping
->fOffset
= offset
;
3881 // look for a compatible existing mapping
3882 if( (iter
= OSCollectionIterator::withCollection(_mappings
)))
3884 IOMemoryMap
* lookMapping
;
3885 while ((lookMapping
= (IOMemoryMap
*) iter
->getNextObject()))
3887 if ((result
= lookMapping
->copyCompatible(mapping
)))
3890 result
->setMemoryDescriptor(this, offset
);
3896 if (result
|| (options
& kIOMapReference
))
3898 if (result
!= mapping
)
3913 kr
= mapDesc
->doMap( 0, (IOVirtualAddress
*) &mapping
, options
, 0, 0 );
3914 if (kIOReturnSuccess
== kr
)
3917 mapDesc
->addMapping(result
);
3918 result
->setMemoryDescriptor(mapDesc
, offset
);
3936 void IOMemoryDescriptor::addMapping(
3937 IOMemoryMap
* mapping
)
3942 _mappings
= OSSet::withCapacity(1);
3944 _mappings
->setObject( mapping
);
3948 void IOMemoryDescriptor::removeMapping(
3949 IOMemoryMap
* mapping
)
3952 _mappings
->removeObject( mapping
);
3956 // obsolete initializers
3957 // - initWithOptions is the designated initializer
3959 IOMemoryDescriptor::initWithAddress(void * address
,
3961 IODirection direction
)
3967 IOMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
3969 IODirection direction
,
3976 IOMemoryDescriptor::initWithPhysicalAddress(
3977 IOPhysicalAddress address
,
3979 IODirection direction
)
3985 IOMemoryDescriptor::initWithRanges(
3986 IOVirtualRange
* ranges
,
3988 IODirection direction
,
3996 IOMemoryDescriptor::initWithPhysicalRanges( IOPhysicalRange
* ranges
,
3998 IODirection direction
,
4004 void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
4005 IOByteCount
* lengthOfSegment
)
4009 #endif /* !__LP64__ */
4011 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4013 bool IOGeneralMemoryDescriptor::serialize(OSSerialize
* s
) const
4015 OSSymbol
const *keys
[2];
4016 OSObject
*values
[2];
4018 user_addr_t address
;
4021 unsigned int index
, nRanges
;
4024 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
4026 if (s
== NULL
) return false;
4027 if (s
->previouslySerialized(this)) return true;
4029 // Pretend we are an array.
4030 if (!s
->addXMLStartTag(this, "array")) return false;
4032 nRanges
= _rangesCount
;
4033 vcopy
= (SerData
*) IOMalloc(sizeof(SerData
) * nRanges
);
4034 if (vcopy
== 0) return false;
4036 keys
[0] = OSSymbol::withCString("address");
4037 keys
[1] = OSSymbol::withCString("length");
4040 values
[0] = values
[1] = 0;
4042 // From this point on we can go to bail.
4044 // Copy the volatile data so we don't have to allocate memory
4045 // while the lock is held.
4047 if (nRanges
== _rangesCount
) {
4048 Ranges vec
= _ranges
;
4049 for (index
= 0; index
< nRanges
; index
++) {
4050 user_addr_t addr
; IOByteCount len
;
4051 getAddrLenForInd(addr
, len
, type
, vec
, index
);
4052 vcopy
[index
].address
= addr
;
4053 vcopy
[index
].length
= len
;
4056 // The descriptor changed out from under us. Give up.
4063 for (index
= 0; index
< nRanges
; index
++)
4065 user_addr_t addr
= vcopy
[index
].address
;
4066 IOByteCount len
= (IOByteCount
) vcopy
[index
].length
;
4068 OSNumber::withNumber(addr
, sizeof(addr
) * 8);
4069 if (values
[0] == 0) {
4073 values
[1] = OSNumber::withNumber(len
, sizeof(len
) * 8);
4074 if (values
[1] == 0) {
4078 OSDictionary
*dict
= OSDictionary::withObjects((const OSObject
**)values
, (const OSSymbol
**)keys
, 2);
4083 values
[0]->release();
4084 values
[1]->release();
4085 values
[0] = values
[1] = 0;
4087 result
= dict
->serialize(s
);
4093 result
= s
->addXMLEndTag("array");
4097 values
[0]->release();
4099 values
[1]->release();
4105 IOFree(vcopy
, sizeof(SerData
) * nRanges
);
4109 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4111 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 0);
4113 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 1);
4114 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 2);
4115 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 3);
4116 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 4);
4117 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 5);
4118 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 6);
4119 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 7);
4120 #else /* !__LP64__ */
4121 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 1);
4122 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 2);
4123 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 3);
4124 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 4);
4125 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 5);
4126 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 6);
4127 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 7);
4128 #endif /* !__LP64__ */
4129 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 8);
4130 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 9);
4131 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 10);
4132 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 11);
4133 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 12);
4134 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 13);
4135 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 14);
4136 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 15);
4138 /* ex-inline function implementation */
4140 IOMemoryDescriptor::getPhysicalAddress()
4141 { return( getPhysicalSegment( 0, 0 )); }