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