]> git.saurik.com Git - apple/xnu.git/blob - iokit/Kernel/IOMemoryDescriptor.cpp
xnu-4570.31.3.tar.gz
[apple/xnu.git] / iokit / Kernel / IOMemoryDescriptor.cpp
1 /*
2 * Copyright (c) 1998-2016 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
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.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
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.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29
30 #include <sys/cdefs.h>
31
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>
39
40 #include <IOKit/IOSubMemoryDescriptor.h>
41 #include <IOKit/IOMultiMemoryDescriptor.h>
42
43 #include <IOKit/IOKitDebug.h>
44 #include <libkern/OSDebug.h>
45
46 #include "IOKitKernelInternal.h"
47
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>
54
55 #include <sys/uio.h>
56
57 __BEGIN_DECLS
58 #include <vm/pmap.h>
59 #include <vm/vm_pageout.h>
60 #include <mach/memory_object_types.h>
61 #include <device/device_port.h>
62
63 #include <mach/vm_prot.h>
64 #include <mach/mach_vm.h>
65 #include <vm/vm_fault.h>
66 #include <vm/vm_protos.h>
67
68 extern ppnum_t pmap_find_phys(pmap_t pmap, addr64_t va);
69 extern void ipc_port_release_send(ipc_port_t port);
70
71 // osfmk/device/iokit_rpc.c
72 unsigned int IODefaultCacheBits(addr64_t pa);
73 unsigned int IOTranslateCacheBits(struct phys_entry *pp);
74
75 __END_DECLS
76
77 #define kIOMapperWaitSystem ((IOMapper *) 1)
78
79 static IOMapper * gIOSystemMapper = NULL;
80
81 ppnum_t gIOLastPage;
82
83 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
84
85 OSDefineMetaClassAndAbstractStructors( IOMemoryDescriptor, OSObject )
86
87 #define super IOMemoryDescriptor
88
89 OSDefineMetaClassAndStructors(IOGeneralMemoryDescriptor, IOMemoryDescriptor)
90
91 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
92
93 static IORecursiveLock * gIOMemoryLock;
94
95 #define LOCK IORecursiveLockLock( gIOMemoryLock)
96 #define UNLOCK IORecursiveLockUnlock( gIOMemoryLock)
97 #define SLEEP IORecursiveLockSleep( gIOMemoryLock, (void *)this, THREAD_UNINT)
98 #define WAKEUP \
99 IORecursiveLockWakeup( gIOMemoryLock, (void *)this, /* one-thread */ false)
100
101 #if 0
102 #define DEBG(fmt, args...) { kprintf(fmt, ## args); }
103 #else
104 #define DEBG(fmt, args...) {}
105 #endif
106
107 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
108
109 // Some data structures and accessor macros used by the initWithOptions
110 // Function
111
112 enum ioPLBlockFlags {
113 kIOPLOnDevice = 0x00000001,
114 kIOPLExternUPL = 0x00000002,
115 };
116
117 struct IOMDPersistentInitData
118 {
119 const IOGeneralMemoryDescriptor * fMD;
120 IOMemoryReference * fMemRef;
121 };
122
123 struct ioPLBlock {
124 upl_t fIOPL;
125 vm_address_t fPageInfo; // Pointer to page list or index into it
126 uint32_t fIOMDOffset; // The offset of this iopl in descriptor
127 ppnum_t fMappedPage; // Page number of first page in this iopl
128 unsigned int fPageOffset; // Offset within first page of iopl
129 unsigned int fFlags; // Flags
130 };
131
132 enum { kMaxWireTags = 6 };
133
134 struct ioGMDData
135 {
136 IOMapper * fMapper;
137 uint64_t fDMAMapAlignment;
138 uint64_t fMappedBase;
139 uint64_t fMappedLength;
140 uint64_t fPreparationID;
141 #if IOTRACKING
142 IOTracking fWireTracking;
143 #endif /* IOTRACKING */
144 unsigned int fPageCnt;
145 uint8_t fDMAMapNumAddressBits;
146 unsigned char fDiscontig:1;
147 unsigned char fCompletionError:1;
148 unsigned char fMappedBaseValid:1;
149 unsigned char _resv:3;
150 unsigned char fDMAAccess:2;
151
152 /* variable length arrays */
153 upl_page_info_t fPageList[1]
154 #if __LP64__
155 // align fPageList as for ioPLBlock
156 __attribute__((aligned(sizeof(upl_t))))
157 #endif
158 ;
159 ioPLBlock fBlocks[1];
160 };
161
162 #define getDataP(osd) ((ioGMDData *) (osd)->getBytesNoCopy())
163 #define getIOPLList(d) ((ioPLBlock *) (void *)&(d->fPageList[d->fPageCnt]))
164 #define getNumIOPL(osd, d) \
165 (((osd)->getLength() - ((char *) getIOPLList(d) - (char *) d)) / sizeof(ioPLBlock))
166 #define getPageList(d) (&(d->fPageList[0]))
167 #define computeDataSize(p, u) \
168 (offsetof(ioGMDData, fPageList) + p * sizeof(upl_page_info_t) + u * sizeof(ioPLBlock))
169
170 enum { kIOMemoryHostOrRemote = kIOMemoryHostOnly | kIOMemoryRemote };
171
172 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
173
174 #define next_page(a) ( trunc_page(a) + PAGE_SIZE )
175
176 extern "C" {
177
178 kern_return_t device_data_action(
179 uintptr_t device_handle,
180 ipc_port_t device_pager,
181 vm_prot_t protection,
182 vm_object_offset_t offset,
183 vm_size_t size)
184 {
185 kern_return_t kr;
186 IOMemoryDescriptorReserved * ref = (IOMemoryDescriptorReserved *) device_handle;
187 IOMemoryDescriptor * memDesc;
188
189 LOCK;
190 memDesc = ref->dp.memory;
191 if( memDesc)
192 {
193 memDesc->retain();
194 kr = memDesc->handleFault(device_pager, offset, size);
195 memDesc->release();
196 }
197 else
198 kr = KERN_ABORTED;
199 UNLOCK;
200
201 return( kr );
202 }
203
204 kern_return_t device_close(
205 uintptr_t device_handle)
206 {
207 IOMemoryDescriptorReserved * ref = (IOMemoryDescriptorReserved *) device_handle;
208
209 IODelete( ref, IOMemoryDescriptorReserved, 1 );
210
211 return( kIOReturnSuccess );
212 }
213 }; // end extern "C"
214
215 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
216
217 // Note this inline function uses C++ reference arguments to return values
218 // This means that pointers are not passed and NULLs don't have to be
219 // checked for as a NULL reference is illegal.
220 static inline void
221 getAddrLenForInd(mach_vm_address_t &addr, mach_vm_size_t &len, // Output variables
222 UInt32 type, IOGeneralMemoryDescriptor::Ranges r, UInt32 ind)
223 {
224 assert(kIOMemoryTypeUIO == type
225 || kIOMemoryTypeVirtual == type || kIOMemoryTypeVirtual64 == type
226 || kIOMemoryTypePhysical == type || kIOMemoryTypePhysical64 == type);
227 if (kIOMemoryTypeUIO == type) {
228 user_size_t us;
229 user_addr_t ad;
230 uio_getiov((uio_t) r.uio, ind, &ad, &us); addr = ad; len = us;
231 }
232 #ifndef __LP64__
233 else if ((kIOMemoryTypeVirtual64 == type) || (kIOMemoryTypePhysical64 == type)) {
234 IOAddressRange cur = r.v64[ind];
235 addr = cur.address;
236 len = cur.length;
237 }
238 #endif /* !__LP64__ */
239 else {
240 IOVirtualRange cur = r.v[ind];
241 addr = cur.address;
242 len = cur.length;
243 }
244 }
245
246 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
247
248 static IOReturn
249 purgeableControlBits(IOOptionBits newState, vm_purgable_t * control, int * state)
250 {
251 IOReturn err = kIOReturnSuccess;
252
253 *control = VM_PURGABLE_SET_STATE;
254
255 enum { kIOMemoryPurgeableControlMask = 15 };
256
257 switch (kIOMemoryPurgeableControlMask & newState)
258 {
259 case kIOMemoryPurgeableKeepCurrent:
260 *control = VM_PURGABLE_GET_STATE;
261 break;
262
263 case kIOMemoryPurgeableNonVolatile:
264 *state = VM_PURGABLE_NONVOLATILE;
265 break;
266 case kIOMemoryPurgeableVolatile:
267 *state = VM_PURGABLE_VOLATILE | (newState & ~kIOMemoryPurgeableControlMask);
268 break;
269 case kIOMemoryPurgeableEmpty:
270 *state = VM_PURGABLE_EMPTY | (newState & ~kIOMemoryPurgeableControlMask);
271 break;
272 default:
273 err = kIOReturnBadArgument;
274 break;
275 }
276
277 if (*control == VM_PURGABLE_SET_STATE) {
278 // let VM know this call is from the kernel and is allowed to alter
279 // the volatility of the memory entry even if it was created with
280 // MAP_MEM_PURGABLE_KERNEL_ONLY
281 *control = VM_PURGABLE_SET_STATE_FROM_KERNEL;
282 }
283
284 return (err);
285 }
286
287 static IOReturn
288 purgeableStateBits(int * state)
289 {
290 IOReturn err = kIOReturnSuccess;
291
292 switch (VM_PURGABLE_STATE_MASK & *state)
293 {
294 case VM_PURGABLE_NONVOLATILE:
295 *state = kIOMemoryPurgeableNonVolatile;
296 break;
297 case VM_PURGABLE_VOLATILE:
298 *state = kIOMemoryPurgeableVolatile;
299 break;
300 case VM_PURGABLE_EMPTY:
301 *state = kIOMemoryPurgeableEmpty;
302 break;
303 default:
304 *state = kIOMemoryPurgeableNonVolatile;
305 err = kIOReturnNotReady;
306 break;
307 }
308 return (err);
309 }
310
311
312 static vm_prot_t
313 vmProtForCacheMode(IOOptionBits cacheMode)
314 {
315 vm_prot_t prot = 0;
316 switch (cacheMode)
317 {
318 case kIOInhibitCache:
319 SET_MAP_MEM(MAP_MEM_IO, prot);
320 break;
321
322 case kIOWriteThruCache:
323 SET_MAP_MEM(MAP_MEM_WTHRU, prot);
324 break;
325
326 case kIOWriteCombineCache:
327 SET_MAP_MEM(MAP_MEM_WCOMB, prot);
328 break;
329
330 case kIOCopybackCache:
331 SET_MAP_MEM(MAP_MEM_COPYBACK, prot);
332 break;
333
334 case kIOCopybackInnerCache:
335 SET_MAP_MEM(MAP_MEM_INNERWBACK, prot);
336 break;
337
338 case kIOPostedWrite:
339 SET_MAP_MEM(MAP_MEM_POSTED, prot);
340 break;
341
342 case kIODefaultCache:
343 default:
344 SET_MAP_MEM(MAP_MEM_NOOP, prot);
345 break;
346 }
347
348 return (prot);
349 }
350
351 static unsigned int
352 pagerFlagsForCacheMode(IOOptionBits cacheMode)
353 {
354 unsigned int pagerFlags = 0;
355 switch (cacheMode)
356 {
357 case kIOInhibitCache:
358 pagerFlags = DEVICE_PAGER_CACHE_INHIB | DEVICE_PAGER_COHERENT | DEVICE_PAGER_GUARDED;
359 break;
360
361 case kIOWriteThruCache:
362 pagerFlags = DEVICE_PAGER_WRITE_THROUGH | DEVICE_PAGER_COHERENT | DEVICE_PAGER_GUARDED;
363 break;
364
365 case kIOWriteCombineCache:
366 pagerFlags = DEVICE_PAGER_CACHE_INHIB | DEVICE_PAGER_COHERENT;
367 break;
368
369 case kIOCopybackCache:
370 pagerFlags = DEVICE_PAGER_COHERENT;
371 break;
372
373 case kIOCopybackInnerCache:
374 pagerFlags = DEVICE_PAGER_COHERENT;
375 break;
376
377 case kIOPostedWrite:
378 pagerFlags = DEVICE_PAGER_CACHE_INHIB | DEVICE_PAGER_COHERENT | DEVICE_PAGER_GUARDED | DEVICE_PAGER_EARLY_ACK;
379 break;
380
381 case kIODefaultCache:
382 default:
383 pagerFlags = -1U;
384 break;
385 }
386 return (pagerFlags);
387 }
388
389 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
390 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
391
392 struct IOMemoryEntry
393 {
394 ipc_port_t entry;
395 int64_t offset;
396 uint64_t size;
397 };
398
399 struct IOMemoryReference
400 {
401 volatile SInt32 refCount;
402 vm_prot_t prot;
403 uint32_t capacity;
404 uint32_t count;
405 struct IOMemoryReference * mapRef;
406 IOMemoryEntry entries[0];
407 };
408
409 enum
410 {
411 kIOMemoryReferenceReuse = 0x00000001,
412 kIOMemoryReferenceWrite = 0x00000002,
413 kIOMemoryReferenceCOW = 0x00000004,
414 };
415
416 SInt32 gIOMemoryReferenceCount;
417
418 IOMemoryReference *
419 IOGeneralMemoryDescriptor::memoryReferenceAlloc(uint32_t capacity, IOMemoryReference * realloc)
420 {
421 IOMemoryReference * ref;
422 size_t newSize, oldSize, copySize;
423
424 newSize = (sizeof(IOMemoryReference)
425 - sizeof(ref->entries)
426 + capacity * sizeof(ref->entries[0]));
427 ref = (typeof(ref)) IOMalloc(newSize);
428 if (realloc)
429 {
430 oldSize = (sizeof(IOMemoryReference)
431 - sizeof(realloc->entries)
432 + realloc->capacity * sizeof(realloc->entries[0]));
433 copySize = oldSize;
434 if (copySize > newSize) copySize = newSize;
435 if (ref) bcopy(realloc, ref, copySize);
436 IOFree(realloc, oldSize);
437 }
438 else if (ref)
439 {
440 bzero(ref, sizeof(*ref));
441 ref->refCount = 1;
442 OSIncrementAtomic(&gIOMemoryReferenceCount);
443 }
444 if (!ref) return (0);
445 ref->capacity = capacity;
446 return (ref);
447 }
448
449 void
450 IOGeneralMemoryDescriptor::memoryReferenceFree(IOMemoryReference * ref)
451 {
452 IOMemoryEntry * entries;
453 size_t size;
454
455 if (ref->mapRef)
456 {
457 memoryReferenceFree(ref->mapRef);
458 ref->mapRef = 0;
459 }
460
461 entries = ref->entries + ref->count;
462 while (entries > &ref->entries[0])
463 {
464 entries--;
465 ipc_port_release_send(entries->entry);
466 }
467 size = (sizeof(IOMemoryReference)
468 - sizeof(ref->entries)
469 + ref->capacity * sizeof(ref->entries[0]));
470 IOFree(ref, size);
471
472 OSDecrementAtomic(&gIOMemoryReferenceCount);
473 }
474
475 void
476 IOGeneralMemoryDescriptor::memoryReferenceRelease(IOMemoryReference * ref)
477 {
478 if (1 == OSDecrementAtomic(&ref->refCount)) memoryReferenceFree(ref);
479 }
480
481
482 IOReturn
483 IOGeneralMemoryDescriptor::memoryReferenceCreate(
484 IOOptionBits options,
485 IOMemoryReference ** reference)
486 {
487 enum { kCapacity = 4, kCapacityInc = 4 };
488
489 kern_return_t err;
490 IOMemoryReference * ref;
491 IOMemoryEntry * entries;
492 IOMemoryEntry * cloneEntries;
493 vm_map_t map;
494 ipc_port_t entry, cloneEntry;
495 vm_prot_t prot;
496 memory_object_size_t actualSize;
497 uint32_t rangeIdx;
498 uint32_t count;
499 mach_vm_address_t entryAddr, endAddr, entrySize;
500 mach_vm_size_t srcAddr, srcLen;
501 mach_vm_size_t nextAddr, nextLen;
502 mach_vm_size_t offset, remain;
503 IOByteCount physLen;
504 IOOptionBits type = (_flags & kIOMemoryTypeMask);
505 IOOptionBits cacheMode;
506 unsigned int pagerFlags;
507 vm_tag_t tag;
508
509 ref = memoryReferenceAlloc(kCapacity, NULL);
510 if (!ref) return (kIOReturnNoMemory);
511
512 tag = getVMTag(kernel_map);
513 entries = &ref->entries[0];
514 count = 0;
515 err = KERN_SUCCESS;
516
517 offset = 0;
518 rangeIdx = 0;
519 if (_task)
520 {
521 getAddrLenForInd(nextAddr, nextLen, type, _ranges, rangeIdx);
522 }
523 else
524 {
525 nextAddr = getPhysicalSegment(offset, &physLen, kIOMemoryMapperNone);
526 nextLen = physLen;
527
528 // default cache mode for physical
529 if (kIODefaultCache == ((_flags & kIOMemoryBufferCacheMask) >> kIOMemoryBufferCacheShift))
530 {
531 IOOptionBits mode;
532 pagerFlags = IODefaultCacheBits(nextAddr);
533 if (DEVICE_PAGER_CACHE_INHIB & pagerFlags)
534 {
535 if (DEVICE_PAGER_EARLY_ACK & pagerFlags)
536 mode = kIOPostedWrite;
537 else if (DEVICE_PAGER_GUARDED & pagerFlags)
538 mode = kIOInhibitCache;
539 else
540 mode = kIOWriteCombineCache;
541 }
542 else if (DEVICE_PAGER_WRITE_THROUGH & pagerFlags)
543 mode = kIOWriteThruCache;
544 else
545 mode = kIOCopybackCache;
546 _flags |= (mode << kIOMemoryBufferCacheShift);
547 }
548 }
549
550 // cache mode & vm_prot
551 prot = VM_PROT_READ;
552 cacheMode = ((_flags & kIOMemoryBufferCacheMask) >> kIOMemoryBufferCacheShift);
553 prot |= vmProtForCacheMode(cacheMode);
554 // VM system requires write access to change cache mode
555 if (kIODefaultCache != cacheMode) prot |= VM_PROT_WRITE;
556 if (kIODirectionOut != (kIODirectionOutIn & _flags)) prot |= VM_PROT_WRITE;
557 if (kIOMemoryReferenceWrite & options) prot |= VM_PROT_WRITE;
558 if (kIOMemoryReferenceCOW & options) prot |= MAP_MEM_VM_COPY;
559
560 if ((kIOMemoryReferenceReuse & options) && _memRef)
561 {
562 cloneEntries = &_memRef->entries[0];
563 prot |= MAP_MEM_NAMED_REUSE;
564 }
565
566 if (_task)
567 {
568 // virtual ranges
569
570 if (kIOMemoryBufferPageable & _flags)
571 {
572 // IOBufferMemoryDescriptor alloc - set flags for entry + object create
573 prot |= MAP_MEM_NAMED_CREATE;
574 if (kIOMemoryBufferPurgeable & _flags) prot |= (MAP_MEM_PURGABLE | MAP_MEM_PURGABLE_KERNEL_ONLY);
575 if (kIOMemoryUseReserve & _flags) prot |= MAP_MEM_GRAB_SECLUDED;
576
577 prot |= VM_PROT_WRITE;
578 map = NULL;
579 }
580 else map = get_task_map(_task);
581
582 remain = _length;
583 while (remain)
584 {
585 srcAddr = nextAddr;
586 srcLen = nextLen;
587 nextAddr = 0;
588 nextLen = 0;
589 // coalesce addr range
590 for (++rangeIdx; rangeIdx < _rangesCount; rangeIdx++)
591 {
592 getAddrLenForInd(nextAddr, nextLen, type, _ranges, rangeIdx);
593 if ((srcAddr + srcLen) != nextAddr) break;
594 srcLen += nextLen;
595 }
596 entryAddr = trunc_page_64(srcAddr);
597 endAddr = round_page_64(srcAddr + srcLen);
598 do
599 {
600 entrySize = (endAddr - entryAddr);
601 if (!entrySize) break;
602 actualSize = entrySize;
603
604 cloneEntry = MACH_PORT_NULL;
605 if (MAP_MEM_NAMED_REUSE & prot)
606 {
607 if (cloneEntries < &_memRef->entries[_memRef->count]) cloneEntry = cloneEntries->entry;
608 else prot &= ~MAP_MEM_NAMED_REUSE;
609 }
610
611 err = mach_make_memory_entry_64(map,
612 &actualSize, entryAddr, prot, &entry, cloneEntry);
613
614 if (KERN_SUCCESS != err) break;
615 if (actualSize > entrySize) panic("mach_make_memory_entry_64 actualSize");
616
617 if (count >= ref->capacity)
618 {
619 ref = memoryReferenceAlloc(ref->capacity + kCapacityInc, ref);
620 entries = &ref->entries[count];
621 }
622 entries->entry = entry;
623 entries->size = actualSize;
624 entries->offset = offset + (entryAddr - srcAddr);
625 entryAddr += actualSize;
626 if (MAP_MEM_NAMED_REUSE & prot)
627 {
628 if ((cloneEntries->entry == entries->entry)
629 && (cloneEntries->size == entries->size)
630 && (cloneEntries->offset == entries->offset)) cloneEntries++;
631 else prot &= ~MAP_MEM_NAMED_REUSE;
632 }
633 entries++;
634 count++;
635 }
636 while (true);
637 offset += srcLen;
638 remain -= srcLen;
639 }
640 }
641 else
642 {
643 // _task == 0, physical or kIOMemoryTypeUPL
644 memory_object_t pager;
645 vm_size_t size = ptoa_32(_pages);
646
647 if (!getKernelReserved()) panic("getKernelReserved");
648
649 reserved->dp.pagerContig = (1 == _rangesCount);
650 reserved->dp.memory = this;
651
652 pagerFlags = pagerFlagsForCacheMode(cacheMode);
653 if (-1U == pagerFlags) panic("phys is kIODefaultCache");
654 if (reserved->dp.pagerContig) pagerFlags |= DEVICE_PAGER_CONTIGUOUS;
655
656 pager = device_pager_setup((memory_object_t) 0, (uintptr_t) reserved,
657 size, pagerFlags);
658 assert (pager);
659 if (!pager) err = kIOReturnVMError;
660 else
661 {
662 srcAddr = nextAddr;
663 entryAddr = trunc_page_64(srcAddr);
664 err = mach_memory_object_memory_entry_64((host_t) 1, false /*internal*/,
665 size, VM_PROT_READ | VM_PROT_WRITE, pager, &entry);
666 assert (KERN_SUCCESS == err);
667 if (KERN_SUCCESS != err) device_pager_deallocate(pager);
668 else
669 {
670 reserved->dp.devicePager = pager;
671 entries->entry = entry;
672 entries->size = size;
673 entries->offset = offset + (entryAddr - srcAddr);
674 entries++;
675 count++;
676 }
677 }
678 }
679
680 ref->count = count;
681 ref->prot = prot;
682
683 if (_task && (KERN_SUCCESS == err)
684 && (kIOMemoryMapCopyOnWrite & _flags)
685 && !(kIOMemoryReferenceCOW & options))
686 {
687 err = memoryReferenceCreate(options | kIOMemoryReferenceCOW, &ref->mapRef);
688 }
689
690 if (KERN_SUCCESS == err)
691 {
692 if (MAP_MEM_NAMED_REUSE & prot)
693 {
694 memoryReferenceFree(ref);
695 OSIncrementAtomic(&_memRef->refCount);
696 ref = _memRef;
697 }
698 }
699 else
700 {
701 memoryReferenceFree(ref);
702 ref = NULL;
703 }
704
705 *reference = ref;
706
707 return (err);
708 }
709
710 kern_return_t
711 IOMemoryDescriptorMapAlloc(vm_map_t map, void * _ref)
712 {
713 IOMemoryDescriptorMapAllocRef * ref = (typeof(ref))_ref;
714 IOReturn err;
715 vm_map_offset_t addr;
716
717 addr = ref->mapped;
718
719 err = vm_map_enter_mem_object(map, &addr, ref->size,
720 (vm_map_offset_t) 0,
721 (((ref->options & kIOMapAnywhere)
722 ? VM_FLAGS_ANYWHERE
723 : VM_FLAGS_FIXED)),
724 VM_MAP_KERNEL_FLAGS_NONE,
725 ref->tag,
726 IPC_PORT_NULL,
727 (memory_object_offset_t) 0,
728 false, /* copy */
729 ref->prot,
730 ref->prot,
731 VM_INHERIT_NONE);
732 if (KERN_SUCCESS == err)
733 {
734 ref->mapped = (mach_vm_address_t) addr;
735 ref->map = map;
736 }
737
738 return( err );
739 }
740
741 IOReturn
742 IOGeneralMemoryDescriptor::memoryReferenceMap(
743 IOMemoryReference * ref,
744 vm_map_t map,
745 mach_vm_size_t inoffset,
746 mach_vm_size_t size,
747 IOOptionBits options,
748 mach_vm_address_t * inaddr)
749 {
750 IOReturn err;
751 int64_t offset = inoffset;
752 uint32_t rangeIdx, entryIdx;
753 vm_map_offset_t addr, mapAddr;
754 vm_map_offset_t pageOffset, entryOffset, remain, chunk;
755
756 mach_vm_address_t nextAddr;
757 mach_vm_size_t nextLen;
758 IOByteCount physLen;
759 IOMemoryEntry * entry;
760 vm_prot_t prot, memEntryCacheMode;
761 IOOptionBits type;
762 IOOptionBits cacheMode;
763 vm_tag_t tag;
764 // for the kIOMapPrefault option.
765 upl_page_info_t * pageList = NULL;
766 UInt currentPageIndex = 0;
767 bool didAlloc;
768
769 if (ref->mapRef)
770 {
771 err = memoryReferenceMap(ref->mapRef, map, inoffset, size, options, inaddr);
772 return (err);
773 }
774
775 type = _flags & kIOMemoryTypeMask;
776
777 prot = VM_PROT_READ;
778 if (!(kIOMapReadOnly & options)) prot |= VM_PROT_WRITE;
779 prot &= ref->prot;
780
781 cacheMode = ((options & kIOMapCacheMask) >> kIOMapCacheShift);
782 if (kIODefaultCache != cacheMode)
783 {
784 // VM system requires write access to update named entry cache mode
785 memEntryCacheMode = (MAP_MEM_ONLY | VM_PROT_WRITE | prot | vmProtForCacheMode(cacheMode));
786 }
787
788 tag = getVMTag(map);
789
790 if (_task)
791 {
792 // Find first range for offset
793 if (!_rangesCount) return (kIOReturnBadArgument);
794 for (remain = offset, rangeIdx = 0; rangeIdx < _rangesCount; rangeIdx++)
795 {
796 getAddrLenForInd(nextAddr, nextLen, type, _ranges, rangeIdx);
797 if (remain < nextLen) break;
798 remain -= nextLen;
799 }
800 }
801 else
802 {
803 rangeIdx = 0;
804 remain = 0;
805 nextAddr = getPhysicalSegment(offset, &physLen, kIOMemoryMapperNone);
806 nextLen = size;
807 }
808
809 assert(remain < nextLen);
810 if (remain >= nextLen) return (kIOReturnBadArgument);
811
812 nextAddr += remain;
813 nextLen -= remain;
814 pageOffset = (page_mask & nextAddr);
815 addr = 0;
816 didAlloc = false;
817
818 if (!(options & kIOMapAnywhere))
819 {
820 addr = *inaddr;
821 if (pageOffset != (page_mask & addr)) return (kIOReturnNotAligned);
822 addr -= pageOffset;
823 }
824
825 // find first entry for offset
826 for (entryIdx = 0;
827 (entryIdx < ref->count) && (offset >= ref->entries[entryIdx].offset);
828 entryIdx++) {}
829 entryIdx--;
830 entry = &ref->entries[entryIdx];
831
832 // allocate VM
833 size = round_page_64(size + pageOffset);
834 if (kIOMapOverwrite & options)
835 {
836 if ((map == kernel_map) && (kIOMemoryBufferPageable & _flags))
837 {
838 map = IOPageableMapForAddress(addr);
839 }
840 err = KERN_SUCCESS;
841 }
842 else
843 {
844 IOMemoryDescriptorMapAllocRef ref;
845 ref.map = map;
846 ref.tag = tag;
847 ref.options = options;
848 ref.size = size;
849 ref.prot = prot;
850 if (options & kIOMapAnywhere)
851 // vm_map looks for addresses above here, even when VM_FLAGS_ANYWHERE
852 ref.mapped = 0;
853 else
854 ref.mapped = addr;
855 if ((ref.map == kernel_map) && (kIOMemoryBufferPageable & _flags))
856 err = IOIteratePageableMaps( ref.size, &IOMemoryDescriptorMapAlloc, &ref );
857 else
858 err = IOMemoryDescriptorMapAlloc(ref.map, &ref);
859 if (KERN_SUCCESS == err)
860 {
861 addr = ref.mapped;
862 map = ref.map;
863 didAlloc = true;
864 }
865 }
866
867 /*
868 * If the memory is associated with a device pager but doesn't have a UPL,
869 * it will be immediately faulted in through the pager via populateDevicePager().
870 * kIOMapPrefault is redundant in that case, so don't try to use it for UPL
871 * operations.
872 */
873 if ((reserved != NULL) && (reserved->dp.devicePager) && (_memoryEntries == NULL) && (_wireCount != 0))
874 options &= ~kIOMapPrefault;
875
876 /*
877 * Prefaulting is only possible if we wired the memory earlier. Check the
878 * memory type, and the underlying data.
879 */
880 if (options & kIOMapPrefault)
881 {
882 /*
883 * The memory must have been wired by calling ::prepare(), otherwise
884 * we don't have the UPL. Without UPLs, pages cannot be pre-faulted
885 */
886 assert(_wireCount != 0);
887 assert(_memoryEntries != NULL);
888 if ((_wireCount == 0) ||
889 (_memoryEntries == NULL))
890 {
891 return kIOReturnBadArgument;
892 }
893
894 // Get the page list.
895 ioGMDData* dataP = getDataP(_memoryEntries);
896 ioPLBlock const* ioplList = getIOPLList(dataP);
897 pageList = getPageList(dataP);
898
899 // Get the number of IOPLs.
900 UInt numIOPLs = getNumIOPL(_memoryEntries, dataP);
901
902 /*
903 * Scan through the IOPL Info Blocks, looking for the first block containing
904 * the offset. The research will go past it, so we'll need to go back to the
905 * right range at the end.
906 */
907 UInt ioplIndex = 0;
908 while (ioplIndex < numIOPLs && offset >= ioplList[ioplIndex].fIOMDOffset)
909 ioplIndex++;
910 ioplIndex--;
911
912 // Retrieve the IOPL info block.
913 ioPLBlock ioplInfo = ioplList[ioplIndex];
914
915 /*
916 * For external UPLs, the fPageInfo points directly to the UPL's page_info_t
917 * array.
918 */
919 if (ioplInfo.fFlags & kIOPLExternUPL)
920 pageList = (upl_page_info_t*) ioplInfo.fPageInfo;
921 else
922 pageList = &pageList[ioplInfo.fPageInfo];
923
924 // Rebase [offset] into the IOPL in order to looks for the first page index.
925 mach_vm_size_t offsetInIOPL = offset - ioplInfo.fIOMDOffset + ioplInfo.fPageOffset;
926
927 // Retrieve the index of the first page corresponding to the offset.
928 currentPageIndex = atop_32(offsetInIOPL);
929 }
930
931 // enter mappings
932 remain = size;
933 mapAddr = addr;
934 addr += pageOffset;
935
936 while (remain && (KERN_SUCCESS == err))
937 {
938 entryOffset = offset - entry->offset;
939 if ((page_mask & entryOffset) != pageOffset)
940 {
941 err = kIOReturnNotAligned;
942 break;
943 }
944
945 if (kIODefaultCache != cacheMode)
946 {
947 vm_size_t unused = 0;
948 err = mach_make_memory_entry(NULL /*unused*/, &unused, 0 /*unused*/,
949 memEntryCacheMode, NULL, entry->entry);
950 assert (KERN_SUCCESS == err);
951 }
952
953 entryOffset -= pageOffset;
954 if (entryOffset >= entry->size) panic("entryOffset");
955 chunk = entry->size - entryOffset;
956 if (chunk)
957 {
958 vm_map_kernel_flags_t vmk_flags;
959
960 vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
961 vmk_flags.vmkf_iokit_acct = TRUE; /* iokit accounting */
962
963 if (chunk > remain) chunk = remain;
964 if (options & kIOMapPrefault)
965 {
966 UInt nb_pages = round_page(chunk) / PAGE_SIZE;
967
968 err = vm_map_enter_mem_object_prefault(map,
969 &mapAddr,
970 chunk, 0 /* mask */,
971 (VM_FLAGS_FIXED
972 | VM_FLAGS_OVERWRITE),
973 vmk_flags,
974 tag,
975 entry->entry,
976 entryOffset,
977 prot, // cur
978 prot, // max
979 &pageList[currentPageIndex],
980 nb_pages);
981
982 // Compute the next index in the page list.
983 currentPageIndex += nb_pages;
984 assert(currentPageIndex <= _pages);
985 }
986 else
987 {
988 err = vm_map_enter_mem_object(map,
989 &mapAddr,
990 chunk, 0 /* mask */,
991 (VM_FLAGS_FIXED
992 | VM_FLAGS_OVERWRITE),
993 vmk_flags,
994 tag,
995 entry->entry,
996 entryOffset,
997 false, // copy
998 prot, // cur
999 prot, // max
1000 VM_INHERIT_NONE);
1001 }
1002 if (KERN_SUCCESS != err) break;
1003 remain -= chunk;
1004 if (!remain) break;
1005 mapAddr += chunk;
1006 offset += chunk - pageOffset;
1007 }
1008 pageOffset = 0;
1009 entry++;
1010 entryIdx++;
1011 if (entryIdx >= ref->count)
1012 {
1013 err = kIOReturnOverrun;
1014 break;
1015 }
1016 }
1017
1018 if ((KERN_SUCCESS != err) && didAlloc)
1019 {
1020 (void) mach_vm_deallocate(map, trunc_page_64(addr), size);
1021 addr = 0;
1022 }
1023 *inaddr = addr;
1024
1025 return (err);
1026 }
1027
1028 IOReturn
1029 IOGeneralMemoryDescriptor::memoryReferenceGetPageCounts(
1030 IOMemoryReference * ref,
1031 IOByteCount * residentPageCount,
1032 IOByteCount * dirtyPageCount)
1033 {
1034 IOReturn err;
1035 IOMemoryEntry * entries;
1036 unsigned int resident, dirty;
1037 unsigned int totalResident, totalDirty;
1038
1039 totalResident = totalDirty = 0;
1040 err = kIOReturnSuccess;
1041 entries = ref->entries + ref->count;
1042 while (entries > &ref->entries[0])
1043 {
1044 entries--;
1045 err = mach_memory_entry_get_page_counts(entries->entry, &resident, &dirty);
1046 if (KERN_SUCCESS != err) break;
1047 totalResident += resident;
1048 totalDirty += dirty;
1049 }
1050
1051 if (residentPageCount) *residentPageCount = totalResident;
1052 if (dirtyPageCount) *dirtyPageCount = totalDirty;
1053 return (err);
1054 }
1055
1056 IOReturn
1057 IOGeneralMemoryDescriptor::memoryReferenceSetPurgeable(
1058 IOMemoryReference * ref,
1059 IOOptionBits newState,
1060 IOOptionBits * oldState)
1061 {
1062 IOReturn err;
1063 IOMemoryEntry * entries;
1064 vm_purgable_t control;
1065 int totalState, state;
1066
1067 totalState = kIOMemoryPurgeableNonVolatile;
1068 err = kIOReturnSuccess;
1069 entries = ref->entries + ref->count;
1070 while (entries > &ref->entries[0])
1071 {
1072 entries--;
1073
1074 err = purgeableControlBits(newState, &control, &state);
1075 if (KERN_SUCCESS != err) break;
1076 err = memory_entry_purgeable_control_internal(entries->entry, control, &state);
1077 if (KERN_SUCCESS != err) break;
1078 err = purgeableStateBits(&state);
1079 if (KERN_SUCCESS != err) break;
1080
1081 if (kIOMemoryPurgeableEmpty == state) totalState = kIOMemoryPurgeableEmpty;
1082 else if (kIOMemoryPurgeableEmpty == totalState) continue;
1083 else if (kIOMemoryPurgeableVolatile == totalState) continue;
1084 else if (kIOMemoryPurgeableVolatile == state) totalState = kIOMemoryPurgeableVolatile;
1085 else totalState = kIOMemoryPurgeableNonVolatile;
1086 }
1087
1088 if (oldState) *oldState = totalState;
1089 return (err);
1090 }
1091
1092 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1093
1094 IOMemoryDescriptor *
1095 IOMemoryDescriptor::withAddress(void * address,
1096 IOByteCount length,
1097 IODirection direction)
1098 {
1099 return IOMemoryDescriptor::
1100 withAddressRange((IOVirtualAddress) address, length, direction | kIOMemoryAutoPrepare, kernel_task);
1101 }
1102
1103 #ifndef __LP64__
1104 IOMemoryDescriptor *
1105 IOMemoryDescriptor::withAddress(IOVirtualAddress address,
1106 IOByteCount length,
1107 IODirection direction,
1108 task_t task)
1109 {
1110 IOGeneralMemoryDescriptor * that = new IOGeneralMemoryDescriptor;
1111 if (that)
1112 {
1113 if (that->initWithAddress(address, length, direction, task))
1114 return that;
1115
1116 that->release();
1117 }
1118 return 0;
1119 }
1120 #endif /* !__LP64__ */
1121
1122 IOMemoryDescriptor *
1123 IOMemoryDescriptor::withPhysicalAddress(
1124 IOPhysicalAddress address,
1125 IOByteCount length,
1126 IODirection direction )
1127 {
1128 return (IOMemoryDescriptor::withAddressRange(address, length, direction, TASK_NULL));
1129 }
1130
1131 #ifndef __LP64__
1132 IOMemoryDescriptor *
1133 IOMemoryDescriptor::withRanges( IOVirtualRange * ranges,
1134 UInt32 withCount,
1135 IODirection direction,
1136 task_t task,
1137 bool asReference)
1138 {
1139 IOGeneralMemoryDescriptor * that = new IOGeneralMemoryDescriptor;
1140 if (that)
1141 {
1142 if (that->initWithRanges(ranges, withCount, direction, task, asReference))
1143 return that;
1144
1145 that->release();
1146 }
1147 return 0;
1148 }
1149 #endif /* !__LP64__ */
1150
1151 IOMemoryDescriptor *
1152 IOMemoryDescriptor::withAddressRange(mach_vm_address_t address,
1153 mach_vm_size_t length,
1154 IOOptionBits options,
1155 task_t task)
1156 {
1157 IOAddressRange range = { address, length };
1158 return (IOMemoryDescriptor::withAddressRanges(&range, 1, options, task));
1159 }
1160
1161 IOMemoryDescriptor *
1162 IOMemoryDescriptor::withAddressRanges(IOAddressRange * ranges,
1163 UInt32 rangeCount,
1164 IOOptionBits options,
1165 task_t task)
1166 {
1167 IOGeneralMemoryDescriptor * that = new IOGeneralMemoryDescriptor;
1168 if (that)
1169 {
1170 if (task)
1171 options |= kIOMemoryTypeVirtual64;
1172 else
1173 options |= kIOMemoryTypePhysical64;
1174
1175 if (that->initWithOptions(ranges, rangeCount, 0, task, options, /* mapper */ 0))
1176 return that;
1177
1178 that->release();
1179 }
1180
1181 return 0;
1182 }
1183
1184
1185 /*
1186 * withOptions:
1187 *
1188 * Create a new IOMemoryDescriptor. The buffer is made up of several
1189 * virtual address ranges, from a given task.
1190 *
1191 * Passing the ranges as a reference will avoid an extra allocation.
1192 */
1193 IOMemoryDescriptor *
1194 IOMemoryDescriptor::withOptions(void * buffers,
1195 UInt32 count,
1196 UInt32 offset,
1197 task_t task,
1198 IOOptionBits opts,
1199 IOMapper * mapper)
1200 {
1201 IOGeneralMemoryDescriptor *self = new IOGeneralMemoryDescriptor;
1202
1203 if (self
1204 && !self->initWithOptions(buffers, count, offset, task, opts, mapper))
1205 {
1206 self->release();
1207 return 0;
1208 }
1209
1210 return self;
1211 }
1212
1213 bool IOMemoryDescriptor::initWithOptions(void * buffers,
1214 UInt32 count,
1215 UInt32 offset,
1216 task_t task,
1217 IOOptionBits options,
1218 IOMapper * mapper)
1219 {
1220 return( false );
1221 }
1222
1223 #ifndef __LP64__
1224 IOMemoryDescriptor *
1225 IOMemoryDescriptor::withPhysicalRanges( IOPhysicalRange * ranges,
1226 UInt32 withCount,
1227 IODirection direction,
1228 bool asReference)
1229 {
1230 IOGeneralMemoryDescriptor * that = new IOGeneralMemoryDescriptor;
1231 if (that)
1232 {
1233 if (that->initWithPhysicalRanges(ranges, withCount, direction, asReference))
1234 return that;
1235
1236 that->release();
1237 }
1238 return 0;
1239 }
1240
1241 IOMemoryDescriptor *
1242 IOMemoryDescriptor::withSubRange(IOMemoryDescriptor * of,
1243 IOByteCount offset,
1244 IOByteCount length,
1245 IODirection direction)
1246 {
1247 return (IOSubMemoryDescriptor::withSubRange(of, offset, length, direction));
1248 }
1249 #endif /* !__LP64__ */
1250
1251 IOMemoryDescriptor *
1252 IOMemoryDescriptor::withPersistentMemoryDescriptor(IOMemoryDescriptor *originalMD)
1253 {
1254 IOGeneralMemoryDescriptor *origGenMD =
1255 OSDynamicCast(IOGeneralMemoryDescriptor, originalMD);
1256
1257 if (origGenMD)
1258 return IOGeneralMemoryDescriptor::
1259 withPersistentMemoryDescriptor(origGenMD);
1260 else
1261 return 0;
1262 }
1263
1264 IOMemoryDescriptor *
1265 IOGeneralMemoryDescriptor::withPersistentMemoryDescriptor(IOGeneralMemoryDescriptor *originalMD)
1266 {
1267 IOMemoryReference * memRef;
1268
1269 if (kIOReturnSuccess != originalMD->memoryReferenceCreate(kIOMemoryReferenceReuse, &memRef)) return (0);
1270
1271 if (memRef == originalMD->_memRef)
1272 {
1273 originalMD->retain(); // Add a new reference to ourselves
1274 originalMD->memoryReferenceRelease(memRef);
1275 return originalMD;
1276 }
1277
1278 IOGeneralMemoryDescriptor * self = new IOGeneralMemoryDescriptor;
1279 IOMDPersistentInitData initData = { originalMD, memRef };
1280
1281 if (self
1282 && !self->initWithOptions(&initData, 1, 0, 0, kIOMemoryTypePersistentMD, 0)) {
1283 self->release();
1284 self = 0;
1285 }
1286 return self;
1287 }
1288
1289 #ifndef __LP64__
1290 bool
1291 IOGeneralMemoryDescriptor::initWithAddress(void * address,
1292 IOByteCount withLength,
1293 IODirection withDirection)
1294 {
1295 _singleRange.v.address = (vm_offset_t) address;
1296 _singleRange.v.length = withLength;
1297
1298 return initWithRanges(&_singleRange.v, 1, withDirection, kernel_task, true);
1299 }
1300
1301 bool
1302 IOGeneralMemoryDescriptor::initWithAddress(IOVirtualAddress address,
1303 IOByteCount withLength,
1304 IODirection withDirection,
1305 task_t withTask)
1306 {
1307 _singleRange.v.address = address;
1308 _singleRange.v.length = withLength;
1309
1310 return initWithRanges(&_singleRange.v, 1, withDirection, withTask, true);
1311 }
1312
1313 bool
1314 IOGeneralMemoryDescriptor::initWithPhysicalAddress(
1315 IOPhysicalAddress address,
1316 IOByteCount withLength,
1317 IODirection withDirection )
1318 {
1319 _singleRange.p.address = address;
1320 _singleRange.p.length = withLength;
1321
1322 return initWithPhysicalRanges( &_singleRange.p, 1, withDirection, true);
1323 }
1324
1325 bool
1326 IOGeneralMemoryDescriptor::initWithPhysicalRanges(
1327 IOPhysicalRange * ranges,
1328 UInt32 count,
1329 IODirection direction,
1330 bool reference)
1331 {
1332 IOOptionBits mdOpts = direction | kIOMemoryTypePhysical;
1333
1334 if (reference)
1335 mdOpts |= kIOMemoryAsReference;
1336
1337 return initWithOptions(ranges, count, 0, 0, mdOpts, /* mapper */ 0);
1338 }
1339
1340 bool
1341 IOGeneralMemoryDescriptor::initWithRanges(
1342 IOVirtualRange * ranges,
1343 UInt32 count,
1344 IODirection direction,
1345 task_t task,
1346 bool reference)
1347 {
1348 IOOptionBits mdOpts = direction;
1349
1350 if (reference)
1351 mdOpts |= kIOMemoryAsReference;
1352
1353 if (task) {
1354 mdOpts |= kIOMemoryTypeVirtual;
1355
1356 // Auto-prepare if this is a kernel memory descriptor as very few
1357 // clients bother to prepare() kernel memory.
1358 // But it was not enforced so what are you going to do?
1359 if (task == kernel_task)
1360 mdOpts |= kIOMemoryAutoPrepare;
1361 }
1362 else
1363 mdOpts |= kIOMemoryTypePhysical;
1364
1365 return initWithOptions(ranges, count, 0, task, mdOpts, /* mapper */ 0);
1366 }
1367 #endif /* !__LP64__ */
1368
1369 /*
1370 * initWithOptions:
1371 *
1372 * IOMemoryDescriptor. The buffer is made up of several virtual address ranges,
1373 * from a given task, several physical ranges, an UPL from the ubc
1374 * system or a uio (may be 64bit) from the BSD subsystem.
1375 *
1376 * Passing the ranges as a reference will avoid an extra allocation.
1377 *
1378 * An IOMemoryDescriptor can be re-used by calling initWithOptions again on an
1379 * existing instance -- note this behavior is not commonly supported in other
1380 * I/O Kit classes, although it is supported here.
1381 */
1382
1383 bool
1384 IOGeneralMemoryDescriptor::initWithOptions(void * buffers,
1385 UInt32 count,
1386 UInt32 offset,
1387 task_t task,
1388 IOOptionBits options,
1389 IOMapper * mapper)
1390 {
1391 IOOptionBits type = options & kIOMemoryTypeMask;
1392
1393 #ifndef __LP64__
1394 if (task
1395 && (kIOMemoryTypeVirtual == type)
1396 && vm_map_is_64bit(get_task_map(task))
1397 && ((IOVirtualRange *) buffers)->address)
1398 {
1399 OSReportWithBacktrace("IOMemoryDescriptor: attempt to create 32b virtual in 64b task, use ::withAddressRange()");
1400 return false;
1401 }
1402 #endif /* !__LP64__ */
1403
1404 // Grab the original MD's configuation data to initialse the
1405 // arguments to this function.
1406 if (kIOMemoryTypePersistentMD == type) {
1407
1408 IOMDPersistentInitData *initData = (typeof(initData)) buffers;
1409 const IOGeneralMemoryDescriptor *orig = initData->fMD;
1410 ioGMDData *dataP = getDataP(orig->_memoryEntries);
1411
1412 // Only accept persistent memory descriptors with valid dataP data.
1413 assert(orig->_rangesCount == 1);
1414 if ( !(orig->_flags & kIOMemoryPersistent) || !dataP)
1415 return false;
1416
1417 _memRef = initData->fMemRef; // Grab the new named entry
1418 options = orig->_flags & ~kIOMemoryAsReference;
1419 type = options & kIOMemoryTypeMask;
1420 buffers = orig->_ranges.v;
1421 count = orig->_rangesCount;
1422
1423 // Now grab the original task and whatever mapper was previously used
1424 task = orig->_task;
1425 mapper = dataP->fMapper;
1426
1427 // We are ready to go through the original initialisation now
1428 }
1429
1430 switch (type) {
1431 case kIOMemoryTypeUIO:
1432 case kIOMemoryTypeVirtual:
1433 #ifndef __LP64__
1434 case kIOMemoryTypeVirtual64:
1435 #endif /* !__LP64__ */
1436 assert(task);
1437 if (!task)
1438 return false;
1439 break;
1440
1441 case kIOMemoryTypePhysical: // Neither Physical nor UPL should have a task
1442 #ifndef __LP64__
1443 case kIOMemoryTypePhysical64:
1444 #endif /* !__LP64__ */
1445 case kIOMemoryTypeUPL:
1446 assert(!task);
1447 break;
1448 default:
1449 return false; /* bad argument */
1450 }
1451
1452 assert(buffers);
1453 assert(count);
1454
1455 /*
1456 * We can check the _initialized instance variable before having ever set
1457 * it to an initial value because I/O Kit guarantees that all our instance
1458 * variables are zeroed on an object's allocation.
1459 */
1460
1461 if (_initialized) {
1462 /*
1463 * An existing memory descriptor is being retargeted to point to
1464 * somewhere else. Clean up our present state.
1465 */
1466 IOOptionBits type = _flags & kIOMemoryTypeMask;
1467 if ((kIOMemoryTypePhysical != type) && (kIOMemoryTypePhysical64 != type))
1468 {
1469 while (_wireCount)
1470 complete();
1471 }
1472 if (_ranges.v && !(kIOMemoryAsReference & _flags))
1473 {
1474 if (kIOMemoryTypeUIO == type)
1475 uio_free((uio_t) _ranges.v);
1476 #ifndef __LP64__
1477 else if ((kIOMemoryTypeVirtual64 == type) || (kIOMemoryTypePhysical64 == type))
1478 IODelete(_ranges.v64, IOAddressRange, _rangesCount);
1479 #endif /* !__LP64__ */
1480 else
1481 IODelete(_ranges.v, IOVirtualRange, _rangesCount);
1482 }
1483
1484 options |= (kIOMemoryRedirected & _flags);
1485 if (!(kIOMemoryRedirected & options))
1486 {
1487 if (_memRef)
1488 {
1489 memoryReferenceRelease(_memRef);
1490 _memRef = 0;
1491 }
1492 if (_mappings)
1493 _mappings->flushCollection();
1494 }
1495 }
1496 else {
1497 if (!super::init())
1498 return false;
1499 _initialized = true;
1500 }
1501
1502 // Grab the appropriate mapper
1503 if (kIOMemoryHostOrRemote & options) options |= kIOMemoryMapperNone;
1504 if (kIOMemoryMapperNone & options)
1505 mapper = 0; // No Mapper
1506 else if (mapper == kIOMapperSystem) {
1507 IOMapper::checkForSystemMapper();
1508 gIOSystemMapper = mapper = IOMapper::gSystem;
1509 }
1510
1511 // Remove the dynamic internal use flags from the initial setting
1512 options &= ~(kIOMemoryPreparedReadOnly);
1513 _flags = options;
1514 _task = task;
1515
1516 #ifndef __LP64__
1517 _direction = (IODirection) (_flags & kIOMemoryDirectionMask);
1518 #endif /* !__LP64__ */
1519
1520 _dmaReferences = 0;
1521 __iomd_reservedA = 0;
1522 __iomd_reservedB = 0;
1523 _highestPage = 0;
1524
1525 if (kIOMemoryThreadSafe & options)
1526 {
1527 if (!_prepareLock)
1528 _prepareLock = IOLockAlloc();
1529 }
1530 else if (_prepareLock)
1531 {
1532 IOLockFree(_prepareLock);
1533 _prepareLock = NULL;
1534 }
1535
1536 if (kIOMemoryTypeUPL == type) {
1537
1538 ioGMDData *dataP;
1539 unsigned int dataSize = computeDataSize(/* pages */ 0, /* upls */ 1);
1540
1541 if (!initMemoryEntries(dataSize, mapper)) return (false);
1542 dataP = getDataP(_memoryEntries);
1543 dataP->fPageCnt = 0;
1544 switch (kIOMemoryDirectionMask & options)
1545 {
1546 case kIODirectionOut:
1547 dataP->fDMAAccess = kIODMAMapReadAccess;
1548 break;
1549 case kIODirectionIn:
1550 dataP->fDMAAccess = kIODMAMapWriteAccess;
1551 break;
1552 case kIODirectionNone:
1553 case kIODirectionOutIn:
1554 default:
1555 panic("bad dir for upl 0x%x\n", (int) options);
1556 break;
1557 }
1558 // _wireCount++; // UPLs start out life wired
1559
1560 _length = count;
1561 _pages += atop_32(offset + count + PAGE_MASK) - atop_32(offset);
1562
1563 ioPLBlock iopl;
1564 iopl.fIOPL = (upl_t) buffers;
1565 upl_set_referenced(iopl.fIOPL, true);
1566 upl_page_info_t *pageList = UPL_GET_INTERNAL_PAGE_LIST(iopl.fIOPL);
1567
1568 if (upl_get_size(iopl.fIOPL) < (count + offset))
1569 panic("short external upl");
1570
1571 _highestPage = upl_get_highest_page(iopl.fIOPL);
1572
1573 // Set the flag kIOPLOnDevice convieniently equal to 1
1574 iopl.fFlags = pageList->device | kIOPLExternUPL;
1575 if (!pageList->device) {
1576 // Pre-compute the offset into the UPL's page list
1577 pageList = &pageList[atop_32(offset)];
1578 offset &= PAGE_MASK;
1579 }
1580 iopl.fIOMDOffset = 0;
1581 iopl.fMappedPage = 0;
1582 iopl.fPageInfo = (vm_address_t) pageList;
1583 iopl.fPageOffset = offset;
1584 _memoryEntries->appendBytes(&iopl, sizeof(iopl));
1585 }
1586 else {
1587 // kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO
1588 // kIOMemoryTypePhysical | kIOMemoryTypePhysical64
1589
1590 // Initialize the memory descriptor
1591 if (options & kIOMemoryAsReference) {
1592 #ifndef __LP64__
1593 _rangesIsAllocated = false;
1594 #endif /* !__LP64__ */
1595
1596 // Hack assignment to get the buffer arg into _ranges.
1597 // I'd prefer to do _ranges = (Ranges) buffers, but that doesn't
1598 // work, C++ sigh.
1599 // This also initialises the uio & physical ranges.
1600 _ranges.v = (IOVirtualRange *) buffers;
1601 }
1602 else {
1603 #ifndef __LP64__
1604 _rangesIsAllocated = true;
1605 #endif /* !__LP64__ */
1606 switch (type)
1607 {
1608 case kIOMemoryTypeUIO:
1609 _ranges.v = (IOVirtualRange *) uio_duplicate((uio_t) buffers);
1610 break;
1611
1612 #ifndef __LP64__
1613 case kIOMemoryTypeVirtual64:
1614 case kIOMemoryTypePhysical64:
1615 if (count == 1
1616 #ifndef __arm__
1617 && (((IOAddressRange *) buffers)->address + ((IOAddressRange *) buffers)->length) <= 0x100000000ULL
1618 #endif
1619 ) {
1620 if (kIOMemoryTypeVirtual64 == type)
1621 type = kIOMemoryTypeVirtual;
1622 else
1623 type = kIOMemoryTypePhysical;
1624 _flags = (_flags & ~kIOMemoryTypeMask) | type | kIOMemoryAsReference;
1625 _rangesIsAllocated = false;
1626 _ranges.v = &_singleRange.v;
1627 _singleRange.v.address = ((IOAddressRange *) buffers)->address;
1628 _singleRange.v.length = ((IOAddressRange *) buffers)->length;
1629 break;
1630 }
1631 _ranges.v64 = IONew(IOAddressRange, count);
1632 if (!_ranges.v64)
1633 return false;
1634 bcopy(buffers, _ranges.v, count * sizeof(IOAddressRange));
1635 break;
1636 #endif /* !__LP64__ */
1637 case kIOMemoryTypeVirtual:
1638 case kIOMemoryTypePhysical:
1639 if (count == 1) {
1640 _flags |= kIOMemoryAsReference;
1641 #ifndef __LP64__
1642 _rangesIsAllocated = false;
1643 #endif /* !__LP64__ */
1644 _ranges.v = &_singleRange.v;
1645 } else {
1646 _ranges.v = IONew(IOVirtualRange, count);
1647 if (!_ranges.v)
1648 return false;
1649 }
1650 bcopy(buffers, _ranges.v, count * sizeof(IOVirtualRange));
1651 break;
1652 }
1653 }
1654 _rangesCount = count;
1655
1656 // Find starting address within the vector of ranges
1657 Ranges vec = _ranges;
1658 mach_vm_size_t totalLength = 0;
1659 unsigned int ind, pages = 0;
1660 for (ind = 0; ind < count; ind++) {
1661 mach_vm_address_t addr;
1662 mach_vm_address_t endAddr;
1663 mach_vm_size_t len;
1664
1665 // addr & len are returned by this function
1666 getAddrLenForInd(addr, len, type, vec, ind);
1667 if (os_add3_overflow(addr, len, PAGE_MASK, &endAddr)) break;
1668 if (os_add_overflow(pages, (atop_64(endAddr) - atop_64(addr)), &pages)) break;
1669 if (os_add_overflow(totalLength, len, &totalLength)) break;
1670 if ((kIOMemoryTypePhysical == type) || (kIOMemoryTypePhysical64 == type))
1671 {
1672 ppnum_t highPage = atop_64(addr + len - 1);
1673 if (highPage > _highestPage)
1674 _highestPage = highPage;
1675 }
1676 }
1677 if ((ind < count)
1678 || (totalLength != ((IOByteCount) totalLength))) return (false); /* overflow */
1679
1680 _length = totalLength;
1681 _pages = pages;
1682
1683 // Auto-prepare memory at creation time.
1684 // Implied completion when descriptor is free-ed
1685
1686
1687 if ((kIOMemoryTypePhysical == type) || (kIOMemoryTypePhysical64 == type))
1688 _wireCount++; // Physical MDs are, by definition, wired
1689 else { /* kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO */
1690 ioGMDData *dataP;
1691 unsigned dataSize;
1692
1693 if (_pages > atop_64(max_mem)) return false;
1694
1695 dataSize = computeDataSize(_pages, /* upls */ count * 2);
1696 if (!initMemoryEntries(dataSize, mapper)) return false;
1697 dataP = getDataP(_memoryEntries);
1698 dataP->fPageCnt = _pages;
1699
1700 if (((_task != kernel_task) || (kIOMemoryBufferPageable & _flags))
1701 && (VM_KERN_MEMORY_NONE == _kernelTag))
1702 {
1703 _kernelTag = IOMemoryTag(kernel_map);
1704 }
1705
1706 if ( (kIOMemoryPersistent & _flags) && !_memRef)
1707 {
1708 IOReturn
1709 err = memoryReferenceCreate(0, &_memRef);
1710 if (kIOReturnSuccess != err) return false;
1711 }
1712
1713 if ((_flags & kIOMemoryAutoPrepare)
1714 && prepare() != kIOReturnSuccess)
1715 return false;
1716 }
1717 }
1718
1719 return true;
1720 }
1721
1722 /*
1723 * free
1724 *
1725 * Free resources.
1726 */
1727 void IOGeneralMemoryDescriptor::free()
1728 {
1729 IOOptionBits type = _flags & kIOMemoryTypeMask;
1730
1731 if( reserved)
1732 {
1733 LOCK;
1734 reserved->dp.memory = 0;
1735 UNLOCK;
1736 }
1737 if ((kIOMemoryTypePhysical == type) || (kIOMemoryTypePhysical64 == type))
1738 {
1739 ioGMDData * dataP;
1740 if (_memoryEntries && (dataP = getDataP(_memoryEntries)) && dataP->fMappedBaseValid)
1741 {
1742 dmaUnmap(dataP->fMapper, NULL, 0, dataP->fMappedBase, dataP->fMappedLength);
1743 dataP->fMappedBaseValid = dataP->fMappedBase = 0;
1744 }
1745 }
1746 else
1747 {
1748 while (_wireCount) complete();
1749 }
1750
1751 if (_memoryEntries) _memoryEntries->release();
1752
1753 if (_ranges.v && !(kIOMemoryAsReference & _flags))
1754 {
1755 if (kIOMemoryTypeUIO == type)
1756 uio_free((uio_t) _ranges.v);
1757 #ifndef __LP64__
1758 else if ((kIOMemoryTypeVirtual64 == type) || (kIOMemoryTypePhysical64 == type))
1759 IODelete(_ranges.v64, IOAddressRange, _rangesCount);
1760 #endif /* !__LP64__ */
1761 else
1762 IODelete(_ranges.v, IOVirtualRange, _rangesCount);
1763
1764 _ranges.v = NULL;
1765 }
1766
1767 if (reserved)
1768 {
1769 if (reserved->dp.devicePager)
1770 {
1771 // memEntry holds a ref on the device pager which owns reserved
1772 // (IOMemoryDescriptorReserved) so no reserved access after this point
1773 device_pager_deallocate( (memory_object_t) reserved->dp.devicePager );
1774 }
1775 else
1776 IODelete(reserved, IOMemoryDescriptorReserved, 1);
1777 reserved = NULL;
1778 }
1779
1780 if (_memRef) memoryReferenceRelease(_memRef);
1781 if (_prepareLock) IOLockFree(_prepareLock);
1782
1783 super::free();
1784 }
1785
1786 #ifndef __LP64__
1787 void IOGeneralMemoryDescriptor::unmapFromKernel()
1788 {
1789 panic("IOGMD::unmapFromKernel deprecated");
1790 }
1791
1792 void IOGeneralMemoryDescriptor::mapIntoKernel(unsigned rangeIndex)
1793 {
1794 panic("IOGMD::mapIntoKernel deprecated");
1795 }
1796 #endif /* !__LP64__ */
1797
1798 /*
1799 * getDirection:
1800 *
1801 * Get the direction of the transfer.
1802 */
1803 IODirection IOMemoryDescriptor::getDirection() const
1804 {
1805 #ifndef __LP64__
1806 if (_direction)
1807 return _direction;
1808 #endif /* !__LP64__ */
1809 return (IODirection) (_flags & kIOMemoryDirectionMask);
1810 }
1811
1812 /*
1813 * getLength:
1814 *
1815 * Get the length of the transfer (over all ranges).
1816 */
1817 IOByteCount IOMemoryDescriptor::getLength() const
1818 {
1819 return _length;
1820 }
1821
1822 void IOMemoryDescriptor::setTag( IOOptionBits tag )
1823 {
1824 _tag = tag;
1825 }
1826
1827 IOOptionBits IOMemoryDescriptor::getTag( void )
1828 {
1829 return( _tag);
1830 }
1831
1832 uint64_t IOMemoryDescriptor::getFlags(void)
1833 {
1834 return (_flags);
1835 }
1836
1837 #ifndef __LP64__
1838 #pragma clang diagnostic push
1839 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1840
1841 // @@@ gvdl: who is using this API? Seems like a wierd thing to implement.
1842 IOPhysicalAddress
1843 IOMemoryDescriptor::getSourceSegment( IOByteCount offset, IOByteCount * length )
1844 {
1845 addr64_t physAddr = 0;
1846
1847 if( prepare() == kIOReturnSuccess) {
1848 physAddr = getPhysicalSegment64( offset, length );
1849 complete();
1850 }
1851
1852 return( (IOPhysicalAddress) physAddr ); // truncated but only page offset is used
1853 }
1854
1855 #pragma clang diagnostic pop
1856
1857 #endif /* !__LP64__ */
1858
1859 IOByteCount IOMemoryDescriptor::readBytes
1860 (IOByteCount offset, void *bytes, IOByteCount length)
1861 {
1862 addr64_t dstAddr = CAST_DOWN(addr64_t, bytes);
1863 IOByteCount remaining;
1864
1865 // Assert that this entire I/O is withing the available range
1866 assert(offset <= _length);
1867 assert(offset + length <= _length);
1868 if ((offset >= _length)
1869 || ((offset + length) > _length)) {
1870 return 0;
1871 }
1872
1873 assert (!(kIOMemoryRemote & _flags));
1874 if (kIOMemoryRemote & _flags) return (0);
1875
1876 if (kIOMemoryThreadSafe & _flags)
1877 LOCK;
1878
1879 remaining = length = min(length, _length - offset);
1880 while (remaining) { // (process another target segment?)
1881 addr64_t srcAddr64;
1882 IOByteCount srcLen;
1883
1884 srcAddr64 = getPhysicalSegment(offset, &srcLen, kIOMemoryMapperNone);
1885 if (!srcAddr64)
1886 break;
1887
1888 // Clip segment length to remaining
1889 if (srcLen > remaining)
1890 srcLen = remaining;
1891
1892 copypv(srcAddr64, dstAddr, srcLen,
1893 cppvPsrc | cppvNoRefSrc | cppvFsnk | cppvKmap);
1894
1895 dstAddr += srcLen;
1896 offset += srcLen;
1897 remaining -= srcLen;
1898 }
1899
1900 if (kIOMemoryThreadSafe & _flags)
1901 UNLOCK;
1902
1903 assert(!remaining);
1904
1905 return length - remaining;
1906 }
1907
1908 IOByteCount IOMemoryDescriptor::writeBytes
1909 (IOByteCount inoffset, const void *bytes, IOByteCount length)
1910 {
1911 addr64_t srcAddr = CAST_DOWN(addr64_t, bytes);
1912 IOByteCount remaining;
1913 IOByteCount offset = inoffset;
1914
1915 // Assert that this entire I/O is withing the available range
1916 assert(offset <= _length);
1917 assert(offset + length <= _length);
1918
1919 assert( !(kIOMemoryPreparedReadOnly & _flags) );
1920
1921 if ( (kIOMemoryPreparedReadOnly & _flags)
1922 || (offset >= _length)
1923 || ((offset + length) > _length)) {
1924 return 0;
1925 }
1926
1927 assert (!(kIOMemoryRemote & _flags));
1928 if (kIOMemoryRemote & _flags) return (0);
1929
1930 if (kIOMemoryThreadSafe & _flags)
1931 LOCK;
1932
1933 remaining = length = min(length, _length - offset);
1934 while (remaining) { // (process another target segment?)
1935 addr64_t dstAddr64;
1936 IOByteCount dstLen;
1937
1938 dstAddr64 = getPhysicalSegment(offset, &dstLen, kIOMemoryMapperNone);
1939 if (!dstAddr64)
1940 break;
1941
1942 // Clip segment length to remaining
1943 if (dstLen > remaining)
1944 dstLen = remaining;
1945
1946 if (!srcAddr) bzero_phys(dstAddr64, dstLen);
1947 else
1948 {
1949 copypv(srcAddr, (addr64_t) dstAddr64, dstLen,
1950 cppvPsnk | cppvFsnk | cppvNoRefSrc | cppvNoModSnk | cppvKmap);
1951 srcAddr += dstLen;
1952 }
1953 offset += dstLen;
1954 remaining -= dstLen;
1955 }
1956
1957 if (kIOMemoryThreadSafe & _flags)
1958 UNLOCK;
1959
1960 assert(!remaining);
1961
1962 if (!srcAddr) performOperation(kIOMemoryIncoherentIOFlush, inoffset, length);
1963
1964 return length - remaining;
1965 }
1966
1967 #ifndef __LP64__
1968 void IOGeneralMemoryDescriptor::setPosition(IOByteCount position)
1969 {
1970 panic("IOGMD::setPosition deprecated");
1971 }
1972 #endif /* !__LP64__ */
1973
1974 static volatile SInt64 gIOMDPreparationID __attribute__((aligned(8))) = (1ULL << 32);
1975
1976 uint64_t
1977 IOGeneralMemoryDescriptor::getPreparationID( void )
1978 {
1979 ioGMDData *dataP;
1980
1981 if (!_wireCount)
1982 return (kIOPreparationIDUnprepared);
1983
1984 if (((kIOMemoryTypeMask & _flags) == kIOMemoryTypePhysical)
1985 || ((kIOMemoryTypeMask & _flags) == kIOMemoryTypePhysical64))
1986 {
1987 IOMemoryDescriptor::setPreparationID();
1988 return (IOMemoryDescriptor::getPreparationID());
1989 }
1990
1991 if (!_memoryEntries || !(dataP = getDataP(_memoryEntries)))
1992 return (kIOPreparationIDUnprepared);
1993
1994 if (kIOPreparationIDUnprepared == dataP->fPreparationID)
1995 {
1996 dataP->fPreparationID = OSIncrementAtomic64(&gIOMDPreparationID);
1997 }
1998 return (dataP->fPreparationID);
1999 }
2000
2001 IOMemoryDescriptorReserved * IOMemoryDescriptor::getKernelReserved( void )
2002 {
2003 if (!reserved)
2004 {
2005 reserved = IONew(IOMemoryDescriptorReserved, 1);
2006 if (reserved)
2007 bzero(reserved, sizeof(IOMemoryDescriptorReserved));
2008 }
2009 return (reserved);
2010 }
2011
2012 void IOMemoryDescriptor::setPreparationID( void )
2013 {
2014 if (getKernelReserved() && (kIOPreparationIDUnprepared == reserved->preparationID))
2015 {
2016 reserved->preparationID = OSIncrementAtomic64(&gIOMDPreparationID);
2017 }
2018 }
2019
2020 uint64_t IOMemoryDescriptor::getPreparationID( void )
2021 {
2022 if (reserved)
2023 return (reserved->preparationID);
2024 else
2025 return (kIOPreparationIDUnsupported);
2026 }
2027
2028 void IOMemoryDescriptor::setVMTags(vm_tag_t kernelTag, vm_tag_t userTag)
2029 {
2030 _kernelTag = kernelTag;
2031 _userTag = userTag;
2032 }
2033
2034 vm_tag_t IOMemoryDescriptor::getVMTag(vm_map_t map)
2035 {
2036 if (vm_kernel_map_is_kernel(map))
2037 {
2038 if (VM_KERN_MEMORY_NONE != _kernelTag) return (_kernelTag);
2039 }
2040 else
2041 {
2042 if (VM_KERN_MEMORY_NONE != _userTag) return (_userTag);
2043 }
2044 return (IOMemoryTag(map));
2045 }
2046
2047 IOReturn IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *vData, UInt dataSize) const
2048 {
2049 IOReturn err = kIOReturnSuccess;
2050 DMACommandOps params;
2051 IOGeneralMemoryDescriptor * md = const_cast<IOGeneralMemoryDescriptor *>(this);
2052 ioGMDData *dataP;
2053
2054 params = (op & ~kIOMDDMACommandOperationMask & op);
2055 op &= kIOMDDMACommandOperationMask;
2056
2057 if (kIOMDDMAMap == op)
2058 {
2059 if (dataSize < sizeof(IOMDDMAMapArgs))
2060 return kIOReturnUnderrun;
2061
2062 IOMDDMAMapArgs * data = (IOMDDMAMapArgs *) vData;
2063
2064 if (!_memoryEntries
2065 && !md->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem)) return (kIOReturnNoMemory);
2066
2067 if (_memoryEntries && data->fMapper)
2068 {
2069 bool remap, keepMap;
2070 dataP = getDataP(_memoryEntries);
2071
2072 if (data->fMapSpec.numAddressBits < dataP->fDMAMapNumAddressBits) dataP->fDMAMapNumAddressBits = data->fMapSpec.numAddressBits;
2073 if (data->fMapSpec.alignment > dataP->fDMAMapAlignment) dataP->fDMAMapAlignment = data->fMapSpec.alignment;
2074
2075 keepMap = (data->fMapper == gIOSystemMapper);
2076 keepMap &= ((data->fOffset == 0) && (data->fLength == _length));
2077
2078 remap = (!keepMap);
2079 remap |= (dataP->fDMAMapNumAddressBits < 64)
2080 && ((dataP->fMappedBase + _length) > (1ULL << dataP->fDMAMapNumAddressBits));
2081 remap |= (dataP->fDMAMapAlignment > page_size);
2082
2083 if (remap || !dataP->fMappedBaseValid)
2084 {
2085 // if (dataP->fMappedBaseValid) OSReportWithBacktrace("kIOMDDMAMap whole %d remap %d params %d\n", whole, remap, params);
2086 err = md->dmaMap(data->fMapper, data->fCommand, &data->fMapSpec, data->fOffset, data->fLength, &data->fAlloc, &data->fAllocLength);
2087 if (keepMap && (kIOReturnSuccess == err) && !dataP->fMappedBaseValid)
2088 {
2089 dataP->fMappedBase = data->fAlloc;
2090 dataP->fMappedBaseValid = true;
2091 dataP->fMappedLength = data->fAllocLength;
2092 data->fAllocLength = 0; // IOMD owns the alloc now
2093 }
2094 }
2095 else
2096 {
2097 data->fAlloc = dataP->fMappedBase;
2098 data->fAllocLength = 0; // give out IOMD map
2099 md->dmaMapRecord(data->fMapper, data->fCommand, dataP->fMappedLength);
2100 }
2101 data->fMapContig = !dataP->fDiscontig;
2102 }
2103 return (err);
2104 }
2105 if (kIOMDDMAUnmap == op)
2106 {
2107 if (dataSize < sizeof(IOMDDMAMapArgs))
2108 return kIOReturnUnderrun;
2109 IOMDDMAMapArgs * data = (IOMDDMAMapArgs *) vData;
2110
2111 err = md->dmaUnmap(data->fMapper, data->fCommand, data->fOffset, data->fAlloc, data->fAllocLength);
2112
2113 return kIOReturnSuccess;
2114 }
2115
2116 if (kIOMDAddDMAMapSpec == op)
2117 {
2118 if (dataSize < sizeof(IODMAMapSpecification))
2119 return kIOReturnUnderrun;
2120
2121 IODMAMapSpecification * data = (IODMAMapSpecification *) vData;
2122
2123 if (!_memoryEntries
2124 && !md->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem)) return (kIOReturnNoMemory);
2125
2126 if (_memoryEntries)
2127 {
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;
2133 }
2134 return kIOReturnSuccess;
2135 }
2136
2137 if (kIOMDGetCharacteristics == op) {
2138
2139 if (dataSize < sizeof(IOMDDMACharacteristics))
2140 return kIOReturnUnderrun;
2141
2142 IOMDDMACharacteristics *data = (IOMDDMACharacteristics *) vData;
2143 data->fLength = _length;
2144 data->fSGCount = _rangesCount;
2145 data->fPages = _pages;
2146 data->fDirection = getDirection();
2147 if (!_wireCount)
2148 data->fIsPrepared = false;
2149 else {
2150 data->fIsPrepared = true;
2151 data->fHighestPage = _highestPage;
2152 if (_memoryEntries)
2153 {
2154 dataP = getDataP(_memoryEntries);
2155 ioPLBlock *ioplList = getIOPLList(dataP);
2156 UInt count = getNumIOPL(_memoryEntries, dataP);
2157 if (count == 1)
2158 data->fPageAlign = (ioplList[0].fPageOffset & PAGE_MASK) | ~PAGE_MASK;
2159 }
2160 }
2161
2162 return kIOReturnSuccess;
2163 }
2164
2165 else if (kIOMDDMAActive == op)
2166 {
2167 if (params)
2168 {
2169 int16_t prior;
2170 prior = OSAddAtomic16(1, &md->_dmaReferences);
2171 if (!prior) md->_mapName = NULL;
2172 }
2173 else
2174 {
2175 if (md->_dmaReferences) OSAddAtomic16(-1, &md->_dmaReferences);
2176 else panic("_dmaReferences underflow");
2177 }
2178 }
2179 else if (kIOMDWalkSegments != op)
2180 return kIOReturnBadArgument;
2181
2182 // Get the next segment
2183 struct InternalState {
2184 IOMDDMAWalkSegmentArgs fIO;
2185 UInt fOffset2Index;
2186 UInt fIndex;
2187 UInt fNextOffset;
2188 } *isP;
2189
2190 // Find the next segment
2191 if (dataSize < sizeof(*isP))
2192 return kIOReturnUnderrun;
2193
2194 isP = (InternalState *) vData;
2195 UInt offset = isP->fIO.fOffset;
2196 uint8_t mapped = isP->fIO.fMapped;
2197 uint64_t mappedBase;
2198
2199 if (mapped && (kIOMemoryRemote & _flags)) return (kIOReturnNotAttached);
2200
2201 if (IOMapper::gSystem && mapped
2202 && (!(kIOMemoryHostOnly & _flags))
2203 && (!_memoryEntries || !getDataP(_memoryEntries)->fMappedBaseValid))
2204 // && (_memoryEntries && !getDataP(_memoryEntries)->fMappedBaseValid))
2205 {
2206 if (!_memoryEntries
2207 && !md->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem)) return (kIOReturnNoMemory);
2208
2209 dataP = getDataP(_memoryEntries);
2210 if (dataP->fMapper)
2211 {
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;
2219 }
2220 }
2221
2222 if (kIOMDDMAWalkMappedLocal == mapped) mappedBase = isP->fIO.fMappedBase;
2223 else if (mapped)
2224 {
2225 if (IOMapper::gSystem
2226 && (!(kIOMemoryHostOnly & _flags))
2227 && _memoryEntries
2228 && (dataP = getDataP(_memoryEntries))
2229 && dataP->fMappedBaseValid)
2230 {
2231 mappedBase = dataP->fMappedBase;
2232 }
2233 else mapped = 0;
2234 }
2235
2236 if (offset >= _length)
2237 return (offset == _length)? kIOReturnOverrun : kIOReturnInternalError;
2238
2239 // Validate the previous offset
2240 UInt ind, off2Ind = isP->fOffset2Index;
2241 if (!params
2242 && offset
2243 && (offset == isP->fNextOffset || off2Ind <= offset))
2244 ind = isP->fIndex;
2245 else
2246 ind = off2Ind = 0; // Start from beginning
2247
2248 UInt length;
2249 UInt64 address;
2250
2251 if ( (_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical) {
2252
2253 // Physical address based memory descriptor
2254 const IOPhysicalRange *physP = (IOPhysicalRange *) &_ranges.p[0];
2255
2256 // Find the range after the one that contains the offset
2257 mach_vm_size_t len;
2258 for (len = 0; off2Ind <= offset; ind++) {
2259 len = physP[ind].length;
2260 off2Ind += len;
2261 }
2262
2263 // Calculate length within range and starting address
2264 length = off2Ind - offset;
2265 address = physP[ind - 1].address + len - length;
2266
2267 if (true && mapped)
2268 {
2269 address = mappedBase + offset;
2270 }
2271 else
2272 {
2273 // see how far we can coalesce ranges
2274 while (ind < _rangesCount && address + length == physP[ind].address) {
2275 len = physP[ind].length;
2276 length += len;
2277 off2Ind += len;
2278 ind++;
2279 }
2280 }
2281
2282 // correct contiguous check overshoot
2283 ind--;
2284 off2Ind -= len;
2285 }
2286 #ifndef __LP64__
2287 else if ( (_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical64) {
2288
2289 // Physical address based memory descriptor
2290 const IOAddressRange *physP = (IOAddressRange *) &_ranges.v64[0];
2291
2292 // Find the range after the one that contains the offset
2293 mach_vm_size_t len;
2294 for (len = 0; off2Ind <= offset; ind++) {
2295 len = physP[ind].length;
2296 off2Ind += len;
2297 }
2298
2299 // Calculate length within range and starting address
2300 length = off2Ind - offset;
2301 address = physP[ind - 1].address + len - length;
2302
2303 if (true && mapped)
2304 {
2305 address = mappedBase + offset;
2306 }
2307 else
2308 {
2309 // see how far we can coalesce ranges
2310 while (ind < _rangesCount && address + length == physP[ind].address) {
2311 len = physP[ind].length;
2312 length += len;
2313 off2Ind += len;
2314 ind++;
2315 }
2316 }
2317 // correct contiguous check overshoot
2318 ind--;
2319 off2Ind -= len;
2320 }
2321 #endif /* !__LP64__ */
2322 else do {
2323 if (!_wireCount)
2324 panic("IOGMD: not wired for the IODMACommand");
2325
2326 assert(_memoryEntries);
2327
2328 dataP = getDataP(_memoryEntries);
2329 const ioPLBlock *ioplList = getIOPLList(dataP);
2330 UInt numIOPLs = getNumIOPL(_memoryEntries, dataP);
2331 upl_page_info_t *pageList = getPageList(dataP);
2332
2333 assert(numIOPLs > 0);
2334
2335 // Scan through iopl info blocks looking for block containing offset
2336 while (ind < numIOPLs && offset >= ioplList[ind].fIOMDOffset)
2337 ind++;
2338
2339 // Go back to actual range as search goes past it
2340 ioPLBlock ioplInfo = ioplList[ind - 1];
2341 off2Ind = ioplInfo.fIOMDOffset;
2342
2343 if (ind < numIOPLs)
2344 length = ioplList[ind].fIOMDOffset;
2345 else
2346 length = _length;
2347 length -= offset; // Remainder within iopl
2348
2349 // Subtract offset till this iopl in total list
2350 offset -= off2Ind;
2351
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.
2354 if (mapped) {
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
2358 }
2359
2360 // The offset is rebased into the current iopl.
2361 // Now add the iopl 1st page offset.
2362 offset += ioplInfo.fPageOffset;
2363
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;
2368 else
2369 pageList = &pageList[ioplInfo.fPageInfo];
2370
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
2375 }
2376
2377 // Now we need compute the index into the pageList
2378 UInt pageInd = atop_32(offset);
2379 offset &= PAGE_MASK;
2380
2381 // Compute the starting address of this segment
2382 IOPhysicalAddress pageAddr = pageList[pageInd].phys_addr;
2383 if (!pageAddr) {
2384 panic("!pageList phys_addr");
2385 }
2386
2387 address = ptoa_64(pageAddr) + offset;
2388
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)
2395 {
2396 contigLength += PAGE_SIZE;
2397 }
2398
2399 if (contigLength < length)
2400 length = contigLength;
2401
2402
2403 assert(address);
2404 assert(length);
2405
2406 } while (false);
2407
2408 // Update return values and state
2409 isP->fIO.fIOVMAddr = address;
2410 isP->fIO.fLength = length;
2411 isP->fIndex = ind;
2412 isP->fOffset2Index = off2Ind;
2413 isP->fNextOffset = isP->fIO.fOffset + length;
2414
2415 return kIOReturnSuccess;
2416 }
2417
2418 addr64_t
2419 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset, IOByteCount *lengthOfSegment, IOOptionBits options)
2420 {
2421 IOReturn ret;
2422 mach_vm_address_t address = 0;
2423 mach_vm_size_t length = 0;
2424 IOMapper * mapper = gIOSystemMapper;
2425 IOOptionBits type = _flags & kIOMemoryTypeMask;
2426
2427 if (lengthOfSegment)
2428 *lengthOfSegment = 0;
2429
2430 if (offset >= _length)
2431 return 0;
2432
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
2437
2438 if ((options & _kIOMemorySourceSegment) && (kIOMemoryTypeUPL != type))
2439 {
2440 unsigned rangesIndex = 0;
2441 Ranges vec = _ranges;
2442 mach_vm_address_t addr;
2443
2444 // Find starting address within the vector of ranges
2445 for (;;) {
2446 getAddrLenForInd(addr, length, type, vec, rangesIndex);
2447 if (offset < length)
2448 break;
2449 offset -= length; // (make offset relative)
2450 rangesIndex++;
2451 }
2452
2453 // Now that we have the starting range,
2454 // lets find the last contiguous range
2455 addr += offset;
2456 length -= offset;
2457
2458 for ( ++rangesIndex; rangesIndex < _rangesCount; rangesIndex++ ) {
2459 mach_vm_address_t newAddr;
2460 mach_vm_size_t newLen;
2461
2462 getAddrLenForInd(newAddr, newLen, type, vec, rangesIndex);
2463 if (addr + length != newAddr)
2464 break;
2465 length += newLen;
2466 }
2467 if (addr)
2468 address = (IOPhysicalAddress) addr; // Truncate address to 32bit
2469 }
2470 else
2471 {
2472 IOMDDMAWalkSegmentState _state;
2473 IOMDDMAWalkSegmentArgs * state = (IOMDDMAWalkSegmentArgs *) (void *)&_state;
2474
2475 state->fOffset = offset;
2476 state->fLength = _length - offset;
2477 state->fMapped = (0 == (options & kIOMemoryMapperNone)) && !(_flags & kIOMemoryHostOrRemote);
2478
2479 ret = dmaCommandOperation(kIOMDFirstSegment, _state, sizeof(_state));
2480
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)
2486 {
2487 address = state->fIOVMAddr;
2488 length = state->fLength;
2489 }
2490
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
2493
2494 if (mapper && ((kIOMemoryTypePhysical == type) || (kIOMemoryTypePhysical64 == type)))
2495 {
2496 if ((options & kIOMemoryMapperNone) && !(_flags & kIOMemoryMapperNone))
2497 {
2498 addr64_t origAddr = address;
2499 IOByteCount origLen = length;
2500
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)
2507 length = origLen;
2508 }
2509 }
2510 }
2511
2512 if (!address)
2513 length = 0;
2514
2515 if (lengthOfSegment)
2516 *lengthOfSegment = length;
2517
2518 return (address);
2519 }
2520
2521 #ifndef __LP64__
2522 #pragma clang diagnostic push
2523 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2524
2525 addr64_t
2526 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset, IOByteCount *lengthOfSegment, IOOptionBits options)
2527 {
2528 addr64_t address = 0;
2529
2530 if (options & _kIOMemorySourceSegment)
2531 {
2532 address = getSourceSegment(offset, lengthOfSegment);
2533 }
2534 else if (options & kIOMemoryMapperNone)
2535 {
2536 address = getPhysicalSegment64(offset, lengthOfSegment);
2537 }
2538 else
2539 {
2540 address = getPhysicalSegment(offset, lengthOfSegment);
2541 }
2542
2543 return (address);
2544 }
2545 #pragma clang diagnostic pop
2546
2547 addr64_t
2548 IOGeneralMemoryDescriptor::getPhysicalSegment64(IOByteCount offset, IOByteCount *lengthOfSegment)
2549 {
2550 return (getPhysicalSegment(offset, lengthOfSegment, kIOMemoryMapperNone));
2551 }
2552
2553 IOPhysicalAddress
2554 IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset, IOByteCount *lengthOfSegment)
2555 {
2556 addr64_t address = 0;
2557 IOByteCount length = 0;
2558
2559 address = getPhysicalSegment(offset, lengthOfSegment, 0);
2560
2561 if (lengthOfSegment)
2562 length = *lengthOfSegment;
2563
2564 if ((address + length) > 0x100000000ULL)
2565 {
2566 panic("getPhysicalSegment() out of 32b range 0x%qx, len 0x%lx, class %s",
2567 address, (long) length, (getMetaClass())->getClassName());
2568 }
2569
2570 return ((IOPhysicalAddress) address);
2571 }
2572
2573 addr64_t
2574 IOMemoryDescriptor::getPhysicalSegment64(IOByteCount offset, IOByteCount *lengthOfSegment)
2575 {
2576 IOPhysicalAddress phys32;
2577 IOByteCount length;
2578 addr64_t phys64;
2579 IOMapper * mapper = 0;
2580
2581 phys32 = getPhysicalSegment(offset, lengthOfSegment);
2582 if (!phys32)
2583 return 0;
2584
2585 if (gIOSystemMapper)
2586 mapper = gIOSystemMapper;
2587
2588 if (mapper)
2589 {
2590 IOByteCount origLen;
2591
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)
2599 length = origLen;
2600
2601 *lengthOfSegment = length;
2602 }
2603 else
2604 phys64 = (addr64_t) phys32;
2605
2606 return phys64;
2607 }
2608
2609 IOPhysicalAddress
2610 IOMemoryDescriptor::getPhysicalSegment(IOByteCount offset, IOByteCount *lengthOfSegment)
2611 {
2612 return ((IOPhysicalAddress) getPhysicalSegment(offset, lengthOfSegment, 0));
2613 }
2614
2615 IOPhysicalAddress
2616 IOGeneralMemoryDescriptor::getSourceSegment(IOByteCount offset, IOByteCount *lengthOfSegment)
2617 {
2618 return ((IOPhysicalAddress) getPhysicalSegment(offset, lengthOfSegment, _kIOMemorySourceSegment));
2619 }
2620
2621 #pragma clang diagnostic push
2622 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2623
2624 void * IOGeneralMemoryDescriptor::getVirtualSegment(IOByteCount offset,
2625 IOByteCount * lengthOfSegment)
2626 {
2627 if (_task == kernel_task)
2628 return (void *) getSourceSegment(offset, lengthOfSegment);
2629 else
2630 panic("IOGMD::getVirtualSegment deprecated");
2631
2632 return 0;
2633 }
2634 #pragma clang diagnostic pop
2635 #endif /* !__LP64__ */
2636
2637 IOReturn
2638 IOMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *vData, UInt dataSize) const
2639 {
2640 IOMemoryDescriptor *md = const_cast<IOMemoryDescriptor *>(this);
2641 DMACommandOps params;
2642 IOReturn err;
2643
2644 params = (op & ~kIOMDDMACommandOperationMask & op);
2645 op &= kIOMDDMACommandOperationMask;
2646
2647 if (kIOMDGetCharacteristics == op) {
2648 if (dataSize < sizeof(IOMDDMACharacteristics))
2649 return kIOReturnUnderrun;
2650
2651 IOMDDMACharacteristics *data = (IOMDDMACharacteristics *) vData;
2652 data->fLength = getLength();
2653 data->fSGCount = 0;
2654 data->fDirection = getDirection();
2655 data->fIsPrepared = true; // Assume prepared - fails safe
2656 }
2657 else if (kIOMDWalkSegments == op) {
2658 if (dataSize < sizeof(IOMDDMAWalkSegmentArgs))
2659 return kIOReturnUnderrun;
2660
2661 IOMDDMAWalkSegmentArgs *data = (IOMDDMAWalkSegmentArgs *) vData;
2662 IOByteCount offset = (IOByteCount) data->fOffset;
2663
2664 IOPhysicalLength length;
2665 if (data->fMapped && IOMapper::gSystem)
2666 data->fIOVMAddr = md->getPhysicalSegment(offset, &length);
2667 else
2668 data->fIOVMAddr = md->getPhysicalSegment(offset, &length, kIOMemoryMapperNone);
2669 data->fLength = length;
2670 }
2671 else if (kIOMDAddDMAMapSpec == op) return kIOReturnUnsupported;
2672 else if (kIOMDDMAMap == op)
2673 {
2674 if (dataSize < sizeof(IOMDDMAMapArgs))
2675 return kIOReturnUnderrun;
2676 IOMDDMAMapArgs * data = (IOMDDMAMapArgs *) vData;
2677
2678 if (params) panic("class %s does not support IODMACommand::kIterateOnly", getMetaClass()->getClassName());
2679
2680 data->fMapContig = true;
2681 err = md->dmaMap(data->fMapper, data->fCommand, &data->fMapSpec, data->fOffset, data->fLength, &data->fAlloc, &data->fAllocLength);
2682
2683 return (err);
2684 }
2685 else if (kIOMDDMAUnmap == op)
2686 {
2687 if (dataSize < sizeof(IOMDDMAMapArgs))
2688 return kIOReturnUnderrun;
2689 IOMDDMAMapArgs * data = (IOMDDMAMapArgs *) vData;
2690
2691 err = md->dmaUnmap(data->fMapper, data->fCommand, data->fOffset, data->fAlloc, data->fAllocLength);
2692
2693 return (kIOReturnSuccess);
2694 }
2695 else return kIOReturnBadArgument;
2696
2697 return kIOReturnSuccess;
2698 }
2699
2700 IOReturn
2701 IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState,
2702 IOOptionBits * oldState )
2703 {
2704 IOReturn err = kIOReturnSuccess;
2705
2706 vm_purgable_t control;
2707 int state;
2708
2709 assert (!(kIOMemoryRemote & _flags));
2710 if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
2711
2712 if (_memRef)
2713 {
2714 err = super::setPurgeable(newState, oldState);
2715 }
2716 else
2717 {
2718 if (kIOMemoryThreadSafe & _flags)
2719 LOCK;
2720 do
2721 {
2722 // Find the appropriate vm_map for the given task
2723 vm_map_t curMap;
2724 if (_task == kernel_task && (kIOMemoryBufferPageable & _flags))
2725 {
2726 err = kIOReturnNotReady;
2727 break;
2728 }
2729 else if (!_task)
2730 {
2731 err = kIOReturnUnsupported;
2732 break;
2733 }
2734 else
2735 {
2736 curMap = get_task_map(_task);
2737 if (NULL == curMap)
2738 {
2739 err = KERN_INVALID_ARGUMENT;
2740 break;
2741 }
2742 }
2743
2744 // can only do one range
2745 Ranges vec = _ranges;
2746 IOOptionBits type = _flags & kIOMemoryTypeMask;
2747 mach_vm_address_t addr;
2748 mach_vm_size_t len;
2749 getAddrLenForInd(addr, len, type, vec, 0);
2750
2751 err = purgeableControlBits(newState, &control, &state);
2752 if (kIOReturnSuccess != err)
2753 break;
2754 err = vm_map_purgable_control(curMap, addr, control, &state);
2755 if (oldState)
2756 {
2757 if (kIOReturnSuccess == err)
2758 {
2759 err = purgeableStateBits(&state);
2760 *oldState = state;
2761 }
2762 }
2763 }
2764 while (false);
2765 if (kIOMemoryThreadSafe & _flags)
2766 UNLOCK;
2767 }
2768
2769 return (err);
2770 }
2771
2772 IOReturn IOMemoryDescriptor::setPurgeable( IOOptionBits newState,
2773 IOOptionBits * oldState )
2774 {
2775 IOReturn err = kIOReturnNotReady;
2776
2777 if (kIOMemoryThreadSafe & _flags) LOCK;
2778 if (_memRef) err = IOGeneralMemoryDescriptor::memoryReferenceSetPurgeable(_memRef, newState, oldState);
2779 if (kIOMemoryThreadSafe & _flags) UNLOCK;
2780
2781 return (err);
2782 }
2783
2784 IOReturn IOMemoryDescriptor::getPageCounts( IOByteCount * residentPageCount,
2785 IOByteCount * dirtyPageCount )
2786 {
2787 IOReturn err = kIOReturnNotReady;
2788
2789 assert (!(kIOMemoryRemote & _flags));
2790 if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
2791
2792 if (kIOMemoryThreadSafe & _flags) LOCK;
2793 if (_memRef) err = IOGeneralMemoryDescriptor::memoryReferenceGetPageCounts(_memRef, residentPageCount, dirtyPageCount);
2794 else
2795 {
2796 IOMultiMemoryDescriptor * mmd;
2797 IOSubMemoryDescriptor * smd;
2798 if ((smd = OSDynamicCast(IOSubMemoryDescriptor, this)))
2799 {
2800 err = smd->getPageCounts(residentPageCount, dirtyPageCount);
2801 }
2802 else if ((mmd = OSDynamicCast(IOMultiMemoryDescriptor, this)))
2803 {
2804 err = mmd->getPageCounts(residentPageCount, dirtyPageCount);
2805 }
2806 }
2807 if (kIOMemoryThreadSafe & _flags) UNLOCK;
2808
2809 return (err);
2810 }
2811
2812
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__) */
2820
2821 static void SetEncryptOp(addr64_t pa, unsigned int count)
2822 {
2823 ppnum_t page, end;
2824
2825 page = atop_64(round_page_64(pa));
2826 end = atop_64(trunc_page_64(pa + count));
2827 for (; page < end; page++)
2828 {
2829 pmap_clear_noencrypt(page);
2830 }
2831 }
2832
2833 static void ClearEncryptOp(addr64_t pa, unsigned int count)
2834 {
2835 ppnum_t page, end;
2836
2837 page = atop_64(round_page_64(pa));
2838 end = atop_64(trunc_page_64(pa + count));
2839 for (; page < end; page++)
2840 {
2841 pmap_set_noencrypt(page);
2842 }
2843 }
2844
2845 IOReturn IOMemoryDescriptor::performOperation( IOOptionBits options,
2846 IOByteCount offset, IOByteCount length )
2847 {
2848 IOByteCount remaining;
2849 unsigned int res;
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;
2853 #endif
2854
2855 assert (!(kIOMemoryRemote & _flags));
2856 if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
2857
2858 switch (options)
2859 {
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__ */
2867 break;
2868 #endif /* __ARM_COHERENT_IO__ */
2869 #else /* defined(__arm__) || defined(__arm64__) */
2870 func = &dcache_incoherent_io_flush64;
2871 break;
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__ */
2880 break;
2881 #endif /* __ARM_COHERENT_IO__ */
2882 #else /* defined(__arm__) || defined(__arm64__) */
2883 func = &dcache_incoherent_io_store64;
2884 break;
2885 #endif /* defined(__arm__) || defined(__arm64__) */
2886
2887 case kIOMemorySetEncrypted:
2888 func = &SetEncryptOp;
2889 break;
2890 case kIOMemoryClearEncrypted:
2891 func = &ClearEncryptOp;
2892 break;
2893 }
2894
2895 #if defined(__arm__) || defined(__arm64__)
2896 if ((func == 0) && (func_ext == 0))
2897 return (kIOReturnUnsupported);
2898 #else /* defined(__arm__) || defined(__arm64__) */
2899 if (!func)
2900 return (kIOReturnUnsupported);
2901 #endif /* defined(__arm__) || defined(__arm64__) */
2902
2903 if (kIOMemoryThreadSafe & _flags)
2904 LOCK;
2905
2906 res = 0x0UL;
2907 remaining = length = min(length, getLength() - offset);
2908 while (remaining)
2909 // (process another target segment?)
2910 {
2911 addr64_t dstAddr64;
2912 IOByteCount dstLen;
2913
2914 dstAddr64 = getPhysicalSegment(offset, &dstLen, kIOMemoryMapperNone);
2915 if (!dstAddr64)
2916 break;
2917
2918 // Clip segment length to remaining
2919 if (dstLen > remaining)
2920 dstLen = remaining;
2921
2922 #if defined(__arm__) || defined(__arm64__)
2923 if (func)
2924 (*func)(dstAddr64, dstLen);
2925 if (func_ext) {
2926 (*func_ext)(dstAddr64, dstLen, remaining, &res);
2927 if (res != 0x0UL) {
2928 remaining = 0;
2929 break;
2930 }
2931 }
2932 #else /* defined(__arm__) || defined(__arm64__) */
2933 (*func)(dstAddr64, dstLen);
2934 #endif /* defined(__arm__) || defined(__arm64__) */
2935
2936 offset += dstLen;
2937 remaining -= dstLen;
2938 }
2939
2940 if (kIOMemoryThreadSafe & _flags)
2941 UNLOCK;
2942
2943 return (remaining ? kIOReturnUnderrun : kIOReturnSuccess);
2944 }
2945
2946 /*
2947 *
2948 */
2949
2950 #if defined(__i386__) || defined(__x86_64__)
2951
2952 #define io_kernel_static_start vm_kernel_stext
2953 #define io_kernel_static_end vm_kernel_etext
2954
2955 #elif defined(__arm__) || defined(__arm64__)
2956
2957 extern vm_offset_t static_memory_end;
2958
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__) */
2964
2965 #define io_kernel_static_end static_memory_end
2966
2967 #else
2968 #error io_kernel_static_end is undefined for this architecture
2969 #endif
2970
2971 static kern_return_t
2972 io_get_kernel_static_upl(
2973 vm_map_t /* map */,
2974 uintptr_t offset,
2975 upl_size_t *upl_size,
2976 upl_t *upl,
2977 upl_page_info_array_t page_list,
2978 unsigned int *count,
2979 ppnum_t *highest_page)
2980 {
2981 unsigned int pageCount, page;
2982 ppnum_t phys;
2983 ppnum_t highestPage = 0;
2984
2985 pageCount = atop_32(*upl_size);
2986 if (pageCount > *count)
2987 pageCount = *count;
2988
2989 *upl = NULL;
2990
2991 for (page = 0; page < pageCount; page++)
2992 {
2993 phys = pmap_find_phys(kernel_pmap, ((addr64_t)offset) + ptoa_64(page));
2994 if (!phys)
2995 break;
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)
3003 highestPage = phys;
3004 }
3005
3006 *highest_page = highestPage;
3007
3008 return ((page >= pageCount) ? kIOReturnSuccess : kIOReturnVMError);
3009 }
3010
3011 IOReturn IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection)
3012 {
3013 IOOptionBits type = _flags & kIOMemoryTypeMask;
3014 IOReturn error = kIOReturnSuccess;
3015 ioGMDData *dataP;
3016 upl_page_info_array_t pageInfo;
3017 ppnum_t mapBase;
3018 vm_tag_t tag = VM_KERN_MEMORY_NONE;
3019
3020 assert(kIOMemoryTypeVirtual == type || kIOMemoryTypeVirtual64 == type || kIOMemoryTypeUIO == type);
3021
3022 if ((kIODirectionOutIn & forDirection) == kIODirectionNone)
3023 forDirection = (IODirection) (forDirection | getDirection());
3024
3025 dataP = getDataP(_memoryEntries);
3026 upl_control_flags_t uplFlags; // This Mem Desc's default flags for upl creation
3027 switch (kIODirectionOutIn & forDirection)
3028 {
3029 case kIODirectionOut:
3030 // Pages do not need to be marked as dirty on commit
3031 uplFlags = UPL_COPYOUT_FROM;
3032 dataP->fDMAAccess = kIODMAMapReadAccess;
3033 break;
3034
3035 case kIODirectionIn:
3036 dataP->fDMAAccess = kIODMAMapWriteAccess;
3037 uplFlags = 0; // i.e. ~UPL_COPYOUT_FROM
3038 break;
3039
3040 default:
3041 dataP->fDMAAccess = kIODMAMapReadAccess | kIODMAMapWriteAccess;
3042 uplFlags = 0; // i.e. ~UPL_COPYOUT_FROM
3043 break;
3044 }
3045
3046 if (_wireCount)
3047 {
3048 if ((kIOMemoryPreparedReadOnly & _flags) && !(UPL_COPYOUT_FROM & uplFlags))
3049 {
3050 OSReportWithBacktrace("IOMemoryDescriptor 0x%lx prepared read only", VM_KERNEL_ADDRPERM(this));
3051 error = kIOReturnNotWritable;
3052 }
3053 }
3054 else
3055 {
3056 IOMapper *mapper;
3057
3058 mapper = dataP->fMapper;
3059 dataP->fMappedBaseValid = dataP->fMappedBase = 0;
3060
3061 uplFlags |= UPL_SET_IO_WIRE | UPL_SET_LITE;
3062 tag = _kernelTag;
3063 if (VM_KERN_MEMORY_NONE == tag) tag = IOMemoryTag(kernel_map);
3064
3065 if (kIODirectionPrepareToPhys32 & forDirection)
3066 {
3067 if (!mapper) uplFlags |= UPL_NEED_32BIT_ADDR;
3068 if (dataP->fDMAMapNumAddressBits > 32) dataP->fDMAMapNumAddressBits = 32;
3069 }
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;
3073
3074 mapBase = 0;
3075
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);
3081 dataP = 0;
3082
3083 // Find the appropriate vm_map for the given task
3084 vm_map_t curMap;
3085 if (_task == kernel_task && (kIOMemoryBufferPageable & _flags)) curMap = 0;
3086 else curMap = get_task_map(_task);
3087
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;
3093
3094 IOMemoryEntry * memRefEntry = 0;
3095 if (_memRef) memRefEntry = &_memRef->entries[0];
3096
3097 for (UInt range = 0; range < _rangesCount; range++) {
3098 ioPLBlock iopl;
3099 mach_vm_address_t startPage, startPageOffset;
3100 mach_vm_size_t numBytes;
3101 ppnum_t highPage = 0;
3102
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);
3109
3110 if (mapper)
3111 iopl.fMappedPage = mapBase + pageIndex;
3112 else
3113 iopl.fMappedPage = 0;
3114
3115 // Iterate over the current range, creating UPLs
3116 while (numBytes) {
3117 vm_address_t kernelStart = (vm_address_t) startPage;
3118 vm_map_t theMap;
3119 if (curMap) theMap = curMap;
3120 else if (_memRef)
3121 {
3122 theMap = NULL;
3123 }
3124 else
3125 {
3126 assert(_task == kernel_task);
3127 theMap = IOPageableMapForAddress(kernelStart);
3128 }
3129
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];
3135
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);
3139
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,
3144 kernelStart,
3145 &ioplSize,
3146 &iopl.fIOPL,
3147 baseInfo,
3148 &numPageInfo,
3149 &highPage);
3150 }
3151 else if (_memRef) {
3152 memory_object_offset_t entryOffset;
3153
3154 entryOffset = mdOffset;
3155 entryOffset = (entryOffset - iopl.fPageOffset - memRefEntry->offset);
3156 if (entryOffset >= memRefEntry->size) {
3157 memRefEntry++;
3158 if (memRefEntry >= &_memRef->entries[_memRef->count]) panic("memRefEntry");
3159 entryOffset = 0;
3160 }
3161 if (ioplSize > (memRefEntry->size - entryOffset)) ioplSize = (memRefEntry->size - entryOffset);
3162 error = memory_object_iopl_request(memRefEntry->entry,
3163 entryOffset,
3164 &ioplSize,
3165 &iopl.fIOPL,
3166 baseInfo,
3167 &numPageInfo,
3168 &ioplFlags,
3169 tag);
3170 }
3171 else {
3172 assert(theMap);
3173 error = vm_map_create_upl(theMap,
3174 startPage,
3175 (upl_size_t*)&ioplSize,
3176 &iopl.fIOPL,
3177 baseInfo,
3178 &numPageInfo,
3179 &ioplFlags,
3180 tag);
3181 }
3182
3183 if (error != KERN_SUCCESS) goto abortExit;
3184
3185 assert(ioplSize);
3186
3187 if (iopl.fIOPL)
3188 highPage = upl_get_highest_page(iopl.fIOPL);
3189 if (highPage > highestPage)
3190 highestPage = highPage;
3191
3192 if (baseInfo->device) {
3193 numPageInfo = 1;
3194 iopl.fFlags = kIOPLOnDevice;
3195 }
3196 else {
3197 iopl.fFlags = 0;
3198 }
3199
3200 iopl.fIOMDOffset = mdOffset;
3201 iopl.fPageInfo = pageIndex;
3202 if (mapper && pageIndex && (page_mask & (mdOffset + startPageOffset))) dataP->fDiscontig = true;
3203
3204 if (!_memoryEntries->appendBytes(&iopl, sizeof(iopl))) {
3205 // Clean up partial created and unsaved iopl
3206 if (iopl.fIOPL) {
3207 upl_abort(iopl.fIOPL, 0);
3208 upl_deallocate(iopl.fIOPL);
3209 }
3210 goto abortExit;
3211 }
3212 dataP = 0;
3213
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;
3223 }
3224 else {
3225 mdOffset += numBytes;
3226 break;
3227 }
3228 }
3229 }
3230
3231 _highestPage = highestPage;
3232
3233 if (UPL_COPYOUT_FROM & uplFlags) _flags |= kIOMemoryPreparedReadOnly;
3234 }
3235
3236 #if IOTRACKING
3237 if (!(_flags & kIOMemoryAutoPrepare) && (kIOReturnSuccess == error))
3238 {
3239 dataP = getDataP(_memoryEntries);
3240 if (!dataP->fWireTracking.link.next)
3241 {
3242 IOTrackingAdd(gIOWireTracking, &dataP->fWireTracking, ptoa(_pages), false, tag);
3243 }
3244 }
3245 #endif /* IOTRACKING */
3246
3247 return (error);
3248
3249 abortExit:
3250 {
3251 dataP = getDataP(_memoryEntries);
3252 UInt done = getNumIOPL(_memoryEntries, dataP);
3253 ioPLBlock *ioplList = getIOPLList(dataP);
3254
3255 for (UInt range = 0; range < done; range++)
3256 {
3257 if (ioplList[range].fIOPL) {
3258 upl_abort(ioplList[range].fIOPL, 0);
3259 upl_deallocate(ioplList[range].fIOPL);
3260 }
3261 }
3262 (void) _memoryEntries->initWithBytes(dataP, computeDataSize(0, 0)); // == setLength()
3263 }
3264
3265 if (error == KERN_FAILURE)
3266 error = kIOReturnCannotWire;
3267 else if (error == KERN_MEMORY_ERROR)
3268 error = kIOReturnNoResources;
3269
3270 return error;
3271 }
3272
3273 bool IOGeneralMemoryDescriptor::initMemoryEntries(size_t size, IOMapper * mapper)
3274 {
3275 ioGMDData * dataP;
3276 unsigned dataSize = size;
3277
3278 if (!_memoryEntries) {
3279 _memoryEntries = OSData::withCapacity(dataSize);
3280 if (!_memoryEntries)
3281 return false;
3282 }
3283 else if (!_memoryEntries->initWithCapacity(dataSize))
3284 return false;
3285
3286 _memoryEntries->appendBytes(0, computeDataSize(0, 0));
3287 dataP = getDataP(_memoryEntries);
3288
3289 if (mapper == kIOMapperWaitSystem) {
3290 IOMapper::checkForSystemMapper();
3291 mapper = IOMapper::gSystem;
3292 }
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;
3302
3303 return (true);
3304 }
3305
3306 IOReturn IOMemoryDescriptor::dmaMap(
3307 IOMapper * mapper,
3308 IODMACommand * command,
3309 const IODMAMapSpecification * mapSpec,
3310 uint64_t offset,
3311 uint64_t length,
3312 uint64_t * mapAddress,
3313 uint64_t * mapLength)
3314 {
3315 IOReturn err;
3316 uint32_t mapOptions;
3317
3318 mapOptions = 0;
3319 mapOptions |= kIODMAMapReadAccess;
3320 if (!(kIOMemoryPreparedReadOnly & _flags)) mapOptions |= kIODMAMapWriteAccess;
3321
3322 err = mapper->iovmMapMemory(this, offset, length, mapOptions,
3323 mapSpec, command, NULL, mapAddress, mapLength);
3324
3325 if (kIOReturnSuccess == err) dmaMapRecord(mapper, command, *mapLength);
3326
3327 return (err);
3328 }
3329
3330 void IOMemoryDescriptor::dmaMapRecord(
3331 IOMapper * mapper,
3332 IODMACommand * command,
3333 uint64_t mapLength)
3334 {
3335 kern_allocation_name_t alloc;
3336 int16_t prior;
3337
3338 if ((alloc = mapper->fAllocName) /* && mapper != IOMapper::gSystem */)
3339 {
3340 kern_allocation_update_size(mapper->fAllocName, mapLength);
3341 }
3342
3343 if (!command) return;
3344 prior = OSAddAtomic16(1, &_dmaReferences);
3345 if (!prior)
3346 {
3347 if (alloc && (VM_KERN_MEMORY_NONE != _kernelTag))
3348 {
3349 _mapName = alloc;
3350 mapLength = _length;
3351 kern_allocation_update_subtotal(alloc, _kernelTag, mapLength);
3352 }
3353 else _mapName = NULL;
3354 }
3355 }
3356
3357 IOReturn IOMemoryDescriptor::dmaUnmap(
3358 IOMapper * mapper,
3359 IODMACommand * command,
3360 uint64_t offset,
3361 uint64_t mapAddress,
3362 uint64_t mapLength)
3363 {
3364 IOReturn ret;
3365 kern_allocation_name_t alloc;
3366 kern_allocation_name_t mapName;
3367 int16_t prior;
3368
3369 mapName = 0;
3370 prior = 0;
3371 if (command)
3372 {
3373 mapName = _mapName;
3374 if (_dmaReferences) prior = OSAddAtomic16(-1, &_dmaReferences);
3375 else panic("_dmaReferences underflow");
3376 }
3377
3378 if (!mapLength) return (kIOReturnSuccess);
3379
3380 ret = mapper->iovmUnmapMemory(this, command, mapAddress, mapLength);
3381
3382 if ((alloc = mapper->fAllocName))
3383 {
3384 kern_allocation_update_size(alloc, -mapLength);
3385 if ((1 == prior) && mapName && (VM_KERN_MEMORY_NONE != _kernelTag))
3386 {
3387 mapLength = _length;
3388 kern_allocation_update_subtotal(mapName, _kernelTag, -mapLength);
3389 }
3390 }
3391
3392 return (ret);
3393 }
3394
3395 IOReturn IOGeneralMemoryDescriptor::dmaMap(
3396 IOMapper * mapper,
3397 IODMACommand * command,
3398 const IODMAMapSpecification * mapSpec,
3399 uint64_t offset,
3400 uint64_t length,
3401 uint64_t * mapAddress,
3402 uint64_t * mapLength)
3403 {
3404 IOReturn err = kIOReturnSuccess;
3405 ioGMDData * dataP;
3406 IOOptionBits type = _flags & kIOMemoryTypeMask;
3407
3408 *mapAddress = 0;
3409 if (kIOMemoryHostOnly & _flags) return (kIOReturnSuccess);
3410 if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
3411
3412 if ((type == kIOMemoryTypePhysical) || (type == kIOMemoryTypePhysical64)
3413 || offset || (length != _length))
3414 {
3415 err = super::dmaMap(mapper, command, mapSpec, offset, length, mapAddress, mapLength);
3416 }
3417 else if (_memoryEntries && _pages && (dataP = getDataP(_memoryEntries)))
3418 {
3419 const ioPLBlock * ioplList = getIOPLList(dataP);
3420 upl_page_info_t * pageList;
3421 uint32_t mapOptions = 0;
3422
3423 IODMAMapSpecification mapSpec;
3424 bzero(&mapSpec, sizeof(mapSpec));
3425 mapSpec.numAddressBits = dataP->fDMAMapNumAddressBits;
3426 mapSpec.alignment = dataP->fDMAMapAlignment;
3427
3428 // For external UPLs the fPageInfo field points directly to
3429 // the upl's upl_page_info_t array.
3430 if (ioplList->fFlags & kIOPLExternUPL)
3431 {
3432 pageList = (upl_page_info_t *) ioplList->fPageInfo;
3433 mapOptions |= kIODMAMapPagingPath;
3434 }
3435 else pageList = getPageList(dataP);
3436
3437 if ((_length == ptoa_64(_pages)) && !(page_mask & ioplList->fPageOffset))
3438 {
3439 mapOptions |= kIODMAMapPageListFullyOccupied;
3440 }
3441
3442 assert(dataP->fDMAAccess);
3443 mapOptions |= dataP->fDMAAccess;
3444
3445 // Check for direct device non-paged memory
3446 if (ioplList->fFlags & kIOPLOnDevice) mapOptions |= kIODMAMapPhysicallyContiguous;
3447
3448 IODMAMapPageList dmaPageList =
3449 {
3450 .pageOffset = (uint32_t)(ioplList->fPageOffset & page_mask),
3451 .pageListCount = _pages,
3452 .pageList = &pageList[0]
3453 };
3454 err = mapper->iovmMapMemory(this, offset, length, mapOptions, &mapSpec,
3455 command, &dmaPageList, mapAddress, mapLength);
3456
3457 if (kIOReturnSuccess == err) dmaMapRecord(mapper, command, *mapLength);
3458 }
3459
3460 return (err);
3461 }
3462
3463 /*
3464 * prepare
3465 *
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.
3471 */
3472
3473 IOReturn IOGeneralMemoryDescriptor::prepare(IODirection forDirection)
3474 {
3475 IOReturn error = kIOReturnSuccess;
3476 IOOptionBits type = _flags & kIOMemoryTypeMask;
3477
3478 if ((kIOMemoryTypePhysical == type) || (kIOMemoryTypePhysical64 == type))
3479 return kIOReturnSuccess;
3480
3481 assert (!(kIOMemoryRemote & _flags));
3482 if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
3483
3484 if (_prepareLock) IOLockLock(_prepareLock);
3485
3486 if (kIOMemoryTypeVirtual == type || kIOMemoryTypeVirtual64 == type || kIOMemoryTypeUIO == type)
3487 {
3488 error = wireVirtual(forDirection);
3489 }
3490
3491 if (kIOReturnSuccess == error)
3492 {
3493 if (1 == ++_wireCount)
3494 {
3495 if (kIOMemoryClearEncrypt & _flags)
3496 {
3497 performOperation(kIOMemoryClearEncrypted, 0, _length);
3498 }
3499 }
3500 }
3501
3502 if (_prepareLock) IOLockUnlock(_prepareLock);
3503
3504 return error;
3505 }
3506
3507 /*
3508 * complete
3509 *
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.
3514 */
3515
3516 IOReturn IOGeneralMemoryDescriptor::complete(IODirection forDirection)
3517 {
3518 IOOptionBits type = _flags & kIOMemoryTypeMask;
3519 ioGMDData * dataP;
3520
3521 if ((kIOMemoryTypePhysical == type) || (kIOMemoryTypePhysical64 == type))
3522 return kIOReturnSuccess;
3523
3524 assert (!(kIOMemoryRemote & _flags));
3525 if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
3526
3527 if (_prepareLock) IOLockLock(_prepareLock);
3528 do
3529 {
3530 assert(_wireCount);
3531 if (!_wireCount) break;
3532 dataP = getDataP(_memoryEntries);
3533 if (!dataP) break;
3534
3535 if (kIODirectionCompleteWithError & forDirection) dataP->fCompletionError = true;
3536
3537 if ((kIOMemoryClearEncrypt & _flags) && (1 == _wireCount))
3538 {
3539 performOperation(kIOMemorySetEncrypted, 0, _length);
3540 }
3541
3542 _wireCount--;
3543 if (!_wireCount || (kIODirectionCompleteWithDataValid & forDirection))
3544 {
3545 ioPLBlock *ioplList = getIOPLList(dataP);
3546 UInt ind, count = getNumIOPL(_memoryEntries, dataP);
3547
3548 if (_wireCount)
3549 {
3550 // kIODirectionCompleteWithDataValid & forDirection
3551 if (kIOMemoryTypeVirtual == type || kIOMemoryTypeVirtual64 == type || kIOMemoryTypeUIO == type)
3552 {
3553 vm_tag_t tag;
3554 tag = getVMTag(kernel_map);
3555 for (ind = 0; ind < count; ind++)
3556 {
3557 if (ioplList[ind].fIOPL) iopl_valid_data(ioplList[ind].fIOPL, tag);
3558 }
3559 }
3560 }
3561 else
3562 {
3563 if (_dmaReferences) panic("complete() while dma active");
3564
3565 if (dataP->fMappedBaseValid) {
3566 dmaUnmap(dataP->fMapper, NULL, 0, dataP->fMappedBase, dataP->fMappedLength);
3567 dataP->fMappedBaseValid = dataP->fMappedBase = 0;
3568 }
3569 #if IOTRACKING
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)
3574 {
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*/);
3579 else
3580 upl_commit(ioplList[ind].fIOPL, 0, 0);
3581 upl_deallocate(ioplList[ind].fIOPL);
3582 }
3583 } else if (kIOMemoryTypeUPL == type) {
3584 upl_set_referenced(ioplList[0].fIOPL, false);
3585 }
3586
3587 (void) _memoryEntries->initWithBytes(dataP, computeDataSize(0, 0)); // == setLength()
3588
3589 dataP->fPreparationID = kIOPreparationIDUnprepared;
3590 _flags &= ~kIOMemoryPreparedReadOnly;
3591 }
3592 }
3593 }
3594 while (false);
3595
3596 if (_prepareLock) IOLockUnlock(_prepareLock);
3597
3598 return kIOReturnSuccess;
3599 }
3600
3601 IOReturn IOGeneralMemoryDescriptor::doMap(
3602 vm_map_t __addressMap,
3603 IOVirtualAddress * __address,
3604 IOOptionBits options,
3605 IOByteCount __offset,
3606 IOByteCount __length )
3607 {
3608 #ifndef __LP64__
3609 if (!(kIOMap64Bit & options)) panic("IOGeneralMemoryDescriptor::doMap !64bit");
3610 #endif /* !__LP64__ */
3611
3612 kern_return_t err;
3613
3614 IOMemoryMap * mapping = (IOMemoryMap *) *__address;
3615 mach_vm_size_t offset = mapping->fOffset + __offset;
3616 mach_vm_size_t length = mapping->fLength;
3617
3618 IOOptionBits type = _flags & kIOMemoryTypeMask;
3619 Ranges vec = _ranges;
3620
3621 mach_vm_address_t range0Addr = 0;
3622 mach_vm_size_t range0Len = 0;
3623
3624 if ((offset >= _length) || ((offset + length) > _length))
3625 return( kIOReturnBadArgument );
3626
3627 assert (!(kIOMemoryRemote & _flags));
3628 if (kIOMemoryRemote & _flags) return (0);
3629
3630 if (vec.v)
3631 getAddrLenForInd(range0Addr, range0Len, type, vec, 0);
3632
3633 // mapping source == dest? (could be much better)
3634 if (_task
3635 && (mapping->fAddressTask == _task)
3636 && (mapping->fAddressMap == get_task_map(_task))
3637 && (options & kIOMapAnywhere)
3638 && (1 == _rangesCount)
3639 && (0 == offset)
3640 && range0Addr
3641 && (length <= range0Len))
3642 {
3643 mapping->fAddress = range0Addr;
3644 mapping->fOptions |= kIOMapStatic;
3645
3646 return( kIOReturnSuccess );
3647 }
3648
3649 if (!_memRef)
3650 {
3651 IOOptionBits createOptions = 0;
3652 if (!(kIOMapReadOnly & options))
3653 {
3654 createOptions |= kIOMemoryReferenceWrite;
3655 #if DEVELOPMENT || DEBUG
3656 if (kIODirectionOut == (kIODirectionOutIn & _flags))
3657 {
3658 OSReportWithBacktrace("warning: creating writable mapping from IOMemoryDescriptor(kIODirectionOut) - use kIOMapReadOnly or change direction");
3659 }
3660 #endif
3661 }
3662 err = memoryReferenceCreate(createOptions, &_memRef);
3663 if (kIOReturnSuccess != err) return (err);
3664 }
3665
3666 memory_object_t pager;
3667 pager = (memory_object_t) (reserved ? reserved->dp.devicePager : 0);
3668
3669 // <upl_transpose //
3670 if ((kIOMapReference|kIOMapUnique) == ((kIOMapReference|kIOMapUnique) & options))
3671 {
3672 do
3673 {
3674 upl_t redirUPL2;
3675 upl_size_t size;
3676 upl_control_flags_t flags;
3677 unsigned int lock_count;
3678
3679 if (!_memRef || (1 != _memRef->count))
3680 {
3681 err = kIOReturnNotReadable;
3682 break;
3683 }
3684
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;
3688
3689 if (KERN_SUCCESS != memory_object_iopl_request(_memRef->entries[0].entry, 0, &size, &redirUPL2,
3690 NULL, NULL,
3691 &flags, getVMTag(kernel_map)))
3692 redirUPL2 = NULL;
3693
3694 for (lock_count = 0;
3695 IORecursiveLockHaveLock(gIOMemoryLock);
3696 lock_count++) {
3697 UNLOCK;
3698 }
3699 err = upl_transpose(redirUPL2, mapping->fRedirUPL);
3700 for (;
3701 lock_count;
3702 lock_count--) {
3703 LOCK;
3704 }
3705
3706 if (kIOReturnSuccess != err)
3707 {
3708 IOLog("upl_transpose(%x)\n", err);
3709 err = kIOReturnSuccess;
3710 }
3711
3712 if (redirUPL2)
3713 {
3714 upl_commit(redirUPL2, NULL, 0);
3715 upl_deallocate(redirUPL2);
3716 redirUPL2 = 0;
3717 }
3718 {
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;
3723 }
3724 if (pager)
3725 err = populateDevicePager( pager, mapping->fAddressMap, mapping->fAddress, offset, length, options );
3726 }
3727 while (false);
3728 }
3729 // upl_transpose> //
3730 else
3731 {
3732 err = memoryReferenceMap(_memRef, mapping->fAddressMap, offset, length, options, &mapping->fAddress);
3733 #if IOTRACKING
3734 if ((err == KERN_SUCCESS) && ((kIOTracking & gIOKitDebug) || _task))
3735 {
3736 // only dram maps in the default on developement case
3737 IOTrackingAddUser(gIOMapTracking, &mapping->fTracking, mapping->fLength);
3738 }
3739 #endif /* IOTRACKING */
3740 if ((err == KERN_SUCCESS) && pager)
3741 {
3742 err = populateDevicePager(pager, mapping->fAddressMap, mapping->fAddress, offset, length, options);
3743
3744 if (err != KERN_SUCCESS) doUnmap(mapping->fAddressMap, (IOVirtualAddress) mapping, 0);
3745 else if (kIOMapDefaultCache == (options & kIOMapCacheMask))
3746 {
3747 mapping->fOptions |= ((_flags & kIOMemoryBufferCacheMask) >> kIOMemoryBufferCacheShift);
3748 }
3749 }
3750 }
3751
3752 return (err);
3753 }
3754
3755 #if IOTRACKING
3756 IOReturn
3757 IOMemoryMapTracking(IOTrackingUser * tracking, task_t * task,
3758 mach_vm_address_t * address, mach_vm_size_t * size)
3759 {
3760 #define iomap_offsetof(type, field) ((size_t)(&((type *)0)->field))
3761
3762 IOMemoryMap * map = (typeof(map)) (((uintptr_t) tracking) - iomap_offsetof(IOMemoryMap, fTracking));
3763
3764 if (!map->fAddressMap || (map->fAddressMap != get_task_map(map->fAddressTask))) return (kIOReturnNotReady);
3765
3766 *task = map->fAddressTask;
3767 *address = map->fAddress;
3768 *size = map->fLength;
3769
3770 return (kIOReturnSuccess);
3771 }
3772 #endif /* IOTRACKING */
3773
3774 IOReturn IOGeneralMemoryDescriptor::doUnmap(
3775 vm_map_t addressMap,
3776 IOVirtualAddress __address,
3777 IOByteCount __length )
3778 {
3779 return (super::doUnmap(addressMap, __address, __length));
3780 }
3781
3782 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3783
3784 #undef super
3785 #define super OSObject
3786
3787 OSDefineMetaClassAndStructors( IOMemoryMap, OSObject )
3788
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);
3797
3798 /* ex-inline function implementation */
3799 IOPhysicalAddress IOMemoryMap::getPhysicalAddress()
3800 { return( getPhysicalSegment( 0, 0 )); }
3801
3802 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3803
3804 bool IOMemoryMap::init(
3805 task_t intoTask,
3806 mach_vm_address_t toAddress,
3807 IOOptionBits _options,
3808 mach_vm_size_t _offset,
3809 mach_vm_size_t _length )
3810 {
3811 if (!intoTask)
3812 return( false);
3813
3814 if (!super::init())
3815 return(false);
3816
3817 fAddressMap = get_task_map(intoTask);
3818 if (!fAddressMap)
3819 return(false);
3820 vm_map_reference(fAddressMap);
3821
3822 fAddressTask = intoTask;
3823 fOptions = _options;
3824 fLength = _length;
3825 fOffset = _offset;
3826 fAddress = toAddress;
3827
3828 return (true);
3829 }
3830
3831 bool IOMemoryMap::setMemoryDescriptor(IOMemoryDescriptor * _memory, mach_vm_size_t _offset)
3832 {
3833 if (!_memory)
3834 return(false);
3835
3836 if (!fSuperMap)
3837 {
3838 if( (_offset + fLength) > _memory->getLength())
3839 return( false);
3840 fOffset = _offset;
3841 }
3842
3843 _memory->retain();
3844 if (fMemory)
3845 {
3846 if (fMemory != _memory)
3847 fMemory->removeMapping(this);
3848 fMemory->release();
3849 }
3850 fMemory = _memory;
3851
3852 return( true );
3853 }
3854
3855 IOReturn IOMemoryDescriptor::doMap(
3856 vm_map_t __addressMap,
3857 IOVirtualAddress * __address,
3858 IOOptionBits options,
3859 IOByteCount __offset,
3860 IOByteCount __length )
3861 {
3862 return (kIOReturnUnsupported);
3863 }
3864
3865 IOReturn IOMemoryDescriptor::handleFault(
3866 void * _pager,
3867 mach_vm_size_t sourceOffset,
3868 mach_vm_size_t length)
3869 {
3870 if( kIOMemoryRedirected & _flags)
3871 {
3872 #if DEBUG
3873 IOLog("sleep mem redirect %p, %qx\n", this, sourceOffset);
3874 #endif
3875 do {
3876 SLEEP;
3877 } while( kIOMemoryRedirected & _flags );
3878 }
3879 return (kIOReturnSuccess);
3880 }
3881
3882 IOReturn IOMemoryDescriptor::populateDevicePager(
3883 void * _pager,
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 )
3889 {
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;
3898 addr64_t physAddr;
3899 IOOptionBits type;
3900
3901 type = _flags & kIOMemoryTypeMask;
3902
3903 if (reserved->dp.pagerContig)
3904 {
3905 sourceOffset = 0;
3906 pagerOffset = 0;
3907 }
3908
3909 physAddr = getPhysicalSegment( sourceOffset, &segLen, kIOMemoryMapperNone );
3910 assert( physAddr );
3911 pageOffset = physAddr - trunc_page_64( physAddr );
3912 pagerOffset = sourceOffset;
3913
3914 size = length + pageOffset;
3915 physAddr -= pageOffset;
3916
3917 segLen += pageOffset;
3918 bytes = size;
3919 do
3920 {
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;
3925
3926 if (kIOReturnSuccess != err) break;
3927
3928 #if DEBUG || DEVELOPMENT
3929 if ((kIOMemoryTypeUPL != type)
3930 && pmap_has_managed_page(atop_64(physAddr), atop_64(physAddr + segLen - 1)))
3931 {
3932 OSReportWithBacktrace("IOMemoryDescriptor physical with managed page 0x%qx:0x%qx", physAddr, segLen);
3933 }
3934 #endif /* DEBUG || DEVELOPMENT */
3935
3936 chunk = (reserved->dp.pagerContig ? round_page(segLen) : page_size);
3937 for (page = 0;
3938 (page < segLen) && (KERN_SUCCESS == err);
3939 page += chunk)
3940 {
3941 err = device_pager_populate_object(pager, pagerOffset,
3942 (ppnum_t)(atop_64(physAddr + page)), chunk);
3943 pagerOffset += chunk;
3944 }
3945
3946 assert (KERN_SUCCESS == err);
3947 if (err) break;
3948
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))
3953 {
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,
3958 THREAD_UNINT, NULL,
3959 (vm_map_offset_t)0);
3960
3961 if (KERN_SUCCESS != err) break;
3962 }
3963
3964 sourceOffset += segLen - pageOffset;
3965 address += segLen;
3966 bytes -= segLen;
3967 pageOffset = 0;
3968 }
3969 while (bytes && (physAddr = getPhysicalSegment( sourceOffset, &segLen, kIOMemoryMapperNone )));
3970
3971 if (bytes)
3972 err = kIOReturnBadArgument;
3973
3974 return (err);
3975 }
3976
3977 IOReturn IOMemoryDescriptor::doUnmap(
3978 vm_map_t addressMap,
3979 IOVirtualAddress __address,
3980 IOByteCount __length )
3981 {
3982 IOReturn err;
3983 IOMemoryMap * mapping;
3984 mach_vm_address_t address;
3985 mach_vm_size_t length;
3986
3987 if (__length) panic("doUnmap");
3988
3989 mapping = (IOMemoryMap *) __address;
3990 addressMap = mapping->fAddressMap;
3991 address = mapping->fAddress;
3992 length = mapping->fLength;
3993
3994 if (kIOMapOverwrite & mapping->fOptions) err = KERN_SUCCESS;
3995 else
3996 {
3997 if ((addressMap == kernel_map) && (kIOMemoryBufferPageable & _flags))
3998 addressMap = IOPageableMapForAddress( address );
3999 #if DEBUG
4000 if( kIOLogMapping & gIOKitDebug) IOLog("IOMemoryDescriptor::doUnmap map %p, 0x%qx:0x%qx\n",
4001 addressMap, address, length );
4002 #endif
4003 err = mach_vm_deallocate( addressMap, address, length );
4004 }
4005
4006 #if IOTRACKING
4007 IOTrackingRemoveUser(gIOMapTracking, &mapping->fTracking);
4008 #endif /* IOTRACKING */
4009
4010 return (err);
4011 }
4012
4013 IOReturn IOMemoryDescriptor::redirect( task_t safeTask, bool doRedirect )
4014 {
4015 IOReturn err = kIOReturnSuccess;
4016 IOMemoryMap * mapping = 0;
4017 OSIterator * iter;
4018
4019 LOCK;
4020
4021 if( doRedirect)
4022 _flags |= kIOMemoryRedirected;
4023 else
4024 _flags &= ~kIOMemoryRedirected;
4025
4026 do {
4027 if( (iter = OSCollectionIterator::withCollection( _mappings))) {
4028
4029 memory_object_t pager;
4030
4031 if( reserved)
4032 pager = (memory_object_t) reserved->dp.devicePager;
4033 else
4034 pager = MACH_PORT_NULL;
4035
4036 while( (mapping = (IOMemoryMap *) iter->getNextObject()))
4037 {
4038 mapping->redirect( safeTask, doRedirect );
4039 if (!doRedirect && !safeTask && pager && (kernel_map == mapping->fAddressMap))
4040 {
4041 err = populateDevicePager(pager, mapping->fAddressMap, mapping->fAddress, mapping->fOffset, mapping->fLength, kIOMapDefaultCache );
4042 }
4043 }
4044
4045 iter->release();
4046 }
4047 } while( false );
4048
4049 if (!doRedirect)
4050 {
4051 WAKEUP;
4052 }
4053
4054 UNLOCK;
4055
4056 #ifndef __LP64__
4057 // temporary binary compatibility
4058 IOSubMemoryDescriptor * subMem;
4059 if( (subMem = OSDynamicCast( IOSubMemoryDescriptor, this)))
4060 err = subMem->redirect( safeTask, doRedirect );
4061 else
4062 err = kIOReturnSuccess;
4063 #endif /* !__LP64__ */
4064
4065 return( err );
4066 }
4067
4068 IOReturn IOMemoryMap::redirect( task_t safeTask, bool doRedirect )
4069 {
4070 IOReturn err = kIOReturnSuccess;
4071
4072 if( fSuperMap) {
4073 // err = ((IOMemoryMap *)superMap)->redirect( safeTask, doRedirect );
4074 } else {
4075
4076 LOCK;
4077
4078 do
4079 {
4080 if (!fAddress)
4081 break;
4082 if (!fAddressMap)
4083 break;
4084
4085 if ((!safeTask || (get_task_map(safeTask) != fAddressMap))
4086 && (0 == (fOptions & kIOMapStatic)))
4087 {
4088 IOUnmapPages( fAddressMap, fAddress, fLength );
4089 err = kIOReturnSuccess;
4090 #if DEBUG
4091 IOLog("IOMemoryMap::redirect(%d, %p) 0x%qx:0x%qx from %p\n", doRedirect, this, fAddress, fLength, fAddressMap);
4092 #endif
4093 }
4094 else if (kIOMapWriteCombineCache == (fOptions & kIOMapCacheMask))
4095 {
4096 IOOptionBits newMode;
4097 newMode = (fOptions & ~kIOMapCacheMask) | (doRedirect ? kIOMapInhibitCache : kIOMapWriteCombineCache);
4098 IOProtectCacheMode(fAddressMap, fAddress, fLength, newMode);
4099 }
4100 }
4101 while (false);
4102 UNLOCK;
4103 }
4104
4105 if ((((fMemory->_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical)
4106 || ((fMemory->_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical64))
4107 && safeTask
4108 && (doRedirect != (0 != (fMemory->_flags & kIOMemoryRedirected))))
4109 fMemory->redirect(safeTask, doRedirect);
4110
4111 return( err );
4112 }
4113
4114 IOReturn IOMemoryMap::unmap( void )
4115 {
4116 IOReturn err;
4117
4118 LOCK;
4119
4120 if( fAddress && fAddressMap && (0 == fSuperMap) && fMemory
4121 && (0 == (kIOMapStatic & fOptions))) {
4122
4123 err = fMemory->doUnmap(fAddressMap, (IOVirtualAddress) this, 0);
4124
4125 } else
4126 err = kIOReturnSuccess;
4127
4128 if (fAddressMap)
4129 {
4130 vm_map_deallocate(fAddressMap);
4131 fAddressMap = 0;
4132 }
4133
4134 fAddress = 0;
4135
4136 UNLOCK;
4137
4138 return( err );
4139 }
4140
4141 void IOMemoryMap::taskDied( void )
4142 {
4143 LOCK;
4144 if (fUserClientUnmap) unmap();
4145 #if IOTRACKING
4146 else IOTrackingRemoveUser(gIOMapTracking, &fTracking);
4147 #endif /* IOTRACKING */
4148
4149 if( fAddressMap) {
4150 vm_map_deallocate(fAddressMap);
4151 fAddressMap = 0;
4152 }
4153 fAddressTask = 0;
4154 fAddress = 0;
4155 UNLOCK;
4156 }
4157
4158 IOReturn IOMemoryMap::userClientUnmap( void )
4159 {
4160 fUserClientUnmap = true;
4161 return (kIOReturnSuccess);
4162 }
4163
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
4169 {
4170 LOCK;
4171 super::taggedRelease(tag, 2);
4172 UNLOCK;
4173 }
4174
4175 void IOMemoryMap::free()
4176 {
4177 unmap();
4178
4179 if (fMemory)
4180 {
4181 LOCK;
4182 fMemory->removeMapping(this);
4183 UNLOCK;
4184 fMemory->release();
4185 }
4186
4187 if (fOwner && (fOwner != fMemory))
4188 {
4189 LOCK;
4190 fOwner->removeMapping(this);
4191 UNLOCK;
4192 }
4193
4194 if (fSuperMap)
4195 fSuperMap->release();
4196
4197 if (fRedirUPL) {
4198 upl_commit(fRedirUPL, NULL, 0);
4199 upl_deallocate(fRedirUPL);
4200 }
4201
4202 super::free();
4203 }
4204
4205 IOByteCount IOMemoryMap::getLength()
4206 {
4207 return( fLength );
4208 }
4209
4210 IOVirtualAddress IOMemoryMap::getVirtualAddress()
4211 {
4212 #ifndef __LP64__
4213 if (fSuperMap)
4214 fSuperMap->getVirtualAddress();
4215 else if (fAddressMap
4216 && vm_map_is_64bit(fAddressMap)
4217 && (sizeof(IOVirtualAddress) < 8))
4218 {
4219 OSReportWithBacktrace("IOMemoryMap::getVirtualAddress(0x%qx) called on 64b map; use ::getAddress()", fAddress);
4220 }
4221 #endif /* !__LP64__ */
4222
4223 return (fAddress);
4224 }
4225
4226 #ifndef __LP64__
4227 mach_vm_address_t IOMemoryMap::getAddress()
4228 {
4229 return( fAddress);
4230 }
4231
4232 mach_vm_size_t IOMemoryMap::getSize()
4233 {
4234 return( fLength );
4235 }
4236 #endif /* !__LP64__ */
4237
4238
4239 task_t IOMemoryMap::getAddressTask()
4240 {
4241 if( fSuperMap)
4242 return( fSuperMap->getAddressTask());
4243 else
4244 return( fAddressTask);
4245 }
4246
4247 IOOptionBits IOMemoryMap::getMapOptions()
4248 {
4249 return( fOptions);
4250 }
4251
4252 IOMemoryDescriptor * IOMemoryMap::getMemoryDescriptor()
4253 {
4254 return( fMemory );
4255 }
4256
4257 IOMemoryMap * IOMemoryMap::copyCompatible(
4258 IOMemoryMap * newMapping )
4259 {
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;
4265
4266 if( (!task) || (!fAddressMap) || (fAddressMap != get_task_map(task)))
4267 return( 0 );
4268 if( (fOptions ^ _options) & kIOMapReadOnly)
4269 return( 0 );
4270 if( (kIOMapDefaultCache != (_options & kIOMapCacheMask))
4271 && ((fOptions ^ _options) & kIOMapCacheMask))
4272 return( 0 );
4273
4274 if( (0 == (_options & kIOMapAnywhere)) && (fAddress != toAddress))
4275 return( 0 );
4276
4277 if( _offset < fOffset)
4278 return( 0 );
4279
4280 _offset -= fOffset;
4281
4282 if( (_offset + _length) > fLength)
4283 return( 0 );
4284
4285 retain();
4286 if( (fLength == _length) && (!_offset))
4287 {
4288 newMapping = this;
4289 }
4290 else
4291 {
4292 newMapping->fSuperMap = this;
4293 newMapping->fOffset = fOffset + _offset;
4294 newMapping->fAddress = fAddress + _offset;
4295 }
4296
4297 return( newMapping );
4298 }
4299
4300 IOReturn IOMemoryMap::wireRange(
4301 uint32_t options,
4302 mach_vm_size_t offset,
4303 mach_vm_size_t length)
4304 {
4305 IOReturn kr;
4306 mach_vm_address_t start = trunc_page_64(fAddress + offset);
4307 mach_vm_address_t end = round_page_64(fAddress + offset + length);
4308 vm_prot_t prot;
4309
4310 prot = (kIODirectionOutIn & options);
4311 if (prot)
4312 {
4313 kr = vm_map_wire_kernel(fAddressMap, start, end, prot, fMemory->getVMTag(kernel_map), FALSE);
4314 }
4315 else
4316 {
4317 kr = vm_map_unwire(fAddressMap, start, end, FALSE);
4318 }
4319
4320 return (kr);
4321 }
4322
4323
4324 IOPhysicalAddress
4325 #ifdef __LP64__
4326 IOMemoryMap::getPhysicalSegment( IOByteCount _offset, IOPhysicalLength * _length, IOOptionBits _options)
4327 #else /* !__LP64__ */
4328 IOMemoryMap::getPhysicalSegment( IOByteCount _offset, IOPhysicalLength * _length)
4329 #endif /* !__LP64__ */
4330 {
4331 IOPhysicalAddress address;
4332
4333 LOCK;
4334 #ifdef __LP64__
4335 address = fMemory->getPhysicalSegment( fOffset + _offset, _length, _options );
4336 #else /* !__LP64__ */
4337 address = fMemory->getPhysicalSegment( fOffset + _offset, _length );
4338 #endif /* !__LP64__ */
4339 UNLOCK;
4340
4341 return( address );
4342 }
4343
4344 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4345
4346 #undef super
4347 #define super OSObject
4348
4349 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4350
4351 void IOMemoryDescriptor::initialize( void )
4352 {
4353 if( 0 == gIOMemoryLock)
4354 gIOMemoryLock = IORecursiveLockAlloc();
4355
4356 gIOLastPage = IOGetLastPageNumber();
4357 }
4358
4359 void IOMemoryDescriptor::free( void )
4360 {
4361 if( _mappings) _mappings->release();
4362
4363 if (reserved)
4364 {
4365 IODelete(reserved, IOMemoryDescriptorReserved, 1);
4366 reserved = NULL;
4367 }
4368 super::free();
4369 }
4370
4371 IOMemoryMap * IOMemoryDescriptor::setMapping(
4372 task_t intoTask,
4373 IOVirtualAddress mapAddress,
4374 IOOptionBits options )
4375 {
4376 return (createMappingInTask( intoTask, mapAddress,
4377 options | kIOMapStatic,
4378 0, getLength() ));
4379 }
4380
4381 IOMemoryMap * IOMemoryDescriptor::map(
4382 IOOptionBits options )
4383 {
4384 return (createMappingInTask( kernel_task, 0,
4385 options | kIOMapAnywhere,
4386 0, getLength() ));
4387 }
4388
4389 #ifndef __LP64__
4390 IOMemoryMap * IOMemoryDescriptor::map(
4391 task_t intoTask,
4392 IOVirtualAddress atAddress,
4393 IOOptionBits options,
4394 IOByteCount offset,
4395 IOByteCount length )
4396 {
4397 if ((!(kIOMapAnywhere & options)) && vm_map_is_64bit(get_task_map(intoTask)))
4398 {
4399 OSReportWithBacktrace("IOMemoryDescriptor::map() in 64b task, use ::createMappingInTask()");
4400 return (0);
4401 }
4402
4403 return (createMappingInTask(intoTask, atAddress,
4404 options, offset, length));
4405 }
4406 #endif /* !__LP64__ */
4407
4408 IOMemoryMap * IOMemoryDescriptor::createMappingInTask(
4409 task_t intoTask,
4410 mach_vm_address_t atAddress,
4411 IOOptionBits options,
4412 mach_vm_size_t offset,
4413 mach_vm_size_t length)
4414 {
4415 IOMemoryMap * result;
4416 IOMemoryMap * mapping;
4417
4418 if (0 == length)
4419 length = getLength();
4420
4421 mapping = new IOMemoryMap;
4422
4423 if( mapping
4424 && !mapping->init( intoTask, atAddress,
4425 options, offset, length )) {
4426 mapping->release();
4427 mapping = 0;
4428 }
4429
4430 if (mapping)
4431 result = makeMapping(this, intoTask, (IOVirtualAddress) mapping, options | kIOMap64Bit, 0, 0);
4432 else
4433 result = 0;
4434
4435 #if DEBUG
4436 if (!result)
4437 IOLog("createMappingInTask failed desc %p, addr %qx, options %x, offset %qx, length %llx\n",
4438 this, atAddress, (uint32_t) options, offset, length);
4439 #endif
4440
4441 return (result);
4442 }
4443
4444 #ifndef __LP64__ // there is only a 64 bit version for LP64
4445 IOReturn IOMemoryMap::redirect(IOMemoryDescriptor * newBackingMemory,
4446 IOOptionBits options,
4447 IOByteCount offset)
4448 {
4449 return (redirect(newBackingMemory, options, (mach_vm_size_t)offset));
4450 }
4451 #endif
4452
4453 IOReturn IOMemoryMap::redirect(IOMemoryDescriptor * newBackingMemory,
4454 IOOptionBits options,
4455 mach_vm_size_t offset)
4456 {
4457 IOReturn err = kIOReturnSuccess;
4458 IOMemoryDescriptor * physMem = 0;
4459
4460 LOCK;
4461
4462 if (fAddress && fAddressMap) do
4463 {
4464 if (((fMemory->_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical)
4465 || ((fMemory->_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical64))
4466 {
4467 physMem = fMemory;
4468 physMem->retain();
4469 }
4470
4471 if (!fRedirUPL && fMemory->_memRef && (1 == fMemory->_memRef->count))
4472 {
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,
4477 NULL, NULL,
4478 &flags, fMemory->getVMTag(kernel_map)))
4479 fRedirUPL = 0;
4480
4481 if (physMem)
4482 {
4483 IOUnmapPages( fAddressMap, fAddress, fLength );
4484 if ((false))
4485 physMem->redirect(0, true);
4486 }
4487 }
4488
4489 if (newBackingMemory)
4490 {
4491 if (newBackingMemory != fMemory)
4492 {
4493 fOffset = 0;
4494 if (this != newBackingMemory->makeMapping(newBackingMemory, fAddressTask, (IOVirtualAddress) this,
4495 options | kIOMapUnique | kIOMapReference | kIOMap64Bit,
4496 offset, fLength))
4497 err = kIOReturnError;
4498 }
4499 if (fRedirUPL)
4500 {
4501 upl_commit(fRedirUPL, NULL, 0);
4502 upl_deallocate(fRedirUPL);
4503 fRedirUPL = 0;
4504 }
4505 if ((false) && physMem)
4506 physMem->redirect(0, false);
4507 }
4508 }
4509 while (false);
4510
4511 UNLOCK;
4512
4513 if (physMem)
4514 physMem->release();
4515
4516 return (err);
4517 }
4518
4519 IOMemoryMap * IOMemoryDescriptor::makeMapping(
4520 IOMemoryDescriptor * owner,
4521 task_t __intoTask,
4522 IOVirtualAddress __address,
4523 IOOptionBits options,
4524 IOByteCount __offset,
4525 IOByteCount __length )
4526 {
4527 #ifndef __LP64__
4528 if (!(kIOMap64Bit & options)) panic("IOMemoryDescriptor::makeMapping !64bit");
4529 #endif /* !__LP64__ */
4530
4531 IOMemoryDescriptor * mapDesc = 0;
4532 IOMemoryMap * result = 0;
4533 OSIterator * iter;
4534
4535 IOMemoryMap * mapping = (IOMemoryMap *) __address;
4536 mach_vm_size_t offset = mapping->fOffset + __offset;
4537 mach_vm_size_t length = mapping->fLength;
4538
4539 mapping->fOffset = offset;
4540
4541 LOCK;
4542
4543 do
4544 {
4545 if (kIOMapStatic & options)
4546 {
4547 result = mapping;
4548 addMapping(mapping);
4549 mapping->setMemoryDescriptor(this, 0);
4550 continue;
4551 }
4552
4553 if (kIOMapUnique & options)
4554 {
4555 addr64_t phys;
4556 IOByteCount physLen;
4557
4558 // if (owner != this) continue;
4559
4560 if (((_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical)
4561 || ((_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical64))
4562 {
4563 phys = getPhysicalSegment(offset, &physLen, kIOMemoryMapperNone);
4564 if (!phys || (physLen < length))
4565 continue;
4566
4567 mapDesc = IOMemoryDescriptor::withAddressRange(
4568 phys, length, getDirection() | kIOMemoryMapperNone, NULL);
4569 if (!mapDesc)
4570 continue;
4571 offset = 0;
4572 mapping->fOffset = offset;
4573 }
4574 }
4575 else
4576 {
4577 // look for a compatible existing mapping
4578 if( (iter = OSCollectionIterator::withCollection(_mappings)))
4579 {
4580 IOMemoryMap * lookMapping;
4581 while ((lookMapping = (IOMemoryMap *) iter->getNextObject()))
4582 {
4583 if ((result = lookMapping->copyCompatible(mapping)))
4584 {
4585 addMapping(result);
4586 result->setMemoryDescriptor(this, offset);
4587 break;
4588 }
4589 }
4590 iter->release();
4591 }
4592 if (result || (options & kIOMapReference))
4593 {
4594 if (result != mapping)
4595 {
4596 mapping->release();
4597 mapping = NULL;
4598 }
4599 continue;
4600 }
4601 }
4602
4603 if (!mapDesc)
4604 {
4605 mapDesc = this;
4606 mapDesc->retain();
4607 }
4608 IOReturn
4609 kr = mapDesc->doMap( 0, (IOVirtualAddress *) &mapping, options, 0, 0 );
4610 if (kIOReturnSuccess == kr)
4611 {
4612 result = mapping;
4613 mapDesc->addMapping(result);
4614 result->setMemoryDescriptor(mapDesc, offset);
4615 }
4616 else
4617 {
4618 mapping->release();
4619 mapping = NULL;
4620 }
4621 }
4622 while( false );
4623
4624 UNLOCK;
4625
4626 if (mapDesc)
4627 mapDesc->release();
4628
4629 return (result);
4630 }
4631
4632 void IOMemoryDescriptor::addMapping(
4633 IOMemoryMap * mapping )
4634 {
4635 if( mapping)
4636 {
4637 if( 0 == _mappings)
4638 _mappings = OSSet::withCapacity(1);
4639 if( _mappings )
4640 _mappings->setObject( mapping );
4641 }
4642 }
4643
4644 void IOMemoryDescriptor::removeMapping(
4645 IOMemoryMap * mapping )
4646 {
4647 if( _mappings)
4648 _mappings->removeObject( mapping);
4649 }
4650
4651 #ifndef __LP64__
4652 // obsolete initializers
4653 // - initWithOptions is the designated initializer
4654 bool
4655 IOMemoryDescriptor::initWithAddress(void * address,
4656 IOByteCount length,
4657 IODirection direction)
4658 {
4659 return( false );
4660 }
4661
4662 bool
4663 IOMemoryDescriptor::initWithAddress(IOVirtualAddress address,
4664 IOByteCount length,
4665 IODirection direction,
4666 task_t task)
4667 {
4668 return( false );
4669 }
4670
4671 bool
4672 IOMemoryDescriptor::initWithPhysicalAddress(
4673 IOPhysicalAddress address,
4674 IOByteCount length,
4675 IODirection direction )
4676 {
4677 return( false );
4678 }
4679
4680 bool
4681 IOMemoryDescriptor::initWithRanges(
4682 IOVirtualRange * ranges,
4683 UInt32 withCount,
4684 IODirection direction,
4685 task_t task,
4686 bool asReference)
4687 {
4688 return( false );
4689 }
4690
4691 bool
4692 IOMemoryDescriptor::initWithPhysicalRanges( IOPhysicalRange * ranges,
4693 UInt32 withCount,
4694 IODirection direction,
4695 bool asReference)
4696 {
4697 return( false );
4698 }
4699
4700 void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset,
4701 IOByteCount * lengthOfSegment)
4702 {
4703 return( 0 );
4704 }
4705 #endif /* !__LP64__ */
4706
4707 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4708
4709 bool IOGeneralMemoryDescriptor::serialize(OSSerialize * s) const
4710 {
4711 OSSymbol const *keys[2];
4712 OSObject *values[2];
4713 OSArray * array;
4714
4715 struct SerData {
4716 user_addr_t address;
4717 user_size_t length;
4718 } *vcopy;
4719 unsigned int index, nRanges;
4720 bool result;
4721
4722 IOOptionBits type = _flags & kIOMemoryTypeMask;
4723
4724 if (s == NULL) return false;
4725
4726 array = OSArray::withCapacity(4);
4727 if (!array) return (false);
4728
4729 nRanges = _rangesCount;
4730 vcopy = (SerData *) IOMalloc(sizeof(SerData) * nRanges);
4731 if (vcopy == 0) return false;
4732
4733 keys[0] = OSSymbol::withCString("address");
4734 keys[1] = OSSymbol::withCString("length");
4735
4736 result = false;
4737 values[0] = values[1] = 0;
4738
4739 // From this point on we can go to bail.
4740
4741 // Copy the volatile data so we don't have to allocate memory
4742 // while the lock is held.
4743 LOCK;
4744 if (nRanges == _rangesCount) {
4745 Ranges vec = _ranges;
4746 for (index = 0; index < nRanges; index++) {
4747 mach_vm_address_t addr; mach_vm_size_t len;
4748 getAddrLenForInd(addr, len, type, vec, index);
4749 vcopy[index].address = addr;
4750 vcopy[index].length = len;
4751 }
4752 } else {
4753 // The descriptor changed out from under us. Give up.
4754 UNLOCK;
4755 result = false;
4756 goto bail;
4757 }
4758 UNLOCK;
4759
4760 for (index = 0; index < nRanges; index++)
4761 {
4762 user_addr_t addr = vcopy[index].address;
4763 IOByteCount len = (IOByteCount) vcopy[index].length;
4764 values[0] = OSNumber::withNumber(addr, sizeof(addr) * 8);
4765 if (values[0] == 0) {
4766 result = false;
4767 goto bail;
4768 }
4769 values[1] = OSNumber::withNumber(len, sizeof(len) * 8);
4770 if (values[1] == 0) {
4771 result = false;
4772 goto bail;
4773 }
4774 OSDictionary *dict = OSDictionary::withObjects((const OSObject **)values, (const OSSymbol **)keys, 2);
4775 if (dict == 0) {
4776 result = false;
4777 goto bail;
4778 }
4779 array->setObject(dict);
4780 dict->release();
4781 values[0]->release();
4782 values[1]->release();
4783 values[0] = values[1] = 0;
4784 }
4785
4786 result = array->serialize(s);
4787
4788 bail:
4789 if (array)
4790 array->release();
4791 if (values[0])
4792 values[0]->release();
4793 if (values[1])
4794 values[1]->release();
4795 if (keys[0])
4796 keys[0]->release();
4797 if (keys[1])
4798 keys[1]->release();
4799 if (vcopy)
4800 IOFree(vcopy, sizeof(SerData) * nRanges);
4801
4802 return result;
4803 }
4804
4805 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
4806
4807 OSMetaClassDefineReservedUsed(IOMemoryDescriptor, 0);
4808 #ifdef __LP64__
4809 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 1);
4810 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 2);
4811 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 3);
4812 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 4);
4813 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 5);
4814 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 6);
4815 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 7);
4816 #else /* !__LP64__ */
4817 OSMetaClassDefineReservedUsed(IOMemoryDescriptor, 1);
4818 OSMetaClassDefineReservedUsed(IOMemoryDescriptor, 2);
4819 OSMetaClassDefineReservedUsed(IOMemoryDescriptor, 3);
4820 OSMetaClassDefineReservedUsed(IOMemoryDescriptor, 4);
4821 OSMetaClassDefineReservedUsed(IOMemoryDescriptor, 5);
4822 OSMetaClassDefineReservedUsed(IOMemoryDescriptor, 6);
4823 OSMetaClassDefineReservedUsed(IOMemoryDescriptor, 7);
4824 #endif /* !__LP64__ */
4825 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 8);
4826 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 9);
4827 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 10);
4828 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 11);
4829 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 12);
4830 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 13);
4831 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 14);
4832 OSMetaClassDefineReservedUnused(IOMemoryDescriptor, 15);
4833
4834 /* ex-inline function implementation */
4835 IOPhysicalAddress
4836 IOMemoryDescriptor::getPhysicalAddress()
4837 { return( getPhysicalSegment( 0, 0 )); }