2 * Copyright (c) 1998-2016 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@
30 #include <sys/cdefs.h>
32 #include <IOKit/assert.h>
33 #include <IOKit/system.h>
34 #include <IOKit/IOLib.h>
35 #include <IOKit/IOMemoryDescriptor.h>
36 #include <IOKit/IOMapper.h>
37 #include <IOKit/IODMACommand.h>
38 #include <IOKit/IOKitKeysPrivate.h>
40 #include <IOKit/IOSubMemoryDescriptor.h>
41 #include <IOKit/IOMultiMemoryDescriptor.h>
43 #include <IOKit/IOKitDebug.h>
44 #include <libkern/OSDebug.h>
46 #include "IOKitKernelInternal.h"
48 #include <libkern/c++/OSContainers.h>
49 #include <libkern/c++/OSDictionary.h>
50 #include <libkern/c++/OSArray.h>
51 #include <libkern/c++/OSSymbol.h>
52 #include <libkern/c++/OSNumber.h>
53 #include <os/overflow.h>
59 #include <vm/vm_pageout.h>
60 #include <mach/memory_object_types.h>
61 #include <device/device_port.h>
63 #include <mach/vm_prot.h>
64 #include <mach/mach_vm.h>
65 #include <vm/vm_fault.h>
66 #include <vm/vm_protos.h>
68 extern ppnum_t
pmap_find_phys(pmap_t pmap
, addr64_t va
);
69 extern void ipc_port_release_send(ipc_port_t port
);
73 #define kIOMapperWaitSystem ((IOMapper *) 1)
75 static IOMapper
* gIOSystemMapper
= NULL
;
79 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
81 OSDefineMetaClassAndAbstractStructors( IOMemoryDescriptor
, OSObject
)
83 #define super IOMemoryDescriptor
85 OSDefineMetaClassAndStructors(IOGeneralMemoryDescriptor
, IOMemoryDescriptor
)
87 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
89 static IORecursiveLock
* gIOMemoryLock
;
91 #define LOCK IORecursiveLockLock( gIOMemoryLock)
92 #define UNLOCK IORecursiveLockUnlock( gIOMemoryLock)
93 #define SLEEP IORecursiveLockSleep( gIOMemoryLock, (void *)this, THREAD_UNINT)
95 IORecursiveLockWakeup( gIOMemoryLock, (void *)this, /* one-thread */ false)
98 #define DEBG(fmt, args...) { kprintf(fmt, ## args); }
100 #define DEBG(fmt, args...) {}
103 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
105 // Some data structures and accessor macros used by the initWithOptions
108 enum ioPLBlockFlags
{
109 kIOPLOnDevice
= 0x00000001,
110 kIOPLExternUPL
= 0x00000002,
113 struct IOMDPersistentInitData
115 const IOGeneralMemoryDescriptor
* fMD
;
116 IOMemoryReference
* fMemRef
;
121 vm_address_t fPageInfo
; // Pointer to page list or index into it
122 uint32_t fIOMDOffset
; // The offset of this iopl in descriptor
123 ppnum_t fMappedPage
; // Page number of first page in this iopl
124 unsigned int fPageOffset
; // Offset within first page of iopl
125 unsigned int fFlags
; // Flags
128 enum { kMaxWireTags
= 6 };
133 uint64_t fDMAMapAlignment
;
134 uint64_t fMappedBase
;
135 uint64_t fMappedLength
;
136 uint64_t fPreparationID
;
138 IOTracking fWireTracking
;
139 #endif /* IOTRACKING */
140 unsigned int fPageCnt
;
141 uint8_t fDMAMapNumAddressBits
;
142 unsigned char fDiscontig
:1;
143 unsigned char fCompletionError
:1;
144 unsigned char fMappedBaseValid
:1;
145 unsigned char _resv
:3;
146 unsigned char fDMAAccess
:2;
148 /* variable length arrays */
149 upl_page_info_t fPageList
[1]
151 // align fPageList as for ioPLBlock
152 __attribute__((aligned(sizeof(upl_t
))))
155 ioPLBlock fBlocks
[1];
158 #define getDataP(osd) ((ioGMDData *) (osd)->getBytesNoCopy())
159 #define getIOPLList(d) ((ioPLBlock *) (void *)&(d->fPageList[d->fPageCnt]))
160 #define getNumIOPL(osd, d) \
161 (((osd)->getLength() - ((char *) getIOPLList(d) - (char *) d)) / sizeof(ioPLBlock))
162 #define getPageList(d) (&(d->fPageList[0]))
163 #define computeDataSize(p, u) \
164 (offsetof(ioGMDData, fPageList) + p * sizeof(upl_page_info_t) + u * sizeof(ioPLBlock))
166 enum { kIOMemoryHostOrRemote
= kIOMemoryHostOnly
| kIOMemoryRemote
};
168 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
170 #define next_page(a) ( trunc_page(a) + PAGE_SIZE )
174 kern_return_t
device_data_action(
175 uintptr_t device_handle
,
176 ipc_port_t device_pager
,
177 vm_prot_t protection
,
178 vm_object_offset_t offset
,
182 IOMemoryDescriptorReserved
* ref
= (IOMemoryDescriptorReserved
*) device_handle
;
183 IOMemoryDescriptor
* memDesc
;
186 memDesc
= ref
->dp
.memory
;
190 kr
= memDesc
->handleFault(device_pager
, offset
, size
);
200 kern_return_t
device_close(
201 uintptr_t device_handle
)
203 IOMemoryDescriptorReserved
* ref
= (IOMemoryDescriptorReserved
*) device_handle
;
205 IODelete( ref
, IOMemoryDescriptorReserved
, 1 );
207 return( kIOReturnSuccess
);
211 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
213 // Note this inline function uses C++ reference arguments to return values
214 // This means that pointers are not passed and NULLs don't have to be
215 // checked for as a NULL reference is illegal.
217 getAddrLenForInd(mach_vm_address_t
&addr
, mach_vm_size_t
&len
, // Output variables
218 UInt32 type
, IOGeneralMemoryDescriptor::Ranges r
, UInt32 ind
)
220 assert(kIOMemoryTypeUIO
== type
221 || kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
222 || kIOMemoryTypePhysical
== type
|| kIOMemoryTypePhysical64
== type
);
223 if (kIOMemoryTypeUIO
== type
) {
226 uio_getiov((uio_t
) r
.uio
, ind
, &ad
, &us
); addr
= ad
; len
= us
;
229 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
)) {
230 IOAddressRange cur
= r
.v64
[ind
];
234 #endif /* !__LP64__ */
236 IOVirtualRange cur
= r
.v
[ind
];
242 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
245 purgeableControlBits(IOOptionBits newState
, vm_purgable_t
* control
, int * state
)
247 IOReturn err
= kIOReturnSuccess
;
249 *control
= VM_PURGABLE_SET_STATE
;
251 enum { kIOMemoryPurgeableControlMask
= 15 };
253 switch (kIOMemoryPurgeableControlMask
& newState
)
255 case kIOMemoryPurgeableKeepCurrent
:
256 *control
= VM_PURGABLE_GET_STATE
;
259 case kIOMemoryPurgeableNonVolatile
:
260 *state
= VM_PURGABLE_NONVOLATILE
;
262 case kIOMemoryPurgeableVolatile
:
263 *state
= VM_PURGABLE_VOLATILE
| (newState
& ~kIOMemoryPurgeableControlMask
);
265 case kIOMemoryPurgeableEmpty
:
266 *state
= VM_PURGABLE_EMPTY
| (newState
& ~kIOMemoryPurgeableControlMask
);
269 err
= kIOReturnBadArgument
;
273 if (*control
== VM_PURGABLE_SET_STATE
) {
274 // let VM know this call is from the kernel and is allowed to alter
275 // the volatility of the memory entry even if it was created with
276 // MAP_MEM_PURGABLE_KERNEL_ONLY
277 *control
= VM_PURGABLE_SET_STATE_FROM_KERNEL
;
284 purgeableStateBits(int * state
)
286 IOReturn err
= kIOReturnSuccess
;
288 switch (VM_PURGABLE_STATE_MASK
& *state
)
290 case VM_PURGABLE_NONVOLATILE
:
291 *state
= kIOMemoryPurgeableNonVolatile
;
293 case VM_PURGABLE_VOLATILE
:
294 *state
= kIOMemoryPurgeableVolatile
;
296 case VM_PURGABLE_EMPTY
:
297 *state
= kIOMemoryPurgeableEmpty
;
300 *state
= kIOMemoryPurgeableNonVolatile
;
301 err
= kIOReturnNotReady
;
309 vmProtForCacheMode(IOOptionBits cacheMode
)
314 case kIOInhibitCache
:
315 SET_MAP_MEM(MAP_MEM_IO
, prot
);
318 case kIOWriteThruCache
:
319 SET_MAP_MEM(MAP_MEM_WTHRU
, prot
);
322 case kIOWriteCombineCache
:
323 SET_MAP_MEM(MAP_MEM_WCOMB
, prot
);
326 case kIOCopybackCache
:
327 SET_MAP_MEM(MAP_MEM_COPYBACK
, prot
);
330 case kIOCopybackInnerCache
:
331 SET_MAP_MEM(MAP_MEM_INNERWBACK
, prot
);
335 SET_MAP_MEM(MAP_MEM_POSTED
, prot
);
338 case kIODefaultCache
:
340 SET_MAP_MEM(MAP_MEM_NOOP
, prot
);
348 pagerFlagsForCacheMode(IOOptionBits cacheMode
)
350 unsigned int pagerFlags
= 0;
353 case kIOInhibitCache
:
354 pagerFlags
= DEVICE_PAGER_CACHE_INHIB
| DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
357 case kIOWriteThruCache
:
358 pagerFlags
= DEVICE_PAGER_WRITE_THROUGH
| DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
;
361 case kIOWriteCombineCache
:
362 pagerFlags
= DEVICE_PAGER_CACHE_INHIB
| DEVICE_PAGER_COHERENT
;
365 case kIOCopybackCache
:
366 pagerFlags
= DEVICE_PAGER_COHERENT
;
369 case kIOCopybackInnerCache
:
370 pagerFlags
= DEVICE_PAGER_COHERENT
;
374 pagerFlags
= DEVICE_PAGER_CACHE_INHIB
| DEVICE_PAGER_COHERENT
| DEVICE_PAGER_GUARDED
| DEVICE_PAGER_EARLY_ACK
;
377 case kIODefaultCache
:
385 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
386 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
395 struct IOMemoryReference
397 volatile SInt32 refCount
;
401 struct IOMemoryReference
* mapRef
;
402 IOMemoryEntry entries
[0];
407 kIOMemoryReferenceReuse
= 0x00000001,
408 kIOMemoryReferenceWrite
= 0x00000002,
409 kIOMemoryReferenceCOW
= 0x00000004,
412 SInt32 gIOMemoryReferenceCount
;
415 IOGeneralMemoryDescriptor::memoryReferenceAlloc(uint32_t capacity
, IOMemoryReference
* realloc
)
417 IOMemoryReference
* ref
;
418 size_t newSize
, oldSize
, copySize
;
420 newSize
= (sizeof(IOMemoryReference
)
421 - sizeof(ref
->entries
)
422 + capacity
* sizeof(ref
->entries
[0]));
423 ref
= (typeof(ref
)) IOMalloc(newSize
);
426 oldSize
= (sizeof(IOMemoryReference
)
427 - sizeof(realloc
->entries
)
428 + realloc
->capacity
* sizeof(realloc
->entries
[0]));
430 if (copySize
> newSize
) copySize
= newSize
;
431 if (ref
) bcopy(realloc
, ref
, copySize
);
432 IOFree(realloc
, oldSize
);
436 bzero(ref
, sizeof(*ref
));
438 OSIncrementAtomic(&gIOMemoryReferenceCount
);
440 if (!ref
) return (0);
441 ref
->capacity
= capacity
;
446 IOGeneralMemoryDescriptor::memoryReferenceFree(IOMemoryReference
* ref
)
448 IOMemoryEntry
* entries
;
453 memoryReferenceFree(ref
->mapRef
);
457 entries
= ref
->entries
+ ref
->count
;
458 while (entries
> &ref
->entries
[0])
461 ipc_port_release_send(entries
->entry
);
463 size
= (sizeof(IOMemoryReference
)
464 - sizeof(ref
->entries
)
465 + ref
->capacity
* sizeof(ref
->entries
[0]));
468 OSDecrementAtomic(&gIOMemoryReferenceCount
);
472 IOGeneralMemoryDescriptor::memoryReferenceRelease(IOMemoryReference
* ref
)
474 if (1 == OSDecrementAtomic(&ref
->refCount
)) memoryReferenceFree(ref
);
479 IOGeneralMemoryDescriptor::memoryReferenceCreate(
480 IOOptionBits options
,
481 IOMemoryReference
** reference
)
483 enum { kCapacity
= 4, kCapacityInc
= 4 };
486 IOMemoryReference
* ref
;
487 IOMemoryEntry
* entries
;
488 IOMemoryEntry
* cloneEntries
;
490 ipc_port_t entry
, cloneEntry
;
492 memory_object_size_t actualSize
;
495 mach_vm_address_t entryAddr
, endAddr
, entrySize
;
496 mach_vm_size_t srcAddr
, srcLen
;
497 mach_vm_size_t nextAddr
, nextLen
;
498 mach_vm_size_t offset
, remain
;
500 IOOptionBits type
= (_flags
& kIOMemoryTypeMask
);
501 IOOptionBits cacheMode
;
502 unsigned int pagerFlags
;
505 ref
= memoryReferenceAlloc(kCapacity
, NULL
);
506 if (!ref
) return (kIOReturnNoMemory
);
508 tag
= getVMTag(kernel_map
);
509 entries
= &ref
->entries
[0];
517 getAddrLenForInd(nextAddr
, nextLen
, type
, _ranges
, rangeIdx
);
521 nextAddr
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
524 // default cache mode for physical
525 if (kIODefaultCache
== ((_flags
& kIOMemoryBufferCacheMask
) >> kIOMemoryBufferCacheShift
))
528 pagerFlags
= IODefaultCacheBits(nextAddr
);
529 if (DEVICE_PAGER_CACHE_INHIB
& pagerFlags
)
531 if (DEVICE_PAGER_EARLY_ACK
& pagerFlags
)
532 mode
= kIOPostedWrite
;
533 else if (DEVICE_PAGER_GUARDED
& pagerFlags
)
534 mode
= kIOInhibitCache
;
536 mode
= kIOWriteCombineCache
;
538 else if (DEVICE_PAGER_WRITE_THROUGH
& pagerFlags
)
539 mode
= kIOWriteThruCache
;
541 mode
= kIOCopybackCache
;
542 _flags
|= (mode
<< kIOMemoryBufferCacheShift
);
546 // cache mode & vm_prot
548 cacheMode
= ((_flags
& kIOMemoryBufferCacheMask
) >> kIOMemoryBufferCacheShift
);
549 prot
|= vmProtForCacheMode(cacheMode
);
550 // VM system requires write access to change cache mode
551 if (kIODefaultCache
!= cacheMode
) prot
|= VM_PROT_WRITE
;
552 if (kIODirectionOut
!= (kIODirectionOutIn
& _flags
)) prot
|= VM_PROT_WRITE
;
553 if (kIOMemoryReferenceWrite
& options
) prot
|= VM_PROT_WRITE
;
554 if (kIOMemoryReferenceCOW
& options
) prot
|= MAP_MEM_VM_COPY
;
556 if ((kIOMemoryReferenceReuse
& options
) && _memRef
)
558 cloneEntries
= &_memRef
->entries
[0];
559 prot
|= MAP_MEM_NAMED_REUSE
;
566 if (kIOMemoryBufferPageable
& _flags
)
568 // IOBufferMemoryDescriptor alloc - set flags for entry + object create
569 prot
|= MAP_MEM_NAMED_CREATE
;
570 if (kIOMemoryBufferPurgeable
& _flags
) prot
|= (MAP_MEM_PURGABLE
| MAP_MEM_PURGABLE_KERNEL_ONLY
);
571 if (kIOMemoryUseReserve
& _flags
) prot
|= MAP_MEM_GRAB_SECLUDED
;
573 prot
|= VM_PROT_WRITE
;
576 else map
= get_task_map(_task
);
585 // coalesce addr range
586 for (++rangeIdx
; rangeIdx
< _rangesCount
; rangeIdx
++)
588 getAddrLenForInd(nextAddr
, nextLen
, type
, _ranges
, rangeIdx
);
589 if ((srcAddr
+ srcLen
) != nextAddr
) break;
592 entryAddr
= trunc_page_64(srcAddr
);
593 endAddr
= round_page_64(srcAddr
+ srcLen
);
596 entrySize
= (endAddr
- entryAddr
);
597 if (!entrySize
) break;
598 actualSize
= entrySize
;
600 cloneEntry
= MACH_PORT_NULL
;
601 if (MAP_MEM_NAMED_REUSE
& prot
)
603 if (cloneEntries
< &_memRef
->entries
[_memRef
->count
]) cloneEntry
= cloneEntries
->entry
;
604 else prot
&= ~MAP_MEM_NAMED_REUSE
;
607 err
= mach_make_memory_entry_64(map
,
608 &actualSize
, entryAddr
, prot
, &entry
, cloneEntry
);
610 if (KERN_SUCCESS
!= err
) break;
611 if (actualSize
> entrySize
) panic("mach_make_memory_entry_64 actualSize");
613 if (count
>= ref
->capacity
)
615 ref
= memoryReferenceAlloc(ref
->capacity
+ kCapacityInc
, ref
);
616 entries
= &ref
->entries
[count
];
618 entries
->entry
= entry
;
619 entries
->size
= actualSize
;
620 entries
->offset
= offset
+ (entryAddr
- srcAddr
);
621 entryAddr
+= actualSize
;
622 if (MAP_MEM_NAMED_REUSE
& prot
)
624 if ((cloneEntries
->entry
== entries
->entry
)
625 && (cloneEntries
->size
== entries
->size
)
626 && (cloneEntries
->offset
== entries
->offset
)) cloneEntries
++;
627 else prot
&= ~MAP_MEM_NAMED_REUSE
;
639 // _task == 0, physical or kIOMemoryTypeUPL
640 memory_object_t pager
;
641 vm_size_t size
= ptoa_32(_pages
);
643 if (!getKernelReserved()) panic("getKernelReserved");
645 reserved
->dp
.pagerContig
= (1 == _rangesCount
);
646 reserved
->dp
.memory
= this;
648 pagerFlags
= pagerFlagsForCacheMode(cacheMode
);
649 if (-1U == pagerFlags
) panic("phys is kIODefaultCache");
650 if (reserved
->dp
.pagerContig
) pagerFlags
|= DEVICE_PAGER_CONTIGUOUS
;
652 pager
= device_pager_setup((memory_object_t
) 0, (uintptr_t) reserved
,
655 if (!pager
) err
= kIOReturnVMError
;
659 entryAddr
= trunc_page_64(srcAddr
);
660 err
= mach_memory_object_memory_entry_64((host_t
) 1, false /*internal*/,
661 size
, VM_PROT_READ
| VM_PROT_WRITE
, pager
, &entry
);
662 assert (KERN_SUCCESS
== err
);
663 if (KERN_SUCCESS
!= err
) device_pager_deallocate(pager
);
666 reserved
->dp
.devicePager
= pager
;
667 entries
->entry
= entry
;
668 entries
->size
= size
;
669 entries
->offset
= offset
+ (entryAddr
- srcAddr
);
679 if (_task
&& (KERN_SUCCESS
== err
)
680 && (kIOMemoryMapCopyOnWrite
& _flags
)
681 && !(kIOMemoryReferenceCOW
& options
))
683 err
= memoryReferenceCreate(options
| kIOMemoryReferenceCOW
, &ref
->mapRef
);
686 if (KERN_SUCCESS
== err
)
688 if (MAP_MEM_NAMED_REUSE
& prot
)
690 memoryReferenceFree(ref
);
691 OSIncrementAtomic(&_memRef
->refCount
);
697 memoryReferenceFree(ref
);
707 IOMemoryDescriptorMapAlloc(vm_map_t map
, void * _ref
)
709 IOMemoryDescriptorMapAllocRef
* ref
= (typeof(ref
))_ref
;
711 vm_map_offset_t addr
;
715 err
= vm_map_enter_mem_object(map
, &addr
, ref
->size
,
717 (((ref
->options
& kIOMapAnywhere
)
720 VM_MAP_KERNEL_FLAGS_NONE
,
723 (memory_object_offset_t
) 0,
728 if (KERN_SUCCESS
== err
)
730 ref
->mapped
= (mach_vm_address_t
) addr
;
738 IOGeneralMemoryDescriptor::memoryReferenceMap(
739 IOMemoryReference
* ref
,
741 mach_vm_size_t inoffset
,
743 IOOptionBits options
,
744 mach_vm_address_t
* inaddr
)
747 int64_t offset
= inoffset
;
748 uint32_t rangeIdx
, entryIdx
;
749 vm_map_offset_t addr
, mapAddr
;
750 vm_map_offset_t pageOffset
, entryOffset
, remain
, chunk
;
752 mach_vm_address_t nextAddr
;
753 mach_vm_size_t nextLen
;
755 IOMemoryEntry
* entry
;
756 vm_prot_t prot
, memEntryCacheMode
;
758 IOOptionBits cacheMode
;
760 // for the kIOMapPrefault option.
761 upl_page_info_t
* pageList
= NULL
;
762 UInt currentPageIndex
= 0;
767 err
= memoryReferenceMap(ref
->mapRef
, map
, inoffset
, size
, options
, inaddr
);
771 type
= _flags
& kIOMemoryTypeMask
;
774 if (!(kIOMapReadOnly
& options
)) prot
|= VM_PROT_WRITE
;
777 cacheMode
= ((options
& kIOMapCacheMask
) >> kIOMapCacheShift
);
778 if (kIODefaultCache
!= cacheMode
)
780 // VM system requires write access to update named entry cache mode
781 memEntryCacheMode
= (MAP_MEM_ONLY
| VM_PROT_WRITE
| prot
| vmProtForCacheMode(cacheMode
));
788 // Find first range for offset
789 if (!_rangesCount
) return (kIOReturnBadArgument
);
790 for (remain
= offset
, rangeIdx
= 0; rangeIdx
< _rangesCount
; rangeIdx
++)
792 getAddrLenForInd(nextAddr
, nextLen
, type
, _ranges
, rangeIdx
);
793 if (remain
< nextLen
) break;
801 nextAddr
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
805 assert(remain
< nextLen
);
806 if (remain
>= nextLen
) return (kIOReturnBadArgument
);
810 pageOffset
= (page_mask
& nextAddr
);
814 if (!(options
& kIOMapAnywhere
))
817 if (pageOffset
!= (page_mask
& addr
)) return (kIOReturnNotAligned
);
821 // find first entry for offset
823 (entryIdx
< ref
->count
) && (offset
>= ref
->entries
[entryIdx
].offset
);
826 entry
= &ref
->entries
[entryIdx
];
829 size
= round_page_64(size
+ pageOffset
);
830 if (kIOMapOverwrite
& options
)
832 if ((map
== kernel_map
) && (kIOMemoryBufferPageable
& _flags
))
834 map
= IOPageableMapForAddress(addr
);
840 IOMemoryDescriptorMapAllocRef ref
;
843 ref
.options
= options
;
846 if (options
& kIOMapAnywhere
)
847 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
851 if ((ref
.map
== kernel_map
) && (kIOMemoryBufferPageable
& _flags
))
852 err
= IOIteratePageableMaps( ref
.size
, &IOMemoryDescriptorMapAlloc
, &ref
);
854 err
= IOMemoryDescriptorMapAlloc(ref
.map
, &ref
);
855 if (KERN_SUCCESS
== err
)
864 * If the memory is associated with a device pager but doesn't have a UPL,
865 * it will be immediately faulted in through the pager via populateDevicePager().
866 * kIOMapPrefault is redundant in that case, so don't try to use it for UPL
869 if ((reserved
!= NULL
) && (reserved
->dp
.devicePager
) && (_memoryEntries
== NULL
) && (_wireCount
!= 0))
870 options
&= ~kIOMapPrefault
;
873 * Prefaulting is only possible if we wired the memory earlier. Check the
874 * memory type, and the underlying data.
876 if (options
& kIOMapPrefault
)
879 * The memory must have been wired by calling ::prepare(), otherwise
880 * we don't have the UPL. Without UPLs, pages cannot be pre-faulted
882 assert(_wireCount
!= 0);
883 assert(_memoryEntries
!= NULL
);
884 if ((_wireCount
== 0) ||
885 (_memoryEntries
== NULL
))
887 return kIOReturnBadArgument
;
890 // Get the page list.
891 ioGMDData
* dataP
= getDataP(_memoryEntries
);
892 ioPLBlock
const* ioplList
= getIOPLList(dataP
);
893 pageList
= getPageList(dataP
);
895 // Get the number of IOPLs.
896 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
899 * Scan through the IOPL Info Blocks, looking for the first block containing
900 * the offset. The research will go past it, so we'll need to go back to the
901 * right range at the end.
904 while (ioplIndex
< numIOPLs
&& offset
>= ioplList
[ioplIndex
].fIOMDOffset
)
908 // Retrieve the IOPL info block.
909 ioPLBlock ioplInfo
= ioplList
[ioplIndex
];
912 * For external UPLs, the fPageInfo points directly to the UPL's page_info_t
915 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
916 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
918 pageList
= &pageList
[ioplInfo
.fPageInfo
];
920 // Rebase [offset] into the IOPL in order to looks for the first page index.
921 mach_vm_size_t offsetInIOPL
= offset
- ioplInfo
.fIOMDOffset
+ ioplInfo
.fPageOffset
;
923 // Retrieve the index of the first page corresponding to the offset.
924 currentPageIndex
= atop_32(offsetInIOPL
);
932 while (remain
&& (KERN_SUCCESS
== err
))
934 entryOffset
= offset
- entry
->offset
;
935 if ((page_mask
& entryOffset
) != pageOffset
)
937 err
= kIOReturnNotAligned
;
941 if (kIODefaultCache
!= cacheMode
)
943 vm_size_t unused
= 0;
944 err
= mach_make_memory_entry(NULL
/*unused*/, &unused
, 0 /*unused*/,
945 memEntryCacheMode
, NULL
, entry
->entry
);
946 assert (KERN_SUCCESS
== err
);
949 entryOffset
-= pageOffset
;
950 if (entryOffset
>= entry
->size
) panic("entryOffset");
951 chunk
= entry
->size
- entryOffset
;
954 vm_map_kernel_flags_t vmk_flags
;
956 vmk_flags
= VM_MAP_KERNEL_FLAGS_NONE
;
957 vmk_flags
.vmkf_iokit_acct
= TRUE
; /* iokit accounting */
959 if (chunk
> remain
) chunk
= remain
;
960 if (options
& kIOMapPrefault
)
962 UInt nb_pages
= round_page(chunk
) / PAGE_SIZE
;
964 err
= vm_map_enter_mem_object_prefault(map
,
968 | VM_FLAGS_OVERWRITE
),
975 &pageList
[currentPageIndex
],
978 // Compute the next index in the page list.
979 currentPageIndex
+= nb_pages
;
980 assert(currentPageIndex
<= _pages
);
984 err
= vm_map_enter_mem_object(map
,
988 | VM_FLAGS_OVERWRITE
),
998 if (KERN_SUCCESS
!= err
) break;
1002 offset
+= chunk
- pageOffset
;
1007 if (entryIdx
>= ref
->count
)
1009 err
= kIOReturnOverrun
;
1014 if ((KERN_SUCCESS
!= err
) && didAlloc
)
1016 (void) mach_vm_deallocate(map
, trunc_page_64(addr
), size
);
1025 IOGeneralMemoryDescriptor::memoryReferenceGetPageCounts(
1026 IOMemoryReference
* ref
,
1027 IOByteCount
* residentPageCount
,
1028 IOByteCount
* dirtyPageCount
)
1031 IOMemoryEntry
* entries
;
1032 unsigned int resident
, dirty
;
1033 unsigned int totalResident
, totalDirty
;
1035 totalResident
= totalDirty
= 0;
1036 err
= kIOReturnSuccess
;
1037 entries
= ref
->entries
+ ref
->count
;
1038 while (entries
> &ref
->entries
[0])
1041 err
= mach_memory_entry_get_page_counts(entries
->entry
, &resident
, &dirty
);
1042 if (KERN_SUCCESS
!= err
) break;
1043 totalResident
+= resident
;
1044 totalDirty
+= dirty
;
1047 if (residentPageCount
) *residentPageCount
= totalResident
;
1048 if (dirtyPageCount
) *dirtyPageCount
= totalDirty
;
1053 IOGeneralMemoryDescriptor::memoryReferenceSetPurgeable(
1054 IOMemoryReference
* ref
,
1055 IOOptionBits newState
,
1056 IOOptionBits
* oldState
)
1059 IOMemoryEntry
* entries
;
1060 vm_purgable_t control
;
1061 int totalState
, state
;
1063 totalState
= kIOMemoryPurgeableNonVolatile
;
1064 err
= kIOReturnSuccess
;
1065 entries
= ref
->entries
+ ref
->count
;
1066 while (entries
> &ref
->entries
[0])
1070 err
= purgeableControlBits(newState
, &control
, &state
);
1071 if (KERN_SUCCESS
!= err
) break;
1072 err
= memory_entry_purgeable_control_internal(entries
->entry
, control
, &state
);
1073 if (KERN_SUCCESS
!= err
) break;
1074 err
= purgeableStateBits(&state
);
1075 if (KERN_SUCCESS
!= err
) break;
1077 if (kIOMemoryPurgeableEmpty
== state
) totalState
= kIOMemoryPurgeableEmpty
;
1078 else if (kIOMemoryPurgeableEmpty
== totalState
) continue;
1079 else if (kIOMemoryPurgeableVolatile
== totalState
) continue;
1080 else if (kIOMemoryPurgeableVolatile
== state
) totalState
= kIOMemoryPurgeableVolatile
;
1081 else totalState
= kIOMemoryPurgeableNonVolatile
;
1084 if (oldState
) *oldState
= totalState
;
1088 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1090 IOMemoryDescriptor
*
1091 IOMemoryDescriptor::withAddress(void * address
,
1093 IODirection direction
)
1095 return IOMemoryDescriptor::
1096 withAddressRange((IOVirtualAddress
) address
, length
, direction
| kIOMemoryAutoPrepare
, kernel_task
);
1100 IOMemoryDescriptor
*
1101 IOMemoryDescriptor::withAddress(IOVirtualAddress address
,
1103 IODirection direction
,
1106 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1109 if (that
->initWithAddress(address
, length
, direction
, task
))
1116 #endif /* !__LP64__ */
1118 IOMemoryDescriptor
*
1119 IOMemoryDescriptor::withPhysicalAddress(
1120 IOPhysicalAddress address
,
1122 IODirection direction
)
1124 return (IOMemoryDescriptor::withAddressRange(address
, length
, direction
, TASK_NULL
));
1128 IOMemoryDescriptor
*
1129 IOMemoryDescriptor::withRanges( IOVirtualRange
* ranges
,
1131 IODirection direction
,
1135 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1138 if (that
->initWithRanges(ranges
, withCount
, direction
, task
, asReference
))
1145 #endif /* !__LP64__ */
1147 IOMemoryDescriptor
*
1148 IOMemoryDescriptor::withAddressRange(mach_vm_address_t address
,
1149 mach_vm_size_t length
,
1150 IOOptionBits options
,
1153 IOAddressRange range
= { address
, length
};
1154 return (IOMemoryDescriptor::withAddressRanges(&range
, 1, options
, task
));
1157 IOMemoryDescriptor
*
1158 IOMemoryDescriptor::withAddressRanges(IOAddressRange
* ranges
,
1160 IOOptionBits options
,
1163 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1167 options
|= kIOMemoryTypeVirtual64
;
1169 options
|= kIOMemoryTypePhysical64
;
1171 if (that
->initWithOptions(ranges
, rangeCount
, 0, task
, options
, /* mapper */ 0))
1184 * Create a new IOMemoryDescriptor. The buffer is made up of several
1185 * virtual address ranges, from a given task.
1187 * Passing the ranges as a reference will avoid an extra allocation.
1189 IOMemoryDescriptor
*
1190 IOMemoryDescriptor::withOptions(void * buffers
,
1197 IOGeneralMemoryDescriptor
*self
= new IOGeneralMemoryDescriptor
;
1200 && !self
->initWithOptions(buffers
, count
, offset
, task
, opts
, mapper
))
1209 bool IOMemoryDescriptor::initWithOptions(void * buffers
,
1213 IOOptionBits options
,
1220 IOMemoryDescriptor
*
1221 IOMemoryDescriptor::withPhysicalRanges( IOPhysicalRange
* ranges
,
1223 IODirection direction
,
1226 IOGeneralMemoryDescriptor
* that
= new IOGeneralMemoryDescriptor
;
1229 if (that
->initWithPhysicalRanges(ranges
, withCount
, direction
, asReference
))
1237 IOMemoryDescriptor
*
1238 IOMemoryDescriptor::withSubRange(IOMemoryDescriptor
* of
,
1241 IODirection direction
)
1243 return (IOSubMemoryDescriptor::withSubRange(of
, offset
, length
, direction
));
1245 #endif /* !__LP64__ */
1247 IOMemoryDescriptor
*
1248 IOMemoryDescriptor::withPersistentMemoryDescriptor(IOMemoryDescriptor
*originalMD
)
1250 IOGeneralMemoryDescriptor
*origGenMD
=
1251 OSDynamicCast(IOGeneralMemoryDescriptor
, originalMD
);
1254 return IOGeneralMemoryDescriptor::
1255 withPersistentMemoryDescriptor(origGenMD
);
1260 IOMemoryDescriptor
*
1261 IOGeneralMemoryDescriptor::withPersistentMemoryDescriptor(IOGeneralMemoryDescriptor
*originalMD
)
1263 IOMemoryReference
* memRef
;
1265 if (kIOReturnSuccess
!= originalMD
->memoryReferenceCreate(kIOMemoryReferenceReuse
, &memRef
)) return (0);
1267 if (memRef
== originalMD
->_memRef
)
1269 originalMD
->retain(); // Add a new reference to ourselves
1270 originalMD
->memoryReferenceRelease(memRef
);
1274 IOGeneralMemoryDescriptor
* self
= new IOGeneralMemoryDescriptor
;
1275 IOMDPersistentInitData initData
= { originalMD
, memRef
};
1278 && !self
->initWithOptions(&initData
, 1, 0, 0, kIOMemoryTypePersistentMD
, 0)) {
1287 IOGeneralMemoryDescriptor::initWithAddress(void * address
,
1288 IOByteCount withLength
,
1289 IODirection withDirection
)
1291 _singleRange
.v
.address
= (vm_offset_t
) address
;
1292 _singleRange
.v
.length
= withLength
;
1294 return initWithRanges(&_singleRange
.v
, 1, withDirection
, kernel_task
, true);
1298 IOGeneralMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
1299 IOByteCount withLength
,
1300 IODirection withDirection
,
1303 _singleRange
.v
.address
= address
;
1304 _singleRange
.v
.length
= withLength
;
1306 return initWithRanges(&_singleRange
.v
, 1, withDirection
, withTask
, true);
1310 IOGeneralMemoryDescriptor::initWithPhysicalAddress(
1311 IOPhysicalAddress address
,
1312 IOByteCount withLength
,
1313 IODirection withDirection
)
1315 _singleRange
.p
.address
= address
;
1316 _singleRange
.p
.length
= withLength
;
1318 return initWithPhysicalRanges( &_singleRange
.p
, 1, withDirection
, true);
1322 IOGeneralMemoryDescriptor::initWithPhysicalRanges(
1323 IOPhysicalRange
* ranges
,
1325 IODirection direction
,
1328 IOOptionBits mdOpts
= direction
| kIOMemoryTypePhysical
;
1331 mdOpts
|= kIOMemoryAsReference
;
1333 return initWithOptions(ranges
, count
, 0, 0, mdOpts
, /* mapper */ 0);
1337 IOGeneralMemoryDescriptor::initWithRanges(
1338 IOVirtualRange
* ranges
,
1340 IODirection direction
,
1344 IOOptionBits mdOpts
= direction
;
1347 mdOpts
|= kIOMemoryAsReference
;
1350 mdOpts
|= kIOMemoryTypeVirtual
;
1352 // Auto-prepare if this is a kernel memory descriptor as very few
1353 // clients bother to prepare() kernel memory.
1354 // But it was not enforced so what are you going to do?
1355 if (task
== kernel_task
)
1356 mdOpts
|= kIOMemoryAutoPrepare
;
1359 mdOpts
|= kIOMemoryTypePhysical
;
1361 return initWithOptions(ranges
, count
, 0, task
, mdOpts
, /* mapper */ 0);
1363 #endif /* !__LP64__ */
1368 * IOMemoryDescriptor. The buffer is made up of several virtual address ranges,
1369 * from a given task, several physical ranges, an UPL from the ubc
1370 * system or a uio (may be 64bit) from the BSD subsystem.
1372 * Passing the ranges as a reference will avoid an extra allocation.
1374 * An IOMemoryDescriptor can be re-used by calling initWithOptions again on an
1375 * existing instance -- note this behavior is not commonly supported in other
1376 * I/O Kit classes, although it is supported here.
1380 IOGeneralMemoryDescriptor::initWithOptions(void * buffers
,
1384 IOOptionBits options
,
1387 IOOptionBits type
= options
& kIOMemoryTypeMask
;
1391 && (kIOMemoryTypeVirtual
== type
)
1392 && vm_map_is_64bit(get_task_map(task
))
1393 && ((IOVirtualRange
*) buffers
)->address
)
1395 OSReportWithBacktrace("IOMemoryDescriptor: attempt to create 32b virtual in 64b task, use ::withAddressRange()");
1398 #endif /* !__LP64__ */
1400 // Grab the original MD's configuation data to initialse the
1401 // arguments to this function.
1402 if (kIOMemoryTypePersistentMD
== type
) {
1404 IOMDPersistentInitData
*initData
= (typeof(initData
)) buffers
;
1405 const IOGeneralMemoryDescriptor
*orig
= initData
->fMD
;
1406 ioGMDData
*dataP
= getDataP(orig
->_memoryEntries
);
1408 // Only accept persistent memory descriptors with valid dataP data.
1409 assert(orig
->_rangesCount
== 1);
1410 if ( !(orig
->_flags
& kIOMemoryPersistent
) || !dataP
)
1413 _memRef
= initData
->fMemRef
; // Grab the new named entry
1414 options
= orig
->_flags
& ~kIOMemoryAsReference
;
1415 type
= options
& kIOMemoryTypeMask
;
1416 buffers
= orig
->_ranges
.v
;
1417 count
= orig
->_rangesCount
;
1419 // Now grab the original task and whatever mapper was previously used
1421 mapper
= dataP
->fMapper
;
1423 // We are ready to go through the original initialisation now
1427 case kIOMemoryTypeUIO
:
1428 case kIOMemoryTypeVirtual
:
1430 case kIOMemoryTypeVirtual64
:
1431 #endif /* !__LP64__ */
1437 case kIOMemoryTypePhysical
: // Neither Physical nor UPL should have a task
1439 case kIOMemoryTypePhysical64
:
1440 #endif /* !__LP64__ */
1441 case kIOMemoryTypeUPL
:
1445 return false; /* bad argument */
1452 * We can check the _initialized instance variable before having ever set
1453 * it to an initial value because I/O Kit guarantees that all our instance
1454 * variables are zeroed on an object's allocation.
1459 * An existing memory descriptor is being retargeted to point to
1460 * somewhere else. Clean up our present state.
1462 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1463 if ((kIOMemoryTypePhysical
!= type
) && (kIOMemoryTypePhysical64
!= type
))
1468 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
1470 if (kIOMemoryTypeUIO
== type
)
1471 uio_free((uio_t
) _ranges
.v
);
1473 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
1474 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
1475 #endif /* !__LP64__ */
1477 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
1480 options
|= (kIOMemoryRedirected
& _flags
);
1481 if (!(kIOMemoryRedirected
& options
))
1485 memoryReferenceRelease(_memRef
);
1489 _mappings
->flushCollection();
1495 _initialized
= true;
1498 // Grab the appropriate mapper
1499 if (kIOMemoryHostOrRemote
& options
) options
|= kIOMemoryMapperNone
;
1500 if (kIOMemoryMapperNone
& options
)
1501 mapper
= 0; // No Mapper
1502 else if (mapper
== kIOMapperSystem
) {
1503 IOMapper::checkForSystemMapper();
1504 gIOSystemMapper
= mapper
= IOMapper::gSystem
;
1507 // Remove the dynamic internal use flags from the initial setting
1508 options
&= ~(kIOMemoryPreparedReadOnly
);
1513 _direction
= (IODirection
) (_flags
& kIOMemoryDirectionMask
);
1514 #endif /* !__LP64__ */
1517 __iomd_reservedA
= 0;
1518 __iomd_reservedB
= 0;
1521 if (kIOMemoryThreadSafe
& options
)
1524 _prepareLock
= IOLockAlloc();
1526 else if (_prepareLock
)
1528 IOLockFree(_prepareLock
);
1529 _prepareLock
= NULL
;
1532 if (kIOMemoryTypeUPL
== type
) {
1535 unsigned int dataSize
= computeDataSize(/* pages */ 0, /* upls */ 1);
1537 if (!initMemoryEntries(dataSize
, mapper
)) return (false);
1538 dataP
= getDataP(_memoryEntries
);
1539 dataP
->fPageCnt
= 0;
1540 switch (kIOMemoryDirectionMask
& options
)
1542 case kIODirectionOut
:
1543 dataP
->fDMAAccess
= kIODMAMapReadAccess
;
1545 case kIODirectionIn
:
1546 dataP
->fDMAAccess
= kIODMAMapWriteAccess
;
1548 case kIODirectionNone
:
1549 case kIODirectionOutIn
:
1551 panic("bad dir for upl 0x%x\n", (int) options
);
1554 // _wireCount++; // UPLs start out life wired
1557 _pages
+= atop_32(offset
+ count
+ PAGE_MASK
) - atop_32(offset
);
1560 iopl
.fIOPL
= (upl_t
) buffers
;
1561 upl_set_referenced(iopl
.fIOPL
, true);
1562 upl_page_info_t
*pageList
= UPL_GET_INTERNAL_PAGE_LIST(iopl
.fIOPL
);
1564 if (upl_get_size(iopl
.fIOPL
) < (count
+ offset
))
1565 panic("short external upl");
1567 _highestPage
= upl_get_highest_page(iopl
.fIOPL
);
1569 // Set the flag kIOPLOnDevice convieniently equal to 1
1570 iopl
.fFlags
= pageList
->device
| kIOPLExternUPL
;
1571 if (!pageList
->device
) {
1572 // Pre-compute the offset into the UPL's page list
1573 pageList
= &pageList
[atop_32(offset
)];
1574 offset
&= PAGE_MASK
;
1576 iopl
.fIOMDOffset
= 0;
1577 iopl
.fMappedPage
= 0;
1578 iopl
.fPageInfo
= (vm_address_t
) pageList
;
1579 iopl
.fPageOffset
= offset
;
1580 _memoryEntries
->appendBytes(&iopl
, sizeof(iopl
));
1583 // kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO
1584 // kIOMemoryTypePhysical | kIOMemoryTypePhysical64
1586 // Initialize the memory descriptor
1587 if (options
& kIOMemoryAsReference
) {
1589 _rangesIsAllocated
= false;
1590 #endif /* !__LP64__ */
1592 // Hack assignment to get the buffer arg into _ranges.
1593 // I'd prefer to do _ranges = (Ranges) buffers, but that doesn't
1595 // This also initialises the uio & physical ranges.
1596 _ranges
.v
= (IOVirtualRange
*) buffers
;
1600 _rangesIsAllocated
= true;
1601 #endif /* !__LP64__ */
1604 case kIOMemoryTypeUIO
:
1605 _ranges
.v
= (IOVirtualRange
*) uio_duplicate((uio_t
) buffers
);
1609 case kIOMemoryTypeVirtual64
:
1610 case kIOMemoryTypePhysical64
:
1613 && (((IOAddressRange
*) buffers
)->address
+ ((IOAddressRange
*) buffers
)->length
) <= 0x100000000ULL
1616 if (kIOMemoryTypeVirtual64
== type
)
1617 type
= kIOMemoryTypeVirtual
;
1619 type
= kIOMemoryTypePhysical
;
1620 _flags
= (_flags
& ~kIOMemoryTypeMask
) | type
| kIOMemoryAsReference
;
1621 _rangesIsAllocated
= false;
1622 _ranges
.v
= &_singleRange
.v
;
1623 _singleRange
.v
.address
= ((IOAddressRange
*) buffers
)->address
;
1624 _singleRange
.v
.length
= ((IOAddressRange
*) buffers
)->length
;
1627 _ranges
.v64
= IONew(IOAddressRange
, count
);
1630 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOAddressRange
));
1632 #endif /* !__LP64__ */
1633 case kIOMemoryTypeVirtual
:
1634 case kIOMemoryTypePhysical
:
1636 _flags
|= kIOMemoryAsReference
;
1638 _rangesIsAllocated
= false;
1639 #endif /* !__LP64__ */
1640 _ranges
.v
= &_singleRange
.v
;
1642 _ranges
.v
= IONew(IOVirtualRange
, count
);
1646 bcopy(buffers
, _ranges
.v
, count
* sizeof(IOVirtualRange
));
1650 _rangesCount
= count
;
1652 // Find starting address within the vector of ranges
1653 Ranges vec
= _ranges
;
1654 mach_vm_size_t totalLength
= 0;
1655 unsigned int ind
, pages
= 0;
1656 for (ind
= 0; ind
< count
; ind
++) {
1657 mach_vm_address_t addr
;
1658 mach_vm_address_t endAddr
;
1661 // addr & len are returned by this function
1662 getAddrLenForInd(addr
, len
, type
, vec
, ind
);
1663 if (os_add3_overflow(addr
, len
, PAGE_MASK
, &endAddr
)) break;
1664 if (os_add_overflow(pages
, (atop_64(endAddr
) - atop_64(addr
)), &pages
)) break;
1665 if (os_add_overflow(totalLength
, len
, &totalLength
)) break;
1666 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
1668 ppnum_t highPage
= atop_64(addr
+ len
- 1);
1669 if (highPage
> _highestPage
)
1670 _highestPage
= highPage
;
1674 || (totalLength
!= ((IOByteCount
) totalLength
))) return (false); /* overflow */
1676 _length
= totalLength
;
1679 // Auto-prepare memory at creation time.
1680 // Implied completion when descriptor is free-ed
1683 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
1684 _wireCount
++; // Physical MDs are, by definition, wired
1685 else { /* kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO */
1689 if (_pages
> atop_64(max_mem
)) return false;
1691 dataSize
= computeDataSize(_pages
, /* upls */ count
* 2);
1692 if (!initMemoryEntries(dataSize
, mapper
)) return false;
1693 dataP
= getDataP(_memoryEntries
);
1694 dataP
->fPageCnt
= _pages
;
1696 if (((_task
!= kernel_task
) || (kIOMemoryBufferPageable
& _flags
))
1697 && (VM_KERN_MEMORY_NONE
== _kernelTag
))
1699 _kernelTag
= IOMemoryTag(kernel_map
);
1702 if ( (kIOMemoryPersistent
& _flags
) && !_memRef
)
1705 err
= memoryReferenceCreate(0, &_memRef
);
1706 if (kIOReturnSuccess
!= err
) return false;
1709 if ((_flags
& kIOMemoryAutoPrepare
)
1710 && prepare() != kIOReturnSuccess
)
1723 void IOGeneralMemoryDescriptor::free()
1725 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
1730 reserved
->dp
.memory
= 0;
1733 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
1736 if (_memoryEntries
&& (dataP
= getDataP(_memoryEntries
)) && dataP
->fMappedBaseValid
)
1738 dmaUnmap(dataP
->fMapper
, NULL
, 0, dataP
->fMappedBase
, dataP
->fMappedLength
);
1739 dataP
->fMappedBaseValid
= dataP
->fMappedBase
= 0;
1744 while (_wireCount
) complete();
1747 if (_memoryEntries
) _memoryEntries
->release();
1749 if (_ranges
.v
&& !(kIOMemoryAsReference
& _flags
))
1751 if (kIOMemoryTypeUIO
== type
)
1752 uio_free((uio_t
) _ranges
.v
);
1754 else if ((kIOMemoryTypeVirtual64
== type
) || (kIOMemoryTypePhysical64
== type
))
1755 IODelete(_ranges
.v64
, IOAddressRange
, _rangesCount
);
1756 #endif /* !__LP64__ */
1758 IODelete(_ranges
.v
, IOVirtualRange
, _rangesCount
);
1765 if (reserved
->dp
.devicePager
)
1767 // memEntry holds a ref on the device pager which owns reserved
1768 // (IOMemoryDescriptorReserved) so no reserved access after this point
1769 device_pager_deallocate( (memory_object_t
) reserved
->dp
.devicePager
);
1772 IODelete(reserved
, IOMemoryDescriptorReserved
, 1);
1776 if (_memRef
) memoryReferenceRelease(_memRef
);
1777 if (_prepareLock
) IOLockFree(_prepareLock
);
1783 void IOGeneralMemoryDescriptor::unmapFromKernel()
1785 panic("IOGMD::unmapFromKernel deprecated");
1788 void IOGeneralMemoryDescriptor::mapIntoKernel(unsigned rangeIndex
)
1790 panic("IOGMD::mapIntoKernel deprecated");
1792 #endif /* !__LP64__ */
1797 * Get the direction of the transfer.
1799 IODirection
IOMemoryDescriptor::getDirection() const
1804 #endif /* !__LP64__ */
1805 return (IODirection
) (_flags
& kIOMemoryDirectionMask
);
1811 * Get the length of the transfer (over all ranges).
1813 IOByteCount
IOMemoryDescriptor::getLength() const
1818 void IOMemoryDescriptor::setTag( IOOptionBits tag
)
1823 IOOptionBits
IOMemoryDescriptor::getTag( void )
1828 uint64_t IOMemoryDescriptor::getFlags(void)
1834 #pragma clang diagnostic push
1835 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1837 // @@@ gvdl: who is using this API? Seems like a wierd thing to implement.
1839 IOMemoryDescriptor::getSourceSegment( IOByteCount offset
, IOByteCount
* length
)
1841 addr64_t physAddr
= 0;
1843 if( prepare() == kIOReturnSuccess
) {
1844 physAddr
= getPhysicalSegment64( offset
, length
);
1848 return( (IOPhysicalAddress
) physAddr
); // truncated but only page offset is used
1851 #pragma clang diagnostic pop
1853 #endif /* !__LP64__ */
1855 IOByteCount
IOMemoryDescriptor::readBytes
1856 (IOByteCount offset
, void *bytes
, IOByteCount length
)
1858 addr64_t dstAddr
= CAST_DOWN(addr64_t
, bytes
);
1859 IOByteCount remaining
;
1861 // Assert that this entire I/O is withing the available range
1862 assert(offset
<= _length
);
1863 assert(offset
+ length
<= _length
);
1864 if ((offset
>= _length
)
1865 || ((offset
+ length
) > _length
)) {
1869 assert (!(kIOMemoryRemote
& _flags
));
1870 if (kIOMemoryRemote
& _flags
) return (0);
1872 if (kIOMemoryThreadSafe
& _flags
)
1875 remaining
= length
= min(length
, _length
- offset
);
1876 while (remaining
) { // (process another target segment?)
1880 srcAddr64
= getPhysicalSegment(offset
, &srcLen
, kIOMemoryMapperNone
);
1884 // Clip segment length to remaining
1885 if (srcLen
> remaining
)
1888 copypv(srcAddr64
, dstAddr
, srcLen
,
1889 cppvPsrc
| cppvNoRefSrc
| cppvFsnk
| cppvKmap
);
1893 remaining
-= srcLen
;
1896 if (kIOMemoryThreadSafe
& _flags
)
1901 return length
- remaining
;
1904 IOByteCount
IOMemoryDescriptor::writeBytes
1905 (IOByteCount inoffset
, const void *bytes
, IOByteCount length
)
1907 addr64_t srcAddr
= CAST_DOWN(addr64_t
, bytes
);
1908 IOByteCount remaining
;
1909 IOByteCount offset
= inoffset
;
1911 // Assert that this entire I/O is withing the available range
1912 assert(offset
<= _length
);
1913 assert(offset
+ length
<= _length
);
1915 assert( !(kIOMemoryPreparedReadOnly
& _flags
) );
1917 if ( (kIOMemoryPreparedReadOnly
& _flags
)
1918 || (offset
>= _length
)
1919 || ((offset
+ length
) > _length
)) {
1923 assert (!(kIOMemoryRemote
& _flags
));
1924 if (kIOMemoryRemote
& _flags
) return (0);
1926 if (kIOMemoryThreadSafe
& _flags
)
1929 remaining
= length
= min(length
, _length
- offset
);
1930 while (remaining
) { // (process another target segment?)
1934 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
1938 // Clip segment length to remaining
1939 if (dstLen
> remaining
)
1942 if (!srcAddr
) bzero_phys(dstAddr64
, dstLen
);
1945 copypv(srcAddr
, (addr64_t
) dstAddr64
, dstLen
,
1946 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
1950 remaining
-= dstLen
;
1953 if (kIOMemoryThreadSafe
& _flags
)
1958 if (!srcAddr
) performOperation(kIOMemoryIncoherentIOFlush
, inoffset
, length
);
1960 return length
- remaining
;
1964 void IOGeneralMemoryDescriptor::setPosition(IOByteCount position
)
1966 panic("IOGMD::setPosition deprecated");
1968 #endif /* !__LP64__ */
1970 static volatile SInt64 gIOMDPreparationID
__attribute__((aligned(8))) = (1ULL << 32);
1973 IOGeneralMemoryDescriptor::getPreparationID( void )
1978 return (kIOPreparationIDUnprepared
);
1980 if (((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical
)
1981 || ((kIOMemoryTypeMask
& _flags
) == kIOMemoryTypePhysical64
))
1983 IOMemoryDescriptor::setPreparationID();
1984 return (IOMemoryDescriptor::getPreparationID());
1987 if (!_memoryEntries
|| !(dataP
= getDataP(_memoryEntries
)))
1988 return (kIOPreparationIDUnprepared
);
1990 if (kIOPreparationIDUnprepared
== dataP
->fPreparationID
)
1992 dataP
->fPreparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
1994 return (dataP
->fPreparationID
);
1997 IOMemoryDescriptorReserved
* IOMemoryDescriptor::getKernelReserved( void )
2001 reserved
= IONew(IOMemoryDescriptorReserved
, 1);
2003 bzero(reserved
, sizeof(IOMemoryDescriptorReserved
));
2008 void IOMemoryDescriptor::setPreparationID( void )
2010 if (getKernelReserved() && (kIOPreparationIDUnprepared
== reserved
->preparationID
))
2012 reserved
->preparationID
= OSIncrementAtomic64(&gIOMDPreparationID
);
2016 uint64_t IOMemoryDescriptor::getPreparationID( void )
2019 return (reserved
->preparationID
);
2021 return (kIOPreparationIDUnsupported
);
2024 void IOMemoryDescriptor::setVMTags(vm_tag_t kernelTag
, vm_tag_t userTag
)
2026 _kernelTag
= kernelTag
;
2030 vm_tag_t
IOMemoryDescriptor::getVMTag(vm_map_t map
)
2032 if (vm_kernel_map_is_kernel(map
))
2034 if (VM_KERN_MEMORY_NONE
!= _kernelTag
) return (_kernelTag
);
2038 if (VM_KERN_MEMORY_NONE
!= _userTag
) return (_userTag
);
2040 return (IOMemoryTag(map
));
2043 IOReturn
IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
2045 IOReturn err
= kIOReturnSuccess
;
2046 DMACommandOps params
;
2047 IOGeneralMemoryDescriptor
* md
= const_cast<IOGeneralMemoryDescriptor
*>(this);
2050 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
2051 op
&= kIOMDDMACommandOperationMask
;
2053 if (kIOMDDMAMap
== op
)
2055 if (dataSize
< sizeof(IOMDDMAMapArgs
))
2056 return kIOReturnUnderrun
;
2058 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
2061 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
2063 if (_memoryEntries
&& data
->fMapper
)
2065 bool remap
, keepMap
;
2066 dataP
= getDataP(_memoryEntries
);
2068 if (data
->fMapSpec
.numAddressBits
< dataP
->fDMAMapNumAddressBits
) dataP
->fDMAMapNumAddressBits
= data
->fMapSpec
.numAddressBits
;
2069 if (data
->fMapSpec
.alignment
> dataP
->fDMAMapAlignment
) dataP
->fDMAMapAlignment
= data
->fMapSpec
.alignment
;
2071 keepMap
= (data
->fMapper
== gIOSystemMapper
);
2072 keepMap
&= ((data
->fOffset
== 0) && (data
->fLength
== _length
));
2074 if ((data
->fMapper
== gIOSystemMapper
) && _prepareLock
) IOLockLock(_prepareLock
);
2077 remap
|= (dataP
->fDMAMapNumAddressBits
< 64)
2078 && ((dataP
->fMappedBase
+ _length
) > (1ULL << dataP
->fDMAMapNumAddressBits
));
2079 remap
|= (dataP
->fDMAMapAlignment
> page_size
);
2081 if (remap
|| !dataP
->fMappedBaseValid
)
2083 // if (dataP->fMappedBaseValid) OSReportWithBacktrace("kIOMDDMAMap whole %d remap %d params %d\n", whole, remap, params);
2084 err
= md
->dmaMap(data
->fMapper
, data
->fCommand
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocLength
);
2085 if (keepMap
&& (kIOReturnSuccess
== err
) && !dataP
->fMappedBaseValid
)
2087 dataP
->fMappedBase
= data
->fAlloc
;
2088 dataP
->fMappedBaseValid
= true;
2089 dataP
->fMappedLength
= data
->fAllocLength
;
2090 data
->fAllocLength
= 0; // IOMD owns the alloc now
2095 data
->fAlloc
= dataP
->fMappedBase
;
2096 data
->fAllocLength
= 0; // give out IOMD map
2097 md
->dmaMapRecord(data
->fMapper
, data
->fCommand
, dataP
->fMappedLength
);
2099 data
->fMapContig
= !dataP
->fDiscontig
;
2101 if ((data
->fMapper
== gIOSystemMapper
) && _prepareLock
) IOLockUnlock(_prepareLock
);
2105 if (kIOMDDMAUnmap
== op
)
2107 if (dataSize
< sizeof(IOMDDMAMapArgs
))
2108 return kIOReturnUnderrun
;
2109 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
2111 err
= md
->dmaUnmap(data
->fMapper
, data
->fCommand
, data
->fOffset
, data
->fAlloc
, data
->fAllocLength
);
2113 return kIOReturnSuccess
;
2116 if (kIOMDAddDMAMapSpec
== op
)
2118 if (dataSize
< sizeof(IODMAMapSpecification
))
2119 return kIOReturnUnderrun
;
2121 IODMAMapSpecification
* data
= (IODMAMapSpecification
*) vData
;
2124 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
2128 dataP
= getDataP(_memoryEntries
);
2129 if (data
->numAddressBits
< dataP
->fDMAMapNumAddressBits
)
2130 dataP
->fDMAMapNumAddressBits
= data
->numAddressBits
;
2131 if (data
->alignment
> dataP
->fDMAMapAlignment
)
2132 dataP
->fDMAMapAlignment
= data
->alignment
;
2134 return kIOReturnSuccess
;
2137 if (kIOMDGetCharacteristics
== op
) {
2139 if (dataSize
< sizeof(IOMDDMACharacteristics
))
2140 return kIOReturnUnderrun
;
2142 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
2143 data
->fLength
= _length
;
2144 data
->fSGCount
= _rangesCount
;
2145 data
->fPages
= _pages
;
2146 data
->fDirection
= getDirection();
2148 data
->fIsPrepared
= false;
2150 data
->fIsPrepared
= true;
2151 data
->fHighestPage
= _highestPage
;
2154 dataP
= getDataP(_memoryEntries
);
2155 ioPLBlock
*ioplList
= getIOPLList(dataP
);
2156 UInt count
= getNumIOPL(_memoryEntries
, dataP
);
2158 data
->fPageAlign
= (ioplList
[0].fPageOffset
& PAGE_MASK
) | ~PAGE_MASK
;
2162 return kIOReturnSuccess
;
2165 else if (kIOMDDMAActive
== op
)
2170 prior
= OSAddAtomic16(1, &md
->_dmaReferences
);
2171 if (!prior
) md
->_mapName
= NULL
;
2175 if (md
->_dmaReferences
) OSAddAtomic16(-1, &md
->_dmaReferences
);
2176 else panic("_dmaReferences underflow");
2179 else if (kIOMDWalkSegments
!= op
)
2180 return kIOReturnBadArgument
;
2182 // Get the next segment
2183 struct InternalState
{
2184 IOMDDMAWalkSegmentArgs fIO
;
2190 // Find the next segment
2191 if (dataSize
< sizeof(*isP
))
2192 return kIOReturnUnderrun
;
2194 isP
= (InternalState
*) vData
;
2195 UInt offset
= isP
->fIO
.fOffset
;
2196 uint8_t mapped
= isP
->fIO
.fMapped
;
2197 uint64_t mappedBase
;
2199 if (mapped
&& (kIOMemoryRemote
& _flags
)) return (kIOReturnNotAttached
);
2201 if (IOMapper::gSystem
&& mapped
2202 && (!(kIOMemoryHostOnly
& _flags
))
2203 && (!_memoryEntries
|| !getDataP(_memoryEntries
)->fMappedBaseValid
))
2204 // && (_memoryEntries && !getDataP(_memoryEntries)->fMappedBaseValid))
2207 && !md
->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem
)) return (kIOReturnNoMemory
);
2209 dataP
= getDataP(_memoryEntries
);
2212 IODMAMapSpecification mapSpec
;
2213 bzero(&mapSpec
, sizeof(mapSpec
));
2214 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
2215 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
2216 err
= md
->dmaMap(dataP
->fMapper
, NULL
, &mapSpec
, 0, _length
, &dataP
->fMappedBase
, &dataP
->fMappedLength
);
2217 if (kIOReturnSuccess
!= err
) return (err
);
2218 dataP
->fMappedBaseValid
= true;
2222 if (kIOMDDMAWalkMappedLocal
== mapped
) mappedBase
= isP
->fIO
.fMappedBase
;
2225 if (IOMapper::gSystem
2226 && (!(kIOMemoryHostOnly
& _flags
))
2228 && (dataP
= getDataP(_memoryEntries
))
2229 && dataP
->fMappedBaseValid
)
2231 mappedBase
= dataP
->fMappedBase
;
2236 if (offset
>= _length
)
2237 return (offset
== _length
)? kIOReturnOverrun
: kIOReturnInternalError
;
2239 // Validate the previous offset
2240 UInt ind
, off2Ind
= isP
->fOffset2Index
;
2243 && (offset
== isP
->fNextOffset
|| off2Ind
<= offset
))
2246 ind
= off2Ind
= 0; // Start from beginning
2251 if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
) {
2253 // Physical address based memory descriptor
2254 const IOPhysicalRange
*physP
= (IOPhysicalRange
*) &_ranges
.p
[0];
2256 // Find the range after the one that contains the offset
2258 for (len
= 0; off2Ind
<= offset
; ind
++) {
2259 len
= physP
[ind
].length
;
2263 // Calculate length within range and starting address
2264 length
= off2Ind
- offset
;
2265 address
= physP
[ind
- 1].address
+ len
- length
;
2269 address
= mappedBase
+ offset
;
2273 // see how far we can coalesce ranges
2274 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
2275 len
= physP
[ind
].length
;
2282 // correct contiguous check overshoot
2287 else if ( (_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
) {
2289 // Physical address based memory descriptor
2290 const IOAddressRange
*physP
= (IOAddressRange
*) &_ranges
.v64
[0];
2292 // Find the range after the one that contains the offset
2294 for (len
= 0; off2Ind
<= offset
; ind
++) {
2295 len
= physP
[ind
].length
;
2299 // Calculate length within range and starting address
2300 length
= off2Ind
- offset
;
2301 address
= physP
[ind
- 1].address
+ len
- length
;
2305 address
= mappedBase
+ offset
;
2309 // see how far we can coalesce ranges
2310 while (ind
< _rangesCount
&& address
+ length
== physP
[ind
].address
) {
2311 len
= physP
[ind
].length
;
2317 // correct contiguous check overshoot
2321 #endif /* !__LP64__ */
2324 panic("IOGMD: not wired for the IODMACommand");
2326 assert(_memoryEntries
);
2328 dataP
= getDataP(_memoryEntries
);
2329 const ioPLBlock
*ioplList
= getIOPLList(dataP
);
2330 UInt numIOPLs
= getNumIOPL(_memoryEntries
, dataP
);
2331 upl_page_info_t
*pageList
= getPageList(dataP
);
2333 assert(numIOPLs
> 0);
2335 // Scan through iopl info blocks looking for block containing offset
2336 while (ind
< numIOPLs
&& offset
>= ioplList
[ind
].fIOMDOffset
)
2339 // Go back to actual range as search goes past it
2340 ioPLBlock ioplInfo
= ioplList
[ind
- 1];
2341 off2Ind
= ioplInfo
.fIOMDOffset
;
2344 length
= ioplList
[ind
].fIOMDOffset
;
2347 length
-= offset
; // Remainder within iopl
2349 // Subtract offset till this iopl in total list
2352 // If a mapped address is requested and this is a pre-mapped IOPL
2353 // then just need to compute an offset relative to the mapped base.
2355 offset
+= (ioplInfo
.fPageOffset
& PAGE_MASK
);
2356 address
= trunc_page_64(mappedBase
) + ptoa_64(ioplInfo
.fMappedPage
) + offset
;
2357 continue; // Done leave do/while(false) now
2360 // The offset is rebased into the current iopl.
2361 // Now add the iopl 1st page offset.
2362 offset
+= ioplInfo
.fPageOffset
;
2364 // For external UPLs the fPageInfo field points directly to
2365 // the upl's upl_page_info_t array.
2366 if (ioplInfo
.fFlags
& kIOPLExternUPL
)
2367 pageList
= (upl_page_info_t
*) ioplInfo
.fPageInfo
;
2369 pageList
= &pageList
[ioplInfo
.fPageInfo
];
2371 // Check for direct device non-paged memory
2372 if ( ioplInfo
.fFlags
& kIOPLOnDevice
) {
2373 address
= ptoa_64(pageList
->phys_addr
) + offset
;
2374 continue; // Done leave do/while(false) now
2377 // Now we need compute the index into the pageList
2378 UInt pageInd
= atop_32(offset
);
2379 offset
&= PAGE_MASK
;
2381 // Compute the starting address of this segment
2382 IOPhysicalAddress pageAddr
= pageList
[pageInd
].phys_addr
;
2384 panic("!pageList phys_addr");
2387 address
= ptoa_64(pageAddr
) + offset
;
2389 // length is currently set to the length of the remainider of the iopl.
2390 // We need to check that the remainder of the iopl is contiguous.
2391 // This is indicated by pageList[ind].phys_addr being sequential.
2392 IOByteCount contigLength
= PAGE_SIZE
- offset
;
2393 while (contigLength
< length
2394 && ++pageAddr
== pageList
[++pageInd
].phys_addr
)
2396 contigLength
+= PAGE_SIZE
;
2399 if (contigLength
< length
)
2400 length
= contigLength
;
2408 // Update return values and state
2409 isP
->fIO
.fIOVMAddr
= address
;
2410 isP
->fIO
.fLength
= length
;
2412 isP
->fOffset2Index
= off2Ind
;
2413 isP
->fNextOffset
= isP
->fIO
.fOffset
+ length
;
2415 return kIOReturnSuccess
;
2419 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
2422 mach_vm_address_t address
= 0;
2423 mach_vm_size_t length
= 0;
2424 IOMapper
* mapper
= gIOSystemMapper
;
2425 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2427 if (lengthOfSegment
)
2428 *lengthOfSegment
= 0;
2430 if (offset
>= _length
)
2433 // IOMemoryDescriptor::doMap() cannot use getPhysicalSegment() to obtain the page offset, since it must
2434 // support the unwired memory case in IOGeneralMemoryDescriptor, and hibernate_write_image() cannot use
2435 // map()->getVirtualAddress() to obtain the kernel pointer, since it must prevent the memory allocation
2436 // due to IOMemoryMap, so _kIOMemorySourceSegment is a necessary evil until all of this gets cleaned up
2438 if ((options
& _kIOMemorySourceSegment
) && (kIOMemoryTypeUPL
!= type
))
2440 unsigned rangesIndex
= 0;
2441 Ranges vec
= _ranges
;
2442 mach_vm_address_t addr
;
2444 // Find starting address within the vector of ranges
2446 getAddrLenForInd(addr
, length
, type
, vec
, rangesIndex
);
2447 if (offset
< length
)
2449 offset
-= length
; // (make offset relative)
2453 // Now that we have the starting range,
2454 // lets find the last contiguous range
2458 for ( ++rangesIndex
; rangesIndex
< _rangesCount
; rangesIndex
++ ) {
2459 mach_vm_address_t newAddr
;
2460 mach_vm_size_t newLen
;
2462 getAddrLenForInd(newAddr
, newLen
, type
, vec
, rangesIndex
);
2463 if (addr
+ length
!= newAddr
)
2468 address
= (IOPhysicalAddress
) addr
; // Truncate address to 32bit
2472 IOMDDMAWalkSegmentState _state
;
2473 IOMDDMAWalkSegmentArgs
* state
= (IOMDDMAWalkSegmentArgs
*) (void *)&_state
;
2475 state
->fOffset
= offset
;
2476 state
->fLength
= _length
- offset
;
2477 state
->fMapped
= (0 == (options
& kIOMemoryMapperNone
)) && !(_flags
& kIOMemoryHostOrRemote
);
2479 ret
= dmaCommandOperation(kIOMDFirstSegment
, _state
, sizeof(_state
));
2481 if ((kIOReturnSuccess
!= ret
) && (kIOReturnOverrun
!= ret
))
2482 DEBG("getPhysicalSegment dmaCommandOperation(%lx), %p, offset %qx, addr %qx, len %qx\n",
2483 ret
, this, state
->fOffset
,
2484 state
->fIOVMAddr
, state
->fLength
);
2485 if (kIOReturnSuccess
== ret
)
2487 address
= state
->fIOVMAddr
;
2488 length
= state
->fLength
;
2491 // dmaCommandOperation() does not distinguish between "mapped" and "unmapped" physical memory, even
2492 // with fMapped set correctly, so we must handle the transformation here until this gets cleaned up
2494 if (mapper
&& ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
)))
2496 if ((options
& kIOMemoryMapperNone
) && !(_flags
& kIOMemoryMapperNone
))
2498 addr64_t origAddr
= address
;
2499 IOByteCount origLen
= length
;
2501 address
= mapper
->mapToPhysicalAddress(origAddr
);
2502 length
= page_size
- (address
& (page_size
- 1));
2503 while ((length
< origLen
)
2504 && ((address
+ length
) == mapper
->mapToPhysicalAddress(origAddr
+ length
)))
2505 length
+= page_size
;
2506 if (length
> origLen
)
2515 if (lengthOfSegment
)
2516 *lengthOfSegment
= length
;
2522 #pragma clang diagnostic push
2523 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2526 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
, IOOptionBits options
)
2528 addr64_t address
= 0;
2530 if (options
& _kIOMemorySourceSegment
)
2532 address
= getSourceSegment(offset
, lengthOfSegment
);
2534 else if (options
& kIOMemoryMapperNone
)
2536 address
= getPhysicalSegment64(offset
, lengthOfSegment
);
2540 address
= getPhysicalSegment(offset
, lengthOfSegment
);
2545 #pragma clang diagnostic pop
2548 IOGeneralMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2550 return (getPhysicalSegment(offset
, lengthOfSegment
, kIOMemoryMapperNone
));
2554 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2556 addr64_t address
= 0;
2557 IOByteCount length
= 0;
2559 address
= getPhysicalSegment(offset
, lengthOfSegment
, 0);
2561 if (lengthOfSegment
)
2562 length
= *lengthOfSegment
;
2564 if ((address
+ length
) > 0x100000000ULL
)
2566 panic("getPhysicalSegment() out of 32b range 0x%qx, len 0x%lx, class %s",
2567 address
, (long) length
, (getMetaClass())->getClassName());
2570 return ((IOPhysicalAddress
) address
);
2574 IOMemoryDescriptor::getPhysicalSegment64(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2576 IOPhysicalAddress phys32
;
2579 IOMapper
* mapper
= 0;
2581 phys32
= getPhysicalSegment(offset
, lengthOfSegment
);
2585 if (gIOSystemMapper
)
2586 mapper
= gIOSystemMapper
;
2590 IOByteCount origLen
;
2592 phys64
= mapper
->mapToPhysicalAddress(phys32
);
2593 origLen
= *lengthOfSegment
;
2594 length
= page_size
- (phys64
& (page_size
- 1));
2595 while ((length
< origLen
)
2596 && ((phys64
+ length
) == mapper
->mapToPhysicalAddress(phys32
+ length
)))
2597 length
+= page_size
;
2598 if (length
> origLen
)
2601 *lengthOfSegment
= length
;
2604 phys64
= (addr64_t
) phys32
;
2610 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2612 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, 0));
2616 IOGeneralMemoryDescriptor::getSourceSegment(IOByteCount offset
, IOByteCount
*lengthOfSegment
)
2618 return ((IOPhysicalAddress
) getPhysicalSegment(offset
, lengthOfSegment
, _kIOMemorySourceSegment
));
2621 #pragma clang diagnostic push
2622 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2624 void * IOGeneralMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
2625 IOByteCount
* lengthOfSegment
)
2627 if (_task
== kernel_task
)
2628 return (void *) getSourceSegment(offset
, lengthOfSegment
);
2630 panic("IOGMD::getVirtualSegment deprecated");
2634 #pragma clang diagnostic pop
2635 #endif /* !__LP64__ */
2638 IOMemoryDescriptor::dmaCommandOperation(DMACommandOps op
, void *vData
, UInt dataSize
) const
2640 IOMemoryDescriptor
*md
= const_cast<IOMemoryDescriptor
*>(this);
2641 DMACommandOps params
;
2644 params
= (op
& ~kIOMDDMACommandOperationMask
& op
);
2645 op
&= kIOMDDMACommandOperationMask
;
2647 if (kIOMDGetCharacteristics
== op
) {
2648 if (dataSize
< sizeof(IOMDDMACharacteristics
))
2649 return kIOReturnUnderrun
;
2651 IOMDDMACharacteristics
*data
= (IOMDDMACharacteristics
*) vData
;
2652 data
->fLength
= getLength();
2654 data
->fDirection
= getDirection();
2655 data
->fIsPrepared
= true; // Assume prepared - fails safe
2657 else if (kIOMDWalkSegments
== op
) {
2658 if (dataSize
< sizeof(IOMDDMAWalkSegmentArgs
))
2659 return kIOReturnUnderrun
;
2661 IOMDDMAWalkSegmentArgs
*data
= (IOMDDMAWalkSegmentArgs
*) vData
;
2662 IOByteCount offset
= (IOByteCount
) data
->fOffset
;
2664 IOPhysicalLength length
;
2665 if (data
->fMapped
&& IOMapper::gSystem
)
2666 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
);
2668 data
->fIOVMAddr
= md
->getPhysicalSegment(offset
, &length
, kIOMemoryMapperNone
);
2669 data
->fLength
= length
;
2671 else if (kIOMDAddDMAMapSpec
== op
) return kIOReturnUnsupported
;
2672 else if (kIOMDDMAMap
== op
)
2674 if (dataSize
< sizeof(IOMDDMAMapArgs
))
2675 return kIOReturnUnderrun
;
2676 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
2678 if (params
) panic("class %s does not support IODMACommand::kIterateOnly", getMetaClass()->getClassName());
2680 data
->fMapContig
= true;
2681 err
= md
->dmaMap(data
->fMapper
, data
->fCommand
, &data
->fMapSpec
, data
->fOffset
, data
->fLength
, &data
->fAlloc
, &data
->fAllocLength
);
2685 else if (kIOMDDMAUnmap
== op
)
2687 if (dataSize
< sizeof(IOMDDMAMapArgs
))
2688 return kIOReturnUnderrun
;
2689 IOMDDMAMapArgs
* data
= (IOMDDMAMapArgs
*) vData
;
2691 err
= md
->dmaUnmap(data
->fMapper
, data
->fCommand
, data
->fOffset
, data
->fAlloc
, data
->fAllocLength
);
2693 return (kIOReturnSuccess
);
2695 else return kIOReturnBadArgument
;
2697 return kIOReturnSuccess
;
2701 IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState
,
2702 IOOptionBits
* oldState
)
2704 IOReturn err
= kIOReturnSuccess
;
2706 vm_purgable_t control
;
2709 assert (!(kIOMemoryRemote
& _flags
));
2710 if (kIOMemoryRemote
& _flags
) return (kIOReturnNotAttached
);
2714 err
= super::setPurgeable(newState
, oldState
);
2718 if (kIOMemoryThreadSafe
& _flags
)
2722 // Find the appropriate vm_map for the given task
2724 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
))
2726 err
= kIOReturnNotReady
;
2731 err
= kIOReturnUnsupported
;
2736 curMap
= get_task_map(_task
);
2739 err
= KERN_INVALID_ARGUMENT
;
2744 // can only do one range
2745 Ranges vec
= _ranges
;
2746 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
2747 mach_vm_address_t addr
;
2749 getAddrLenForInd(addr
, len
, type
, vec
, 0);
2751 err
= purgeableControlBits(newState
, &control
, &state
);
2752 if (kIOReturnSuccess
!= err
)
2754 err
= vm_map_purgable_control(curMap
, addr
, control
, &state
);
2757 if (kIOReturnSuccess
== err
)
2759 err
= purgeableStateBits(&state
);
2765 if (kIOMemoryThreadSafe
& _flags
)
2772 IOReturn
IOMemoryDescriptor::setPurgeable( IOOptionBits newState
,
2773 IOOptionBits
* oldState
)
2775 IOReturn err
= kIOReturnNotReady
;
2777 if (kIOMemoryThreadSafe
& _flags
) LOCK
;
2778 if (_memRef
) err
= IOGeneralMemoryDescriptor::memoryReferenceSetPurgeable(_memRef
, newState
, oldState
);
2779 if (kIOMemoryThreadSafe
& _flags
) UNLOCK
;
2784 IOReturn
IOMemoryDescriptor::getPageCounts( IOByteCount
* residentPageCount
,
2785 IOByteCount
* dirtyPageCount
)
2787 IOReturn err
= kIOReturnNotReady
;
2789 assert (!(kIOMemoryRemote
& _flags
));
2790 if (kIOMemoryRemote
& _flags
) return (kIOReturnNotAttached
);
2792 if (kIOMemoryThreadSafe
& _flags
) LOCK
;
2793 if (_memRef
) err
= IOGeneralMemoryDescriptor::memoryReferenceGetPageCounts(_memRef
, residentPageCount
, dirtyPageCount
);
2796 IOMultiMemoryDescriptor
* mmd
;
2797 IOSubMemoryDescriptor
* smd
;
2798 if ((smd
= OSDynamicCast(IOSubMemoryDescriptor
, this)))
2800 err
= smd
->getPageCounts(residentPageCount
, dirtyPageCount
);
2802 else if ((mmd
= OSDynamicCast(IOMultiMemoryDescriptor
, this)))
2804 err
= mmd
->getPageCounts(residentPageCount
, dirtyPageCount
);
2807 if (kIOMemoryThreadSafe
& _flags
) UNLOCK
;
2813 #if defined(__arm__) || defined(__arm64__)
2814 extern "C" void dcache_incoherent_io_flush64(addr64_t pa
, unsigned int count
, unsigned int remaining
, unsigned int *res
);
2815 extern "C" void dcache_incoherent_io_store64(addr64_t pa
, unsigned int count
, unsigned int remaining
, unsigned int *res
);
2816 #else /* defined(__arm__) || defined(__arm64__) */
2817 extern "C" void dcache_incoherent_io_flush64(addr64_t pa
, unsigned int count
);
2818 extern "C" void dcache_incoherent_io_store64(addr64_t pa
, unsigned int count
);
2819 #endif /* defined(__arm__) || defined(__arm64__) */
2821 static void SetEncryptOp(addr64_t pa
, unsigned int count
)
2825 page
= atop_64(round_page_64(pa
));
2826 end
= atop_64(trunc_page_64(pa
+ count
));
2827 for (; page
< end
; page
++)
2829 pmap_clear_noencrypt(page
);
2833 static void ClearEncryptOp(addr64_t pa
, unsigned int count
)
2837 page
= atop_64(round_page_64(pa
));
2838 end
= atop_64(trunc_page_64(pa
+ count
));
2839 for (; page
< end
; page
++)
2841 pmap_set_noencrypt(page
);
2845 IOReturn
IOMemoryDescriptor::performOperation( IOOptionBits options
,
2846 IOByteCount offset
, IOByteCount length
)
2848 IOByteCount remaining
;
2850 void (*func
)(addr64_t pa
, unsigned int count
) = 0;
2851 #if defined(__arm__) || defined(__arm64__)
2852 void (*func_ext
)(addr64_t pa
, unsigned int count
, unsigned int remaining
, unsigned int *result
) = 0;
2855 assert (!(kIOMemoryRemote
& _flags
));
2856 if (kIOMemoryRemote
& _flags
) return (kIOReturnNotAttached
);
2860 case kIOMemoryIncoherentIOFlush
:
2861 #if defined(__arm__) || defined(__arm64__)
2862 func_ext
= &dcache_incoherent_io_flush64
;
2863 #if __ARM_COHERENT_IO__
2864 func_ext(0, 0, 0, &res
);
2865 return kIOReturnSuccess
;
2866 #else /* __ARM_COHERENT_IO__ */
2868 #endif /* __ARM_COHERENT_IO__ */
2869 #else /* defined(__arm__) || defined(__arm64__) */
2870 func
= &dcache_incoherent_io_flush64
;
2872 #endif /* defined(__arm__) || defined(__arm64__) */
2873 case kIOMemoryIncoherentIOStore
:
2874 #if defined(__arm__) || defined(__arm64__)
2875 func_ext
= &dcache_incoherent_io_store64
;
2876 #if __ARM_COHERENT_IO__
2877 func_ext(0, 0, 0, &res
);
2878 return kIOReturnSuccess
;
2879 #else /* __ARM_COHERENT_IO__ */
2881 #endif /* __ARM_COHERENT_IO__ */
2882 #else /* defined(__arm__) || defined(__arm64__) */
2883 func
= &dcache_incoherent_io_store64
;
2885 #endif /* defined(__arm__) || defined(__arm64__) */
2887 case kIOMemorySetEncrypted
:
2888 func
= &SetEncryptOp
;
2890 case kIOMemoryClearEncrypted
:
2891 func
= &ClearEncryptOp
;
2895 #if defined(__arm__) || defined(__arm64__)
2896 if ((func
== 0) && (func_ext
== 0))
2897 return (kIOReturnUnsupported
);
2898 #else /* defined(__arm__) || defined(__arm64__) */
2900 return (kIOReturnUnsupported
);
2901 #endif /* defined(__arm__) || defined(__arm64__) */
2903 if (kIOMemoryThreadSafe
& _flags
)
2907 remaining
= length
= min(length
, getLength() - offset
);
2909 // (process another target segment?)
2914 dstAddr64
= getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
2918 // Clip segment length to remaining
2919 if (dstLen
> remaining
)
2922 #if defined(__arm__) || defined(__arm64__)
2924 (*func
)(dstAddr64
, dstLen
);
2926 (*func_ext
)(dstAddr64
, dstLen
, remaining
, &res
);
2932 #else /* defined(__arm__) || defined(__arm64__) */
2933 (*func
)(dstAddr64
, dstLen
);
2934 #endif /* defined(__arm__) || defined(__arm64__) */
2937 remaining
-= dstLen
;
2940 if (kIOMemoryThreadSafe
& _flags
)
2943 return (remaining
? kIOReturnUnderrun
: kIOReturnSuccess
);
2950 #if defined(__i386__) || defined(__x86_64__)
2952 #define io_kernel_static_start vm_kernel_stext
2953 #define io_kernel_static_end vm_kernel_etext
2955 #elif defined(__arm__) || defined(__arm64__)
2957 extern vm_offset_t static_memory_end
;
2959 #if defined(__arm64__)
2960 #define io_kernel_static_start vm_kext_base
2961 #else /* defined(__arm64__) */
2962 #define io_kernel_static_start vm_kernel_stext
2963 #endif /* defined(__arm64__) */
2965 #define io_kernel_static_end static_memory_end
2968 #error io_kernel_static_end is undefined for this architecture
2971 static kern_return_t
2972 io_get_kernel_static_upl(
2975 upl_size_t
*upl_size
,
2977 upl_page_info_array_t page_list
,
2978 unsigned int *count
,
2979 ppnum_t
*highest_page
)
2981 unsigned int pageCount
, page
;
2983 ppnum_t highestPage
= 0;
2985 pageCount
= atop_32(*upl_size
);
2986 if (pageCount
> *count
)
2991 for (page
= 0; page
< pageCount
; page
++)
2993 phys
= pmap_find_phys(kernel_pmap
, ((addr64_t
)offset
) + ptoa_64(page
));
2996 page_list
[page
].phys_addr
= phys
;
2997 page_list
[page
].free_when_done
= 0;
2998 page_list
[page
].absent
= 0;
2999 page_list
[page
].dirty
= 0;
3000 page_list
[page
].precious
= 0;
3001 page_list
[page
].device
= 0;
3002 if (phys
> highestPage
)
3006 *highest_page
= highestPage
;
3008 return ((page
>= pageCount
) ? kIOReturnSuccess
: kIOReturnVMError
);
3011 IOReturn
IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection
)
3013 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3014 IOReturn error
= kIOReturnSuccess
;
3016 upl_page_info_array_t pageInfo
;
3018 vm_tag_t tag
= VM_KERN_MEMORY_NONE
;
3020 assert(kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
);
3022 if ((kIODirectionOutIn
& forDirection
) == kIODirectionNone
)
3023 forDirection
= (IODirection
) (forDirection
| getDirection());
3025 dataP
= getDataP(_memoryEntries
);
3026 upl_control_flags_t uplFlags
; // This Mem Desc's default flags for upl creation
3027 switch (kIODirectionOutIn
& forDirection
)
3029 case kIODirectionOut
:
3030 // Pages do not need to be marked as dirty on commit
3031 uplFlags
= UPL_COPYOUT_FROM
;
3032 dataP
->fDMAAccess
= kIODMAMapReadAccess
;
3035 case kIODirectionIn
:
3036 dataP
->fDMAAccess
= kIODMAMapWriteAccess
;
3037 uplFlags
= 0; // i.e. ~UPL_COPYOUT_FROM
3041 dataP
->fDMAAccess
= kIODMAMapReadAccess
| kIODMAMapWriteAccess
;
3042 uplFlags
= 0; // i.e. ~UPL_COPYOUT_FROM
3048 if ((kIOMemoryPreparedReadOnly
& _flags
) && !(UPL_COPYOUT_FROM
& uplFlags
))
3050 OSReportWithBacktrace("IOMemoryDescriptor 0x%lx prepared read only", VM_KERNEL_ADDRPERM(this));
3051 error
= kIOReturnNotWritable
;
3058 mapper
= dataP
->fMapper
;
3059 dataP
->fMappedBaseValid
= dataP
->fMappedBase
= 0;
3061 uplFlags
|= UPL_SET_IO_WIRE
| UPL_SET_LITE
;
3063 if (VM_KERN_MEMORY_NONE
== tag
) tag
= IOMemoryTag(kernel_map
);
3065 if (kIODirectionPrepareToPhys32
& forDirection
)
3067 if (!mapper
) uplFlags
|= UPL_NEED_32BIT_ADDR
;
3068 if (dataP
->fDMAMapNumAddressBits
> 32) dataP
->fDMAMapNumAddressBits
= 32;
3070 if (kIODirectionPrepareNoFault
& forDirection
) uplFlags
|= UPL_REQUEST_NO_FAULT
;
3071 if (kIODirectionPrepareNoZeroFill
& forDirection
) uplFlags
|= UPL_NOZEROFILLIO
;
3072 if (kIODirectionPrepareNonCoherent
& forDirection
) uplFlags
|= UPL_REQUEST_FORCE_COHERENCY
;
3076 // Note that appendBytes(NULL) zeros the data up to the desired length
3077 // and the length parameter is an unsigned int
3078 size_t uplPageSize
= dataP
->fPageCnt
* sizeof(upl_page_info_t
);
3079 if (uplPageSize
> ((unsigned int)uplPageSize
)) return (kIOReturnNoMemory
);
3080 if (!_memoryEntries
->appendBytes(0, uplPageSize
)) return (kIOReturnNoMemory
);
3083 // Find the appropriate vm_map for the given task
3085 if (_task
== kernel_task
&& (kIOMemoryBufferPageable
& _flags
)) curMap
= 0;
3086 else curMap
= get_task_map(_task
);
3088 // Iterate over the vector of virtual ranges
3089 Ranges vec
= _ranges
;
3090 unsigned int pageIndex
= 0;
3091 IOByteCount mdOffset
= 0;
3092 ppnum_t highestPage
= 0;
3094 IOMemoryEntry
* memRefEntry
= 0;
3095 if (_memRef
) memRefEntry
= &_memRef
->entries
[0];
3097 for (UInt range
= 0; range
< _rangesCount
; range
++) {
3099 mach_vm_address_t startPage
, startPageOffset
;
3100 mach_vm_size_t numBytes
;
3101 ppnum_t highPage
= 0;
3103 // Get the startPage address and length of vec[range]
3104 getAddrLenForInd(startPage
, numBytes
, type
, vec
, range
);
3105 startPageOffset
= startPage
& PAGE_MASK
;
3106 iopl
.fPageOffset
= startPageOffset
;
3107 numBytes
+= startPageOffset
;
3108 startPage
= trunc_page_64(startPage
);
3111 iopl
.fMappedPage
= mapBase
+ pageIndex
;
3113 iopl
.fMappedPage
= 0;
3115 // Iterate over the current range, creating UPLs
3117 vm_address_t kernelStart
= (vm_address_t
) startPage
;
3119 if (curMap
) theMap
= curMap
;
3126 assert(_task
== kernel_task
);
3127 theMap
= IOPageableMapForAddress(kernelStart
);
3130 // ioplFlags is an in/out parameter
3131 upl_control_flags_t ioplFlags
= uplFlags
;
3132 dataP
= getDataP(_memoryEntries
);
3133 pageInfo
= getPageList(dataP
);
3134 upl_page_list_ptr_t baseInfo
= &pageInfo
[pageIndex
];
3136 mach_vm_size_t _ioplSize
= round_page(numBytes
);
3137 upl_size_t ioplSize
= (_ioplSize
<= MAX_UPL_SIZE_BYTES
) ? _ioplSize
: MAX_UPL_SIZE_BYTES
;
3138 unsigned int numPageInfo
= atop_32(ioplSize
);
3140 if ((theMap
== kernel_map
)
3141 && (kernelStart
>= io_kernel_static_start
)
3142 && (kernelStart
< io_kernel_static_end
)) {
3143 error
= io_get_kernel_static_upl(theMap
,
3152 memory_object_offset_t entryOffset
;
3154 entryOffset
= mdOffset
;
3155 entryOffset
= (entryOffset
- iopl
.fPageOffset
- memRefEntry
->offset
);
3156 if (entryOffset
>= memRefEntry
->size
) {
3158 if (memRefEntry
>= &_memRef
->entries
[_memRef
->count
]) panic("memRefEntry");
3161 if (ioplSize
> (memRefEntry
->size
- entryOffset
)) ioplSize
= (memRefEntry
->size
- entryOffset
);
3162 error
= memory_object_iopl_request(memRefEntry
->entry
,
3173 error
= vm_map_create_upl(theMap
,
3175 (upl_size_t
*)&ioplSize
,
3183 if (error
!= KERN_SUCCESS
) goto abortExit
;
3188 highPage
= upl_get_highest_page(iopl
.fIOPL
);
3189 if (highPage
> highestPage
)
3190 highestPage
= highPage
;
3192 if (baseInfo
->device
) {
3194 iopl
.fFlags
= kIOPLOnDevice
;
3200 iopl
.fIOMDOffset
= mdOffset
;
3201 iopl
.fPageInfo
= pageIndex
;
3202 if (mapper
&& pageIndex
&& (page_mask
& (mdOffset
+ startPageOffset
))) dataP
->fDiscontig
= true;
3204 if (!_memoryEntries
->appendBytes(&iopl
, sizeof(iopl
))) {
3205 // Clean up partial created and unsaved iopl
3207 upl_abort(iopl
.fIOPL
, 0);
3208 upl_deallocate(iopl
.fIOPL
);
3214 // Check for a multiple iopl's in one virtual range
3215 pageIndex
+= numPageInfo
;
3216 mdOffset
-= iopl
.fPageOffset
;
3217 if (ioplSize
< numBytes
) {
3218 numBytes
-= ioplSize
;
3219 startPage
+= ioplSize
;
3220 mdOffset
+= ioplSize
;
3221 iopl
.fPageOffset
= 0;
3222 if (mapper
) iopl
.fMappedPage
= mapBase
+ pageIndex
;
3225 mdOffset
+= numBytes
;
3231 _highestPage
= highestPage
;
3233 if (UPL_COPYOUT_FROM
& uplFlags
) _flags
|= kIOMemoryPreparedReadOnly
;
3237 if (!(_flags
& kIOMemoryAutoPrepare
) && (kIOReturnSuccess
== error
))
3239 dataP
= getDataP(_memoryEntries
);
3240 if (!dataP
->fWireTracking
.link
.next
)
3242 IOTrackingAdd(gIOWireTracking
, &dataP
->fWireTracking
, ptoa(_pages
), false, tag
);
3245 #endif /* IOTRACKING */
3251 dataP
= getDataP(_memoryEntries
);
3252 UInt done
= getNumIOPL(_memoryEntries
, dataP
);
3253 ioPLBlock
*ioplList
= getIOPLList(dataP
);
3255 for (UInt range
= 0; range
< done
; range
++)
3257 if (ioplList
[range
].fIOPL
) {
3258 upl_abort(ioplList
[range
].fIOPL
, 0);
3259 upl_deallocate(ioplList
[range
].fIOPL
);
3262 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
3265 if (error
== KERN_FAILURE
)
3266 error
= kIOReturnCannotWire
;
3267 else if (error
== KERN_MEMORY_ERROR
)
3268 error
= kIOReturnNoResources
;
3273 bool IOGeneralMemoryDescriptor::initMemoryEntries(size_t size
, IOMapper
* mapper
)
3276 unsigned dataSize
= size
;
3278 if (!_memoryEntries
) {
3279 _memoryEntries
= OSData::withCapacity(dataSize
);
3280 if (!_memoryEntries
)
3283 else if (!_memoryEntries
->initWithCapacity(dataSize
))
3286 _memoryEntries
->appendBytes(0, computeDataSize(0, 0));
3287 dataP
= getDataP(_memoryEntries
);
3289 if (mapper
== kIOMapperWaitSystem
) {
3290 IOMapper::checkForSystemMapper();
3291 mapper
= IOMapper::gSystem
;
3293 dataP
->fMapper
= mapper
;
3294 dataP
->fPageCnt
= 0;
3295 dataP
->fMappedBase
= 0;
3296 dataP
->fDMAMapNumAddressBits
= 64;
3297 dataP
->fDMAMapAlignment
= 0;
3298 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
3299 dataP
->fDiscontig
= false;
3300 dataP
->fCompletionError
= false;
3301 dataP
->fMappedBaseValid
= false;
3306 IOReturn
IOMemoryDescriptor::dmaMap(
3308 IODMACommand
* command
,
3309 const IODMAMapSpecification
* mapSpec
,
3312 uint64_t * mapAddress
,
3313 uint64_t * mapLength
)
3316 uint32_t mapOptions
;
3319 mapOptions
|= kIODMAMapReadAccess
;
3320 if (!(kIOMemoryPreparedReadOnly
& _flags
)) mapOptions
|= kIODMAMapWriteAccess
;
3322 err
= mapper
->iovmMapMemory(this, offset
, length
, mapOptions
,
3323 mapSpec
, command
, NULL
, mapAddress
, mapLength
);
3325 if (kIOReturnSuccess
== err
) dmaMapRecord(mapper
, command
, *mapLength
);
3330 void IOMemoryDescriptor::dmaMapRecord(
3332 IODMACommand
* command
,
3335 kern_allocation_name_t alloc
;
3338 if ((alloc
= mapper
->fAllocName
) /* && mapper != IOMapper::gSystem */)
3340 kern_allocation_update_size(mapper
->fAllocName
, mapLength
);
3343 if (!command
) return;
3344 prior
= OSAddAtomic16(1, &_dmaReferences
);
3347 if (alloc
&& (VM_KERN_MEMORY_NONE
!= _kernelTag
))
3350 mapLength
= _length
;
3351 kern_allocation_update_subtotal(alloc
, _kernelTag
, mapLength
);
3353 else _mapName
= NULL
;
3357 IOReturn
IOMemoryDescriptor::dmaUnmap(
3359 IODMACommand
* command
,
3361 uint64_t mapAddress
,
3365 kern_allocation_name_t alloc
;
3366 kern_allocation_name_t mapName
;
3374 if (_dmaReferences
) prior
= OSAddAtomic16(-1, &_dmaReferences
);
3375 else panic("_dmaReferences underflow");
3378 if (!mapLength
) return (kIOReturnSuccess
);
3380 ret
= mapper
->iovmUnmapMemory(this, command
, mapAddress
, mapLength
);
3382 if ((alloc
= mapper
->fAllocName
))
3384 kern_allocation_update_size(alloc
, -mapLength
);
3385 if ((1 == prior
) && mapName
&& (VM_KERN_MEMORY_NONE
!= _kernelTag
))
3387 mapLength
= _length
;
3388 kern_allocation_update_subtotal(mapName
, _kernelTag
, -mapLength
);
3395 IOReturn
IOGeneralMemoryDescriptor::dmaMap(
3397 IODMACommand
* command
,
3398 const IODMAMapSpecification
* mapSpec
,
3401 uint64_t * mapAddress
,
3402 uint64_t * mapLength
)
3404 IOReturn err
= kIOReturnSuccess
;
3406 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3409 if (kIOMemoryHostOnly
& _flags
) return (kIOReturnSuccess
);
3410 if (kIOMemoryRemote
& _flags
) return (kIOReturnNotAttached
);
3412 if ((type
== kIOMemoryTypePhysical
) || (type
== kIOMemoryTypePhysical64
)
3413 || offset
|| (length
!= _length
))
3415 err
= super::dmaMap(mapper
, command
, mapSpec
, offset
, length
, mapAddress
, mapLength
);
3417 else if (_memoryEntries
&& _pages
&& (dataP
= getDataP(_memoryEntries
)))
3419 const ioPLBlock
* ioplList
= getIOPLList(dataP
);
3420 upl_page_info_t
* pageList
;
3421 uint32_t mapOptions
= 0;
3423 IODMAMapSpecification mapSpec
;
3424 bzero(&mapSpec
, sizeof(mapSpec
));
3425 mapSpec
.numAddressBits
= dataP
->fDMAMapNumAddressBits
;
3426 mapSpec
.alignment
= dataP
->fDMAMapAlignment
;
3428 // For external UPLs the fPageInfo field points directly to
3429 // the upl's upl_page_info_t array.
3430 if (ioplList
->fFlags
& kIOPLExternUPL
)
3432 pageList
= (upl_page_info_t
*) ioplList
->fPageInfo
;
3433 mapOptions
|= kIODMAMapPagingPath
;
3435 else pageList
= getPageList(dataP
);
3437 if ((_length
== ptoa_64(_pages
)) && !(page_mask
& ioplList
->fPageOffset
))
3439 mapOptions
|= kIODMAMapPageListFullyOccupied
;
3442 assert(dataP
->fDMAAccess
);
3443 mapOptions
|= dataP
->fDMAAccess
;
3445 // Check for direct device non-paged memory
3446 if (ioplList
->fFlags
& kIOPLOnDevice
) mapOptions
|= kIODMAMapPhysicallyContiguous
;
3448 IODMAMapPageList dmaPageList
=
3450 .pageOffset
= (uint32_t)(ioplList
->fPageOffset
& page_mask
),
3451 .pageListCount
= _pages
,
3452 .pageList
= &pageList
[0]
3454 err
= mapper
->iovmMapMemory(this, offset
, length
, mapOptions
, &mapSpec
,
3455 command
, &dmaPageList
, mapAddress
, mapLength
);
3457 if (kIOReturnSuccess
== err
) dmaMapRecord(mapper
, command
, *mapLength
);
3466 * Prepare the memory for an I/O transfer. This involves paging in
3467 * the memory, if necessary, and wiring it down for the duration of
3468 * the transfer. The complete() method completes the processing of
3469 * the memory after the I/O transfer finishes. This method needn't
3470 * called for non-pageable memory.
3473 IOReturn
IOGeneralMemoryDescriptor::prepare(IODirection forDirection
)
3475 IOReturn error
= kIOReturnSuccess
;
3476 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3478 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
3479 return kIOReturnSuccess
;
3481 assert (!(kIOMemoryRemote
& _flags
));
3482 if (kIOMemoryRemote
& _flags
) return (kIOReturnNotAttached
);
3484 if (_prepareLock
) IOLockLock(_prepareLock
);
3486 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
)
3488 error
= wireVirtual(forDirection
);
3491 if (kIOReturnSuccess
== error
)
3493 if (1 == ++_wireCount
)
3495 if (kIOMemoryClearEncrypt
& _flags
)
3497 performOperation(kIOMemoryClearEncrypted
, 0, _length
);
3502 if (_prepareLock
) IOLockUnlock(_prepareLock
);
3510 * Complete processing of the memory after an I/O transfer finishes.
3511 * This method should not be called unless a prepare was previously
3512 * issued; the prepare() and complete() must occur in pairs, before
3513 * before and after an I/O transfer involving pageable memory.
3516 IOReturn
IOGeneralMemoryDescriptor::complete(IODirection forDirection
)
3518 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3521 if ((kIOMemoryTypePhysical
== type
) || (kIOMemoryTypePhysical64
== type
))
3522 return kIOReturnSuccess
;
3524 assert (!(kIOMemoryRemote
& _flags
));
3525 if (kIOMemoryRemote
& _flags
) return (kIOReturnNotAttached
);
3527 if (_prepareLock
) IOLockLock(_prepareLock
);
3531 if (!_wireCount
) break;
3532 dataP
= getDataP(_memoryEntries
);
3535 if (kIODirectionCompleteWithError
& forDirection
) dataP
->fCompletionError
= true;
3537 if ((kIOMemoryClearEncrypt
& _flags
) && (1 == _wireCount
))
3539 performOperation(kIOMemorySetEncrypted
, 0, _length
);
3543 if (!_wireCount
|| (kIODirectionCompleteWithDataValid
& forDirection
))
3545 ioPLBlock
*ioplList
= getIOPLList(dataP
);
3546 UInt ind
, count
= getNumIOPL(_memoryEntries
, dataP
);
3550 // kIODirectionCompleteWithDataValid & forDirection
3551 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
)
3554 tag
= getVMTag(kernel_map
);
3555 for (ind
= 0; ind
< count
; ind
++)
3557 if (ioplList
[ind
].fIOPL
) iopl_valid_data(ioplList
[ind
].fIOPL
, tag
);
3563 if (_dmaReferences
) panic("complete() while dma active");
3565 if (dataP
->fMappedBaseValid
) {
3566 dmaUnmap(dataP
->fMapper
, NULL
, 0, dataP
->fMappedBase
, dataP
->fMappedLength
);
3567 dataP
->fMappedBaseValid
= dataP
->fMappedBase
= 0;
3570 if (dataP
->fWireTracking
.link
.next
) IOTrackingRemove(gIOWireTracking
, &dataP
->fWireTracking
, ptoa(_pages
));
3571 #endif /* IOTRACKING */
3572 // Only complete iopls that we created which are for TypeVirtual
3573 if (kIOMemoryTypeVirtual
== type
|| kIOMemoryTypeVirtual64
== type
|| kIOMemoryTypeUIO
== type
)
3575 for (ind
= 0; ind
< count
; ind
++)
3576 if (ioplList
[ind
].fIOPL
) {
3577 if (dataP
->fCompletionError
)
3578 upl_abort(ioplList
[ind
].fIOPL
, 0 /*!UPL_ABORT_DUMP_PAGES*/);
3580 upl_commit(ioplList
[ind
].fIOPL
, 0, 0);
3581 upl_deallocate(ioplList
[ind
].fIOPL
);
3583 } else if (kIOMemoryTypeUPL
== type
) {
3584 upl_set_referenced(ioplList
[0].fIOPL
, false);
3587 (void) _memoryEntries
->initWithBytes(dataP
, computeDataSize(0, 0)); // == setLength()
3589 dataP
->fPreparationID
= kIOPreparationIDUnprepared
;
3590 _flags
&= ~kIOMemoryPreparedReadOnly
;
3596 if (_prepareLock
) IOLockUnlock(_prepareLock
);
3598 return kIOReturnSuccess
;
3601 IOReturn
IOGeneralMemoryDescriptor::doMap(
3602 vm_map_t __addressMap
,
3603 IOVirtualAddress
* __address
,
3604 IOOptionBits options
,
3605 IOByteCount __offset
,
3606 IOByteCount __length
)
3609 if (!(kIOMap64Bit
& options
)) panic("IOGeneralMemoryDescriptor::doMap !64bit");
3610 #endif /* !__LP64__ */
3614 IOMemoryMap
* mapping
= (IOMemoryMap
*) *__address
;
3615 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
3616 mach_vm_size_t length
= mapping
->fLength
;
3618 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
3619 Ranges vec
= _ranges
;
3621 mach_vm_address_t range0Addr
= 0;
3622 mach_vm_size_t range0Len
= 0;
3624 if ((offset
>= _length
) || ((offset
+ length
) > _length
))
3625 return( kIOReturnBadArgument
);
3627 assert (!(kIOMemoryRemote
& _flags
));
3628 if (kIOMemoryRemote
& _flags
) return (0);
3631 getAddrLenForInd(range0Addr
, range0Len
, type
, vec
, 0);
3633 // mapping source == dest? (could be much better)
3635 && (mapping
->fAddressTask
== _task
)
3636 && (mapping
->fAddressMap
== get_task_map(_task
))
3637 && (options
& kIOMapAnywhere
)
3638 && (1 == _rangesCount
)
3641 && (length
<= range0Len
))
3643 mapping
->fAddress
= range0Addr
;
3644 mapping
->fOptions
|= kIOMapStatic
;
3646 return( kIOReturnSuccess
);
3651 IOOptionBits createOptions
= 0;
3652 if (!(kIOMapReadOnly
& options
))
3654 createOptions
|= kIOMemoryReferenceWrite
;
3655 #if DEVELOPMENT || DEBUG
3656 if (kIODirectionOut
== (kIODirectionOutIn
& _flags
))
3658 OSReportWithBacktrace("warning: creating writable mapping from IOMemoryDescriptor(kIODirectionOut) - use kIOMapReadOnly or change direction");
3662 err
= memoryReferenceCreate(createOptions
, &_memRef
);
3663 if (kIOReturnSuccess
!= err
) return (err
);
3666 memory_object_t pager
;
3667 pager
= (memory_object_t
) (reserved
? reserved
->dp
.devicePager
: 0);
3669 // <upl_transpose //
3670 if ((kIOMapReference
|kIOMapUnique
) == ((kIOMapReference
|kIOMapUnique
) & options
))
3676 upl_control_flags_t flags
;
3677 unsigned int lock_count
;
3679 if (!_memRef
|| (1 != _memRef
->count
))
3681 err
= kIOReturnNotReadable
;
3685 size
= round_page(mapping
->fLength
);
3686 flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
3687 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
3689 if (KERN_SUCCESS
!= memory_object_iopl_request(_memRef
->entries
[0].entry
, 0, &size
, &redirUPL2
,
3691 &flags
, getVMTag(kernel_map
)))
3694 for (lock_count
= 0;
3695 IORecursiveLockHaveLock(gIOMemoryLock
);
3699 err
= upl_transpose(redirUPL2
, mapping
->fRedirUPL
);
3706 if (kIOReturnSuccess
!= err
)
3708 IOLog("upl_transpose(%x)\n", err
);
3709 err
= kIOReturnSuccess
;
3714 upl_commit(redirUPL2
, NULL
, 0);
3715 upl_deallocate(redirUPL2
);
3719 // swap the memEntries since they now refer to different vm_objects
3720 IOMemoryReference
* me
= _memRef
;
3721 _memRef
= mapping
->fMemory
->_memRef
;
3722 mapping
->fMemory
->_memRef
= me
;
3725 err
= populateDevicePager( pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
3729 // upl_transpose> //
3732 err
= memoryReferenceMap(_memRef
, mapping
->fAddressMap
, offset
, length
, options
, &mapping
->fAddress
);
3734 if ((err
== KERN_SUCCESS
) && ((kIOTracking
& gIOKitDebug
) || _task
))
3736 // only dram maps in the default on developement case
3737 IOTrackingAddUser(gIOMapTracking
, &mapping
->fTracking
, mapping
->fLength
);
3739 #endif /* IOTRACKING */
3740 if ((err
== KERN_SUCCESS
) && pager
)
3742 err
= populateDevicePager(pager
, mapping
->fAddressMap
, mapping
->fAddress
, offset
, length
, options
);
3744 if (err
!= KERN_SUCCESS
) doUnmap(mapping
->fAddressMap
, (IOVirtualAddress
) mapping
, 0);
3745 else if (kIOMapDefaultCache
== (options
& kIOMapCacheMask
))
3747 mapping
->fOptions
|= ((_flags
& kIOMemoryBufferCacheMask
) >> kIOMemoryBufferCacheShift
);
3757 IOMemoryMapTracking(IOTrackingUser
* tracking
, task_t
* task
,
3758 mach_vm_address_t
* address
, mach_vm_size_t
* size
)
3760 #define iomap_offsetof(type, field) ((size_t)(&((type *)0)->field))
3762 IOMemoryMap
* map
= (typeof(map
)) (((uintptr_t) tracking
) - iomap_offsetof(IOMemoryMap
, fTracking
));
3764 if (!map
->fAddressMap
|| (map
->fAddressMap
!= get_task_map(map
->fAddressTask
))) return (kIOReturnNotReady
);
3766 *task
= map
->fAddressTask
;
3767 *address
= map
->fAddress
;
3768 *size
= map
->fLength
;
3770 return (kIOReturnSuccess
);
3772 #endif /* IOTRACKING */
3774 IOReturn
IOGeneralMemoryDescriptor::doUnmap(
3775 vm_map_t addressMap
,
3776 IOVirtualAddress __address
,
3777 IOByteCount __length
)
3779 return (super::doUnmap(addressMap
, __address
, __length
));
3782 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3785 #define super OSObject
3787 OSDefineMetaClassAndStructors( IOMemoryMap
, OSObject
)
3789 OSMetaClassDefineReservedUnused(IOMemoryMap
, 0);
3790 OSMetaClassDefineReservedUnused(IOMemoryMap
, 1);
3791 OSMetaClassDefineReservedUnused(IOMemoryMap
, 2);
3792 OSMetaClassDefineReservedUnused(IOMemoryMap
, 3);
3793 OSMetaClassDefineReservedUnused(IOMemoryMap
, 4);
3794 OSMetaClassDefineReservedUnused(IOMemoryMap
, 5);
3795 OSMetaClassDefineReservedUnused(IOMemoryMap
, 6);
3796 OSMetaClassDefineReservedUnused(IOMemoryMap
, 7);
3798 /* ex-inline function implementation */
3799 IOPhysicalAddress
IOMemoryMap::getPhysicalAddress()
3800 { return( getPhysicalSegment( 0, 0 )); }
3802 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3804 bool IOMemoryMap::init(
3806 mach_vm_address_t toAddress
,
3807 IOOptionBits _options
,
3808 mach_vm_size_t _offset
,
3809 mach_vm_size_t _length
)
3817 fAddressMap
= get_task_map(intoTask
);
3820 vm_map_reference(fAddressMap
);
3822 fAddressTask
= intoTask
;
3823 fOptions
= _options
;
3826 fAddress
= toAddress
;
3831 bool IOMemoryMap::setMemoryDescriptor(IOMemoryDescriptor
* _memory
, mach_vm_size_t _offset
)
3838 if( (_offset
+ fLength
) > _memory
->getLength())
3846 if (fMemory
!= _memory
)
3847 fMemory
->removeMapping(this);
3855 IOReturn
IOMemoryDescriptor::doMap(
3856 vm_map_t __addressMap
,
3857 IOVirtualAddress
* __address
,
3858 IOOptionBits options
,
3859 IOByteCount __offset
,
3860 IOByteCount __length
)
3862 return (kIOReturnUnsupported
);
3865 IOReturn
IOMemoryDescriptor::handleFault(
3867 mach_vm_size_t sourceOffset
,
3868 mach_vm_size_t length
)
3870 if( kIOMemoryRedirected
& _flags
)
3873 IOLog("sleep mem redirect %p, %qx\n", this, sourceOffset
);
3877 } while( kIOMemoryRedirected
& _flags
);
3879 return (kIOReturnSuccess
);
3882 IOReturn
IOMemoryDescriptor::populateDevicePager(
3884 vm_map_t addressMap
,
3885 mach_vm_address_t address
,
3886 mach_vm_size_t sourceOffset
,
3887 mach_vm_size_t length
,
3888 IOOptionBits options
)
3890 IOReturn err
= kIOReturnSuccess
;
3891 memory_object_t pager
= (memory_object_t
) _pager
;
3892 mach_vm_size_t size
;
3893 mach_vm_size_t bytes
;
3894 mach_vm_size_t page
;
3895 mach_vm_size_t pageOffset
;
3896 mach_vm_size_t pagerOffset
;
3897 IOPhysicalLength segLen
, chunk
;
3901 type
= _flags
& kIOMemoryTypeMask
;
3903 if (reserved
->dp
.pagerContig
)
3909 physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
);
3911 pageOffset
= physAddr
- trunc_page_64( physAddr
);
3912 pagerOffset
= sourceOffset
;
3914 size
= length
+ pageOffset
;
3915 physAddr
-= pageOffset
;
3917 segLen
+= pageOffset
;
3921 // in the middle of the loop only map whole pages
3922 if( segLen
>= bytes
) segLen
= bytes
;
3923 else if (segLen
!= trunc_page(segLen
)) err
= kIOReturnVMError
;
3924 if (physAddr
!= trunc_page_64(physAddr
)) err
= kIOReturnBadArgument
;
3926 if (kIOReturnSuccess
!= err
) break;
3928 #if DEBUG || DEVELOPMENT
3929 if ((kIOMemoryTypeUPL
!= type
)
3930 && pmap_has_managed_page(atop_64(physAddr
), atop_64(physAddr
+ segLen
- 1)))
3932 OSReportWithBacktrace("IOMemoryDescriptor physical with managed page 0x%qx:0x%qx", physAddr
, segLen
);
3934 #endif /* DEBUG || DEVELOPMENT */
3936 chunk
= (reserved
->dp
.pagerContig
? round_page(segLen
) : page_size
);
3938 (page
< segLen
) && (KERN_SUCCESS
== err
);
3941 err
= device_pager_populate_object(pager
, pagerOffset
,
3942 (ppnum_t
)(atop_64(physAddr
+ page
)), chunk
);
3943 pagerOffset
+= chunk
;
3946 assert (KERN_SUCCESS
== err
);
3949 // This call to vm_fault causes an early pmap level resolution
3950 // of the mappings created above for kernel mappings, since
3951 // faulting in later can't take place from interrupt level.
3952 if ((addressMap
== kernel_map
) && !(kIOMemoryRedirected
& _flags
))
3954 err
= vm_fault(addressMap
,
3955 (vm_map_offset_t
)trunc_page_64(address
),
3956 options
& kIOMapReadOnly
? VM_PROT_READ
: VM_PROT_READ
|VM_PROT_WRITE
,
3957 FALSE
, VM_KERN_MEMORY_NONE
,
3959 (vm_map_offset_t
)0);
3961 if (KERN_SUCCESS
!= err
) break;
3964 sourceOffset
+= segLen
- pageOffset
;
3969 while (bytes
&& (physAddr
= getPhysicalSegment( sourceOffset
, &segLen
, kIOMemoryMapperNone
)));
3972 err
= kIOReturnBadArgument
;
3977 IOReturn
IOMemoryDescriptor::doUnmap(
3978 vm_map_t addressMap
,
3979 IOVirtualAddress __address
,
3980 IOByteCount __length
)
3983 IOMemoryMap
* mapping
;
3984 mach_vm_address_t address
;
3985 mach_vm_size_t length
;
3987 if (__length
) panic("doUnmap");
3989 mapping
= (IOMemoryMap
*) __address
;
3990 addressMap
= mapping
->fAddressMap
;
3991 address
= mapping
->fAddress
;
3992 length
= mapping
->fLength
;
3994 if (kIOMapOverwrite
& mapping
->fOptions
) err
= KERN_SUCCESS
;
3997 if ((addressMap
== kernel_map
) && (kIOMemoryBufferPageable
& _flags
))
3998 addressMap
= IOPageableMapForAddress( address
);
4000 if( kIOLogMapping
& gIOKitDebug
) IOLog("IOMemoryDescriptor::doUnmap map %p, 0x%qx:0x%qx\n",
4001 addressMap
, address
, length
);
4003 err
= mach_vm_deallocate( addressMap
, address
, length
);
4007 IOTrackingRemoveUser(gIOMapTracking
, &mapping
->fTracking
);
4008 #endif /* IOTRACKING */
4013 IOReturn
IOMemoryDescriptor::redirect( task_t safeTask
, bool doRedirect
)
4015 IOReturn err
= kIOReturnSuccess
;
4016 IOMemoryMap
* mapping
= 0;
4022 _flags
|= kIOMemoryRedirected
;
4024 _flags
&= ~kIOMemoryRedirected
;
4027 if( (iter
= OSCollectionIterator::withCollection( _mappings
))) {
4029 memory_object_t pager
;
4032 pager
= (memory_object_t
) reserved
->dp
.devicePager
;
4034 pager
= MACH_PORT_NULL
;
4036 while( (mapping
= (IOMemoryMap
*) iter
->getNextObject()))
4038 mapping
->redirect( safeTask
, doRedirect
);
4039 if (!doRedirect
&& !safeTask
&& pager
&& (kernel_map
== mapping
->fAddressMap
))
4041 err
= populateDevicePager(pager
, mapping
->fAddressMap
, mapping
->fAddress
, mapping
->fOffset
, mapping
->fLength
, kIOMapDefaultCache
);
4057 // temporary binary compatibility
4058 IOSubMemoryDescriptor
* subMem
;
4059 if( (subMem
= OSDynamicCast( IOSubMemoryDescriptor
, this)))
4060 err
= subMem
->redirect( safeTask
, doRedirect
);
4062 err
= kIOReturnSuccess
;
4063 #endif /* !__LP64__ */
4068 IOReturn
IOMemoryMap::redirect( task_t safeTask
, bool doRedirect
)
4070 IOReturn err
= kIOReturnSuccess
;
4073 // err = ((IOMemoryMap *)superMap)->redirect( safeTask, doRedirect );
4085 if ((!safeTask
|| (get_task_map(safeTask
) != fAddressMap
))
4086 && (0 == (fOptions
& kIOMapStatic
)))
4088 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
4089 err
= kIOReturnSuccess
;
4091 IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect
, this, fAddress
, fLength
, fAddressMap
);
4094 else if (kIOMapWriteCombineCache
== (fOptions
& kIOMapCacheMask
))
4096 IOOptionBits newMode
;
4097 newMode
= (fOptions
& ~kIOMapCacheMask
) | (doRedirect
? kIOMapInhibitCache
: kIOMapWriteCombineCache
);
4098 IOProtectCacheMode(fAddressMap
, fAddress
, fLength
, newMode
);
4105 if ((((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
4106 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
4108 && (doRedirect
!= (0 != (fMemory
->_flags
& kIOMemoryRedirected
))))
4109 fMemory
->redirect(safeTask
, doRedirect
);
4114 IOReturn
IOMemoryMap::unmap( void )
4120 if( fAddress
&& fAddressMap
&& (0 == fSuperMap
) && fMemory
4121 && (0 == (kIOMapStatic
& fOptions
))) {
4123 err
= fMemory
->doUnmap(fAddressMap
, (IOVirtualAddress
) this, 0);
4126 err
= kIOReturnSuccess
;
4130 vm_map_deallocate(fAddressMap
);
4141 void IOMemoryMap::taskDied( void )
4144 if (fUserClientUnmap
) unmap();
4146 else IOTrackingRemoveUser(gIOMapTracking
, &fTracking
);
4147 #endif /* IOTRACKING */
4150 vm_map_deallocate(fAddressMap
);
4158 IOReturn
IOMemoryMap::userClientUnmap( void )
4160 fUserClientUnmap
= true;
4161 return (kIOReturnSuccess
);
4164 // Overload the release mechanism. All mappings must be a member
4165 // of a memory descriptors _mappings set. This means that we
4166 // always have 2 references on a mapping. When either of these mappings
4167 // are released we need to free ourselves.
4168 void IOMemoryMap::taggedRelease(const void *tag
) const
4171 super::taggedRelease(tag
, 2);
4175 void IOMemoryMap::free()
4182 fMemory
->removeMapping(this);
4187 if (fOwner
&& (fOwner
!= fMemory
))
4190 fOwner
->removeMapping(this);
4195 fSuperMap
->release();
4198 upl_commit(fRedirUPL
, NULL
, 0);
4199 upl_deallocate(fRedirUPL
);
4205 IOByteCount
IOMemoryMap::getLength()
4210 IOVirtualAddress
IOMemoryMap::getVirtualAddress()
4214 fSuperMap
->getVirtualAddress();
4215 else if (fAddressMap
4216 && vm_map_is_64bit(fAddressMap
)
4217 && (sizeof(IOVirtualAddress
) < 8))
4219 OSReportWithBacktrace("IOMemoryMap::getVirtualAddress(0x%qx) called on 64b map; use ::getAddress()", fAddress
);
4221 #endif /* !__LP64__ */
4227 mach_vm_address_t
IOMemoryMap::getAddress()
4232 mach_vm_size_t
IOMemoryMap::getSize()
4236 #endif /* !__LP64__ */
4239 task_t
IOMemoryMap::getAddressTask()
4242 return( fSuperMap
->getAddressTask());
4244 return( fAddressTask
);
4247 IOOptionBits
IOMemoryMap::getMapOptions()
4252 IOMemoryDescriptor
* IOMemoryMap::getMemoryDescriptor()
4257 IOMemoryMap
* IOMemoryMap::copyCompatible(
4258 IOMemoryMap
* newMapping
)
4260 task_t task
= newMapping
->getAddressTask();
4261 mach_vm_address_t toAddress
= newMapping
->fAddress
;
4262 IOOptionBits _options
= newMapping
->fOptions
;
4263 mach_vm_size_t _offset
= newMapping
->fOffset
;
4264 mach_vm_size_t _length
= newMapping
->fLength
;
4266 if( (!task
) || (!fAddressMap
) || (fAddressMap
!= get_task_map(task
)))
4268 if( (fOptions
^ _options
) & kIOMapReadOnly
)
4270 if( (kIOMapDefaultCache
!= (_options
& kIOMapCacheMask
))
4271 && ((fOptions
^ _options
) & kIOMapCacheMask
))
4274 if( (0 == (_options
& kIOMapAnywhere
)) && (fAddress
!= toAddress
))
4277 if( _offset
< fOffset
)
4282 if( (_offset
+ _length
) > fLength
)
4286 if( (fLength
== _length
) && (!_offset
))
4292 newMapping
->fSuperMap
= this;
4293 newMapping
->fOffset
= fOffset
+ _offset
;
4294 newMapping
->fAddress
= fAddress
+ _offset
;
4297 return( newMapping
);
4300 IOReturn
IOMemoryMap::wireRange(
4302 mach_vm_size_t offset
,
4303 mach_vm_size_t length
)
4306 mach_vm_address_t start
= trunc_page_64(fAddress
+ offset
);
4307 mach_vm_address_t end
= round_page_64(fAddress
+ offset
+ length
);
4310 prot
= (kIODirectionOutIn
& options
);
4313 kr
= vm_map_wire_kernel(fAddressMap
, start
, end
, prot
, fMemory
->getVMTag(kernel_map
), FALSE
);
4317 kr
= vm_map_unwire(fAddressMap
, start
, end
, FALSE
);
4326 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
, IOOptionBits _options
)
4327 #else /* !__LP64__ */
4328 IOMemoryMap::getPhysicalSegment( IOByteCount _offset
, IOPhysicalLength
* _length
)
4329 #endif /* !__LP64__ */
4331 IOPhysicalAddress address
;
4335 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
, _options
);
4336 #else /* !__LP64__ */
4337 address
= fMemory
->getPhysicalSegment( fOffset
+ _offset
, _length
);
4338 #endif /* !__LP64__ */
4344 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4347 #define super OSObject
4349 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4351 void IOMemoryDescriptor::initialize( void )
4353 if( 0 == gIOMemoryLock
)
4354 gIOMemoryLock
= IORecursiveLockAlloc();
4356 gIOLastPage
= IOGetLastPageNumber();
4359 void IOMemoryDescriptor::free( void )
4361 if( _mappings
) _mappings
->release();
4365 IODelete(reserved
, IOMemoryDescriptorReserved
, 1);
4371 IOMemoryMap
* IOMemoryDescriptor::setMapping(
4373 IOVirtualAddress mapAddress
,
4374 IOOptionBits options
)
4376 return (createMappingInTask( intoTask
, mapAddress
,
4377 options
| kIOMapStatic
,
4381 IOMemoryMap
* IOMemoryDescriptor::map(
4382 IOOptionBits options
)
4384 return (createMappingInTask( kernel_task
, 0,
4385 options
| kIOMapAnywhere
,
4390 IOMemoryMap
* IOMemoryDescriptor::map(
4392 IOVirtualAddress atAddress
,
4393 IOOptionBits options
,
4395 IOByteCount length
)
4397 if ((!(kIOMapAnywhere
& options
)) && vm_map_is_64bit(get_task_map(intoTask
)))
4399 OSReportWithBacktrace("IOMemoryDescriptor::map() in 64b task, use ::createMappingInTask()");
4403 return (createMappingInTask(intoTask
, atAddress
,
4404 options
, offset
, length
));
4406 #endif /* !__LP64__ */
4408 IOMemoryMap
* IOMemoryDescriptor::createMappingInTask(
4410 mach_vm_address_t atAddress
,
4411 IOOptionBits options
,
4412 mach_vm_size_t offset
,
4413 mach_vm_size_t length
)
4415 IOMemoryMap
* result
;
4416 IOMemoryMap
* mapping
;
4419 length
= getLength();
4421 mapping
= new IOMemoryMap
;
4424 && !mapping
->init( intoTask
, atAddress
,
4425 options
, offset
, length
)) {
4431 result
= makeMapping(this, intoTask
, (IOVirtualAddress
) mapping
, options
| kIOMap64Bit
, 0, 0);
4437 IOLog("createMappingInTask failed desc %p, addr %qx, options %x, offset %qx, length %llx\n",
4438 this, atAddress
, (uint32_t) options
, offset
, length
);
4444 #ifndef __LP64__ // there is only a 64 bit version for LP64
4445 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
4446 IOOptionBits options
,
4449 return (redirect(newBackingMemory
, options
, (mach_vm_size_t
)offset
));
4453 IOReturn
IOMemoryMap::redirect(IOMemoryDescriptor
* newBackingMemory
,
4454 IOOptionBits options
,
4455 mach_vm_size_t offset
)
4457 IOReturn err
= kIOReturnSuccess
;
4458 IOMemoryDescriptor
* physMem
= 0;
4462 if (fAddress
&& fAddressMap
) do
4464 if (((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
4465 || ((fMemory
->_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
4471 if (!fRedirUPL
&& fMemory
->_memRef
&& (1 == fMemory
->_memRef
->count
))
4473 upl_size_t size
= round_page(fLength
);
4474 upl_control_flags_t flags
= UPL_COPYOUT_FROM
| UPL_SET_INTERNAL
4475 | UPL_SET_LITE
| UPL_SET_IO_WIRE
| UPL_BLOCK_ACCESS
;
4476 if (KERN_SUCCESS
!= memory_object_iopl_request(fMemory
->_memRef
->entries
[0].entry
, 0, &size
, &fRedirUPL
,
4478 &flags
, fMemory
->getVMTag(kernel_map
)))
4483 IOUnmapPages( fAddressMap
, fAddress
, fLength
);
4485 physMem
->redirect(0, true);
4489 if (newBackingMemory
)
4491 if (newBackingMemory
!= fMemory
)
4494 if (this != newBackingMemory
->makeMapping(newBackingMemory
, fAddressTask
, (IOVirtualAddress
) this,
4495 options
| kIOMapUnique
| kIOMapReference
| kIOMap64Bit
,
4497 err
= kIOReturnError
;
4501 upl_commit(fRedirUPL
, NULL
, 0);
4502 upl_deallocate(fRedirUPL
);
4505 if ((false) && physMem
)
4506 physMem
->redirect(0, false);
4519 IOMemoryMap
* IOMemoryDescriptor::makeMapping(
4520 IOMemoryDescriptor
* owner
,
4522 IOVirtualAddress __address
,
4523 IOOptionBits options
,
4524 IOByteCount __offset
,
4525 IOByteCount __length
)
4528 if (!(kIOMap64Bit
& options
)) panic("IOMemoryDescriptor::makeMapping !64bit");
4529 #endif /* !__LP64__ */
4531 IOMemoryDescriptor
* mapDesc
= 0;
4532 IOMemoryMap
* result
= 0;
4535 IOMemoryMap
* mapping
= (IOMemoryMap
*) __address
;
4536 mach_vm_size_t offset
= mapping
->fOffset
+ __offset
;
4537 mach_vm_size_t length
= mapping
->fLength
;
4539 mapping
->fOffset
= offset
;
4545 if (kIOMapStatic
& options
)
4548 addMapping(mapping
);
4549 mapping
->setMemoryDescriptor(this, 0);
4553 if (kIOMapUnique
& options
)
4556 IOByteCount physLen
;
4558 // if (owner != this) continue;
4560 if (((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical
)
4561 || ((_flags
& kIOMemoryTypeMask
) == kIOMemoryTypePhysical64
))
4563 phys
= getPhysicalSegment(offset
, &physLen
, kIOMemoryMapperNone
);
4564 if (!phys
|| (physLen
< length
))
4567 mapDesc
= IOMemoryDescriptor::withAddressRange(
4568 phys
, length
, getDirection() | kIOMemoryMapperNone
, NULL
);
4572 mapping
->fOffset
= offset
;
4577 // look for a compatible existing mapping
4578 if( (iter
= OSCollectionIterator::withCollection(_mappings
)))
4580 IOMemoryMap
* lookMapping
;
4581 while ((lookMapping
= (IOMemoryMap
*) iter
->getNextObject()))
4583 if ((result
= lookMapping
->copyCompatible(mapping
)))
4586 result
->setMemoryDescriptor(this, offset
);
4592 if (result
|| (options
& kIOMapReference
))
4594 if (result
!= mapping
)
4609 kr
= mapDesc
->doMap( 0, (IOVirtualAddress
*) &mapping
, options
, 0, 0 );
4610 if (kIOReturnSuccess
== kr
)
4613 mapDesc
->addMapping(result
);
4614 result
->setMemoryDescriptor(mapDesc
, offset
);
4632 void IOMemoryDescriptor::addMapping(
4633 IOMemoryMap
* mapping
)
4638 _mappings
= OSSet::withCapacity(1);
4640 _mappings
->setObject( mapping
);
4644 void IOMemoryDescriptor::removeMapping(
4645 IOMemoryMap
* mapping
)
4648 _mappings
->removeObject( mapping
);
4652 // obsolete initializers
4653 // - initWithOptions is the designated initializer
4655 IOMemoryDescriptor::initWithAddress(void * address
,
4657 IODirection direction
)
4663 IOMemoryDescriptor::initWithAddress(IOVirtualAddress address
,
4665 IODirection direction
,
4672 IOMemoryDescriptor::initWithPhysicalAddress(
4673 IOPhysicalAddress address
,
4675 IODirection direction
)
4681 IOMemoryDescriptor::initWithRanges(
4682 IOVirtualRange
* ranges
,
4684 IODirection direction
,
4692 IOMemoryDescriptor::initWithPhysicalRanges( IOPhysicalRange
* ranges
,
4694 IODirection direction
,
4700 void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset
,
4701 IOByteCount
* lengthOfSegment
)
4705 #endif /* !__LP64__ */
4707 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4709 bool IOGeneralMemoryDescriptor::serialize(OSSerialize
* s
) const
4711 OSSymbol
const *keys
[2] = {0};
4712 OSObject
*values
[2] = {0};
4714 vm_size_t vcopy_size
;
4717 user_addr_t address
;
4720 unsigned int index
, nRanges
;
4721 bool result
= false;
4723 IOOptionBits type
= _flags
& kIOMemoryTypeMask
;
4725 if (s
== NULL
) return false;
4727 array
= OSArray::withCapacity(4);
4728 if (!array
) return (false);
4730 nRanges
= _rangesCount
;
4731 if (os_mul_overflow(sizeof(SerData
), nRanges
, &vcopy_size
)) {
4735 vcopy
= (SerData
*) IOMalloc(vcopy_size
);
4741 keys
[0] = OSSymbol::withCString("address");
4742 keys
[1] = OSSymbol::withCString("length");
4744 // Copy the volatile data so we don't have to allocate memory
4745 // while the lock is held.
4747 if (nRanges
== _rangesCount
) {
4748 Ranges vec
= _ranges
;
4749 for (index
= 0; index
< nRanges
; index
++) {
4750 mach_vm_address_t addr
; mach_vm_size_t len
;
4751 getAddrLenForInd(addr
, len
, type
, vec
, index
);
4752 vcopy
[index
].address
= addr
;
4753 vcopy
[index
].length
= len
;
4756 // The descriptor changed out from under us. Give up.
4763 for (index
= 0; index
< nRanges
; index
++)
4765 user_addr_t addr
= vcopy
[index
].address
;
4766 IOByteCount len
= (IOByteCount
) vcopy
[index
].length
;
4767 values
[0] = OSNumber::withNumber(addr
, sizeof(addr
) * 8);
4768 if (values
[0] == 0) {
4772 values
[1] = OSNumber::withNumber(len
, sizeof(len
) * 8);
4773 if (values
[1] == 0) {
4777 OSDictionary
*dict
= OSDictionary::withObjects((const OSObject
**)values
, (const OSSymbol
**)keys
, 2);
4782 array
->setObject(dict
);
4784 values
[0]->release();
4785 values
[1]->release();
4786 values
[0] = values
[1] = 0;
4789 result
= array
->serialize(s
);
4795 values
[0]->release();
4797 values
[1]->release();
4803 IOFree(vcopy
, vcopy_size
);
4808 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4810 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 0);
4812 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 1);
4813 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 2);
4814 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 3);
4815 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 4);
4816 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 5);
4817 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 6);
4818 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 7);
4819 #else /* !__LP64__ */
4820 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 1);
4821 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 2);
4822 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 3);
4823 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 4);
4824 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 5);
4825 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 6);
4826 OSMetaClassDefineReservedUsed(IOMemoryDescriptor
, 7);
4827 #endif /* !__LP64__ */
4828 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 8);
4829 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 9);
4830 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 10);
4831 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 11);
4832 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 12);
4833 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 13);
4834 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 14);
4835 OSMetaClassDefineReservedUnused(IOMemoryDescriptor
, 15);
4837 /* ex-inline function implementation */
4839 IOMemoryDescriptor::getPhysicalAddress()
4840 { return( getPhysicalSegment( 0, 0 )); }