]> git.saurik.com Git - apple/xnu.git/blobdiff - iokit/Kernel/IOMemoryDescriptor.cpp
xnu-4903.221.2.tar.gz
[apple/xnu.git] / iokit / Kernel / IOMemoryDescriptor.cpp
index b2bde45a817621c47db05b8a961a6d23e18e660e..3c1c4674b3a38e06bac1bd645fd970b99de7e1a1 100644 (file)
@@ -42,6 +42,7 @@
 
 #include <IOKit/IOKitDebug.h>
 #include <libkern/OSDebug.h>
+#include <libkern/OSKextLibPrivate.h>
 
 #include "IOKitKernelInternal.h"
 
@@ -68,10 +69,6 @@ __BEGIN_DECLS
 extern ppnum_t pmap_find_phys(pmap_t pmap, addr64_t va);
 extern void ipc_port_release_send(ipc_port_t port);
 
-// osfmk/device/iokit_rpc.c
-unsigned int IODefaultCacheBits(addr64_t pa);
-unsigned int  IOTranslateCacheBits(struct phys_entry *pp);
-
 __END_DECLS
 
 #define kIOMapperWaitSystem    ((IOMapper *) 1)
@@ -104,8 +101,6 @@ static IORecursiveLock * gIOMemoryLock;
 #define DEBG(fmt, args...)     {}
 #endif
 
-#define IOMD_DEBUG_DMAACTIVE   1
-
 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
 
 // Some data structures and accessor macros used by the initWithOptions
@@ -142,15 +137,14 @@ struct ioGMDData
     uint64_t    fPreparationID;
 #if IOTRACKING
     IOTracking  fWireTracking;
-    struct vm_tag_set fWireTags;
-    struct vm_tag_set_entry fWireTagsEntries[kMaxWireTags];
 #endif /* IOTRACKING */
     unsigned int      fPageCnt;
     uint8_t          fDMAMapNumAddressBits;
-    vm_tag_t          fAllocTag;
     unsigned char     fDiscontig:1;
     unsigned char     fCompletionError:1;
-    unsigned char     _resv:6;
+    unsigned char     fMappedBaseValid:1;
+    unsigned char     _resv:3;
+    unsigned char     fDMAAccess:2;
 
     /* variable length arrays */
     upl_page_info_t fPageList[1]
@@ -170,6 +164,8 @@ struct ioGMDData
 #define computeDataSize(p, u) \
     (offsetof(ioGMDData, fPageList) + p * sizeof(upl_page_info_t) + u * sizeof(ioPLBlock))
 
+enum { kIOMemoryHostOrRemote = kIOMemoryHostOnly | kIOMemoryRemote };
+
 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
 
 #define next_page(a) ( trunc_page(a) + PAGE_SIZE )
@@ -274,6 +270,14 @@ purgeableControlBits(IOOptionBits newState, vm_purgable_t * control, int * state
            err = kIOReturnBadArgument;
            break;
     }
+
+    if (*control == VM_PURGABLE_SET_STATE) {
+       // let VM know this call is from the kernel and is allowed to alter
+       // the volatility of the memory entry even if it was created with
+       // MAP_MEM_PURGABLE_KERNEL_ONLY
+       *control = VM_PURGABLE_SET_STATE_FROM_KERNEL;
+    }
+
     return (err);
 }
 
@@ -328,6 +332,10 @@ vmProtForCacheMode(IOOptionBits cacheMode)
            SET_MAP_MEM(MAP_MEM_INNERWBACK, prot);
            break;
 
+       case kIOPostedWrite:
+           SET_MAP_MEM(MAP_MEM_POSTED, prot);
+           break;
+
        case kIODefaultCache:
        default:
            SET_MAP_MEM(MAP_MEM_NOOP, prot);
@@ -363,6 +371,10 @@ pagerFlagsForCacheMode(IOOptionBits cacheMode)
            pagerFlags = DEVICE_PAGER_COHERENT;
            break;
 
+       case kIOPostedWrite:
+           pagerFlags = DEVICE_PAGER_CACHE_INHIB |  DEVICE_PAGER_COHERENT | DEVICE_PAGER_GUARDED | DEVICE_PAGER_EARLY_ACK;
+           break;
+
        case kIODefaultCache:
        default:
            pagerFlags = -1U;
@@ -383,17 +395,19 @@ struct IOMemoryEntry
 
 struct IOMemoryReference
 {
-    volatile SInt32 refCount;
-    vm_prot_t       prot;
-    uint32_t        capacity;
-    uint32_t        count;
-    IOMemoryEntry   entries[0];
+    volatile SInt32             refCount;
+    vm_prot_t                   prot;
+    uint32_t                    capacity;
+    uint32_t                    count;
+    struct IOMemoryReference  * mapRef;
+    IOMemoryEntry               entries[0];
 };
 
 enum
 {
     kIOMemoryReferenceReuse = 0x00000001,
     kIOMemoryReferenceWrite = 0x00000002,
+    kIOMemoryReferenceCOW   = 0x00000004,
 };
 
 SInt32 gIOMemoryReferenceCount;
@@ -435,6 +449,12 @@ IOGeneralMemoryDescriptor::memoryReferenceFree(IOMemoryReference * ref)
     IOMemoryEntry * entries;
     size_t          size;
 
+    if (ref->mapRef)
+    {
+       memoryReferenceFree(ref->mapRef);
+       ref->mapRef = 0;
+    }
+
     entries = ref->entries + ref->count;
     while (entries > &ref->entries[0])
     {
@@ -489,10 +509,14 @@ IOGeneralMemoryDescriptor::memoryReferenceCreate(
     tag = getVMTag(kernel_map);
     entries = &ref->entries[0];
     count = 0;
+    err = KERN_SUCCESS;
 
     offset = 0;
     rangeIdx = 0;
-    if (_task) getAddrLenForInd(nextAddr, nextLen, type, _ranges, rangeIdx);
+    if (_task)
+    {
+        getAddrLenForInd(nextAddr, nextLen, type, _ranges, rangeIdx);
+    }
     else
     {
         nextAddr = getPhysicalSegment(offset, &physLen, kIOMemoryMapperNone);
@@ -505,7 +529,9 @@ IOGeneralMemoryDescriptor::memoryReferenceCreate(
            pagerFlags = IODefaultCacheBits(nextAddr);
            if (DEVICE_PAGER_CACHE_INHIB & pagerFlags)
            {
-               if (DEVICE_PAGER_GUARDED & pagerFlags)
+               if (DEVICE_PAGER_EARLY_ACK & pagerFlags)
+                   mode = kIOPostedWrite;
+               else if (DEVICE_PAGER_GUARDED & pagerFlags)
                    mode = kIOInhibitCache;
                else
                    mode = kIOWriteCombineCache;
@@ -526,6 +552,7 @@ IOGeneralMemoryDescriptor::memoryReferenceCreate(
     if (kIODefaultCache != cacheMode)                    prot |= VM_PROT_WRITE;
     if (kIODirectionOut != (kIODirectionOutIn & _flags)) prot |= VM_PROT_WRITE;
     if (kIOMemoryReferenceWrite & options)               prot |= VM_PROT_WRITE;
+    if (kIOMemoryReferenceCOW   & options)               prot |= MAP_MEM_VM_COPY;
 
     if ((kIOMemoryReferenceReuse & options) && _memRef)
     {
@@ -541,7 +568,14 @@ IOGeneralMemoryDescriptor::memoryReferenceCreate(
        {
            // IOBufferMemoryDescriptor alloc - set flags for entry + object create
            prot |= MAP_MEM_NAMED_CREATE;
-           if (kIOMemoryBufferPurgeable & _flags) prot |= MAP_MEM_PURGABLE;
+           if (kIOMemoryBufferPurgeable & _flags)
+           {
+               prot |= (MAP_MEM_PURGABLE | MAP_MEM_PURGABLE_KERNEL_ONLY);
+               if (VM_KERN_MEMORY_SKYWALK == tag)
+               {
+                   prot |= MAP_MEM_LEDGER_TAG_NETWORK;
+               }
+           }
            if (kIOMemoryUseReserve & _flags)      prot |= MAP_MEM_GRAB_SECLUDED;
 
            prot |= VM_PROT_WRITE;
@@ -578,7 +612,7 @@ IOGeneralMemoryDescriptor::memoryReferenceCreate(
                    else                                                  prot &= ~MAP_MEM_NAMED_REUSE;
                }
 
-               err = mach_make_memory_entry_64(map,
+               err = mach_make_memory_entry_internal(map,
                        &actualSize, entryAddr, prot, &entry, cloneEntry);
 
                if (KERN_SUCCESS != err) break;
@@ -650,6 +684,13 @@ IOGeneralMemoryDescriptor::memoryReferenceCreate(
     ref->count = count;
     ref->prot  = prot;
 
+    if (_task && (KERN_SUCCESS == err)
+      && (kIOMemoryMapCopyOnWrite & _flags)
+      && !(kIOMemoryReferenceCOW & options))
+    {
+        err = memoryReferenceCreate(options | kIOMemoryReferenceCOW, &ref->mapRef);
+    }
+
     if (KERN_SUCCESS == err)
     {
        if (MAP_MEM_NAMED_REUSE & prot)
@@ -683,8 +724,9 @@ IOMemoryDescriptorMapAlloc(vm_map_t map, void * _ref)
                                  (vm_map_offset_t) 0,
                                  (((ref->options & kIOMapAnywhere)
                                    ? VM_FLAGS_ANYWHERE
-                                   : VM_FLAGS_FIXED)
-                                  | VM_MAKE_TAG(ref->tag)),
+                                   : VM_FLAGS_FIXED)),
+                                 VM_MAP_KERNEL_FLAGS_NONE,
+                                 ref->tag,
                                  IPC_PORT_NULL,
                                  (memory_object_offset_t) 0,
                                  false, /* copy */
@@ -723,14 +765,19 @@ IOGeneralMemoryDescriptor::memoryReferenceMap(
     IOOptionBits      type;
     IOOptionBits      cacheMode;
     vm_tag_t          tag;
+    // for the kIOMapPrefault option.
+    upl_page_info_t * pageList = NULL;
+    UInt              currentPageIndex = 0;
+    bool              didAlloc;
 
-    /*
-     * For the kIOMapPrefault option.
-     */
-    upl_page_info_t *pageList = NULL;
-    UInt currentPageIndex = 0;
+    if (ref->mapRef)
+    {
+       err = memoryReferenceMap(ref->mapRef, map, inoffset, size, options, inaddr);
+       return (err);
+    }
 
     type = _flags & kIOMemoryTypeMask;
+
     prot = VM_PROT_READ;
     if (!(kIOMapReadOnly & options)) prot |= VM_PROT_WRITE;
     prot &= ref->prot;
@@ -769,7 +816,9 @@ IOGeneralMemoryDescriptor::memoryReferenceMap(
     nextAddr  += remain;
     nextLen   -= remain;
     pageOffset = (page_mask & nextAddr);
-    addr = 0;
+    addr       = 0;
+    didAlloc   = false;
+
     if (!(options & kIOMapAnywhere))
     {
         addr = *inaddr;
@@ -813,11 +862,21 @@ IOGeneralMemoryDescriptor::memoryReferenceMap(
            err = IOMemoryDescriptorMapAlloc(ref.map, &ref);
        if (KERN_SUCCESS == err)
        {
-           addr = ref.mapped;
-           map  = ref.map;
+           addr     = ref.mapped;
+           map      = ref.map;
+           didAlloc = true;
        }
     }
 
+    /*
+     * If the memory is associated with a device pager but doesn't have a UPL,
+     * it will be immediately faulted in through the pager via populateDevicePager().
+     * kIOMapPrefault is redundant in that case, so don't try to use it for UPL
+     * operations.
+     */ 
+    if ((reserved != NULL) && (reserved->dp.devicePager) && (_wireCount != 0))
+        options &= ~kIOMapPrefault;
+
     /*
      * Prefaulting is only possible if we wired the memory earlier. Check the
      * memory type, and the underlying data.
@@ -828,11 +887,9 @@ IOGeneralMemoryDescriptor::memoryReferenceMap(
          * The memory must have been wired by calling ::prepare(), otherwise
          * we don't have the UPL. Without UPLs, pages cannot be pre-faulted
          */
-        assert(map != kernel_map);
         assert(_wireCount != 0);
         assert(_memoryEntries != NULL);
-        if ((map == kernel_map) ||
-            (_wireCount == 0) ||
+        if ((_wireCount == 0) ||
             (_memoryEntries == NULL))
         {
             return kIOReturnBadArgument;
@@ -902,17 +959,23 @@ IOGeneralMemoryDescriptor::memoryReferenceMap(
             chunk = entry->size - entryOffset;
             if (chunk)
             {
+               vm_map_kernel_flags_t vmk_flags;
+
+               vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
+               vmk_flags.vmkf_iokit_acct = TRUE; /* iokit accounting */
+
                 if (chunk > remain) chunk = remain;
                if (options & kIOMapPrefault) 
                {
                     UInt nb_pages = round_page(chunk) / PAGE_SIZE;
+
                     err = vm_map_enter_mem_object_prefault(map,
                                                            &mapAddr,
                                                            chunk, 0 /* mask */, 
-                                                            (VM_FLAGS_FIXED
-                                                           | VM_FLAGS_OVERWRITE
-                                                           | VM_MAKE_TAG(tag)
-                                                           | VM_FLAGS_IOKIT_ACCT), /* iokit accounting */
+                                                          (VM_FLAGS_FIXED
+                                                           | VM_FLAGS_OVERWRITE),
+                                                          vmk_flags,
+                                                          tag,
                                                            entry->entry,
                                                            entryOffset,
                                                            prot, // cur
@@ -930,9 +993,9 @@ IOGeneralMemoryDescriptor::memoryReferenceMap(
                                                   &mapAddr,
                                                   chunk, 0 /* mask */, 
                                                    (VM_FLAGS_FIXED
-                                                  | VM_FLAGS_OVERWRITE
-                                                  | VM_MAKE_TAG(tag)
-                                                  | VM_FLAGS_IOKIT_ACCT), /* iokit accounting */
+                                                   | VM_FLAGS_OVERWRITE),
+                                                 vmk_flags,
+                                                 tag,
                                                   entry->entry,
                                                   entryOffset,
                                                   false, // copy
@@ -956,7 +1019,7 @@ IOGeneralMemoryDescriptor::memoryReferenceMap(
             }
         }
 
-    if ((KERN_SUCCESS != err) && addr && !(kIOMapOverwrite & options))
+    if ((KERN_SUCCESS != err) && didAlloc)
     {
         (void) mach_vm_deallocate(map, trunc_page_64(addr), size);
         addr = 0;
@@ -1014,7 +1077,7 @@ IOGeneralMemoryDescriptor::memoryReferenceSetPurgeable(
 
        err = purgeableControlBits(newState, &control, &state);
        if (KERN_SUCCESS != err) break;
-       err = mach_memory_entry_purgable_control(entries->entry, control, &state);
+       err = memory_entry_purgeable_control_internal(entries->entry, control, &state);
        if (KERN_SUCCESS != err) break;
        err = purgeableStateBits(&state);
        if (KERN_SUCCESS != err) break;
@@ -1441,7 +1504,7 @@ IOGeneralMemoryDescriptor::initWithOptions(void * buffers,
     }
 
     // Grab the appropriate mapper
-    if (kIOMemoryHostOnly & options) options |= kIOMemoryMapperNone;
+    if (kIOMemoryHostOrRemote & options) options |= kIOMemoryMapperNone;
     if (kIOMemoryMapperNone & options)
         mapper = 0;    // No Mapper
     else if (mapper == kIOMapperSystem) {
@@ -1449,12 +1512,6 @@ IOGeneralMemoryDescriptor::initWithOptions(void *        buffers,
         gIOSystemMapper = mapper = IOMapper::gSystem;
     }
 
-    // Temp binary compatibility for kIOMemoryThreadSafe
-    if (kIOMemoryReserved6156215 & options)
-    {
-       options &= ~kIOMemoryReserved6156215;
-       options |= kIOMemoryThreadSafe;
-    }
     // Remove the dynamic internal use flags from the initial setting
     options              &= ~(kIOMemoryPreparedReadOnly);
     _flags                = options;
@@ -1464,6 +1521,7 @@ IOGeneralMemoryDescriptor::initWithOptions(void * buffers,
     _direction             = (IODirection) (_flags & kIOMemoryDirectionMask);
 #endif /* !__LP64__ */
 
+    _dmaReferences = 0;
     __iomd_reservedA = 0;
     __iomd_reservedB = 0;
     _highestPage = 0;
@@ -1487,7 +1545,20 @@ IOGeneralMemoryDescriptor::initWithOptions(void *        buffers,
         if (!initMemoryEntries(dataSize, mapper)) return (false);
         dataP = getDataP(_memoryEntries);
         dataP->fPageCnt = 0;
-
+       switch (kIOMemoryDirectionMask & options)
+       {
+           case kIODirectionOut:
+               dataP->fDMAAccess = kIODMAMapReadAccess;
+               break;
+           case kIODirectionIn:
+               dataP->fDMAAccess = kIODMAMapWriteAccess;
+               break;
+           case kIODirectionNone:
+           case kIODirectionOutIn:
+           default:
+               panic("bad dir for upl 0x%x\n", (int) options);
+               break;
+       }
  //       _wireCount++;        // UPLs start out life wired
 
         _length    = count;
@@ -1546,7 +1617,9 @@ IOGeneralMemoryDescriptor::initWithOptions(void * buffers,
              case kIOMemoryTypeVirtual64:
              case kIOMemoryTypePhysical64:
                if (count == 1
+#ifndef __arm__
                    && (((IOAddressRange *) buffers)->address + ((IOAddressRange *) buffers)->length) <= 0x100000000ULL
+#endif
                    ) {
                    if (kIOMemoryTypeVirtual64 == type)
                        type = kIOMemoryTypeVirtual;
@@ -1582,6 +1655,7 @@ IOGeneralMemoryDescriptor::initWithOptions(void * buffers,
                break;
            }
        } 
+       _rangesCount = count;
 
        // Find starting address within the vector of ranges
        Ranges vec = _ranges;
@@ -1609,10 +1683,11 @@ IOGeneralMemoryDescriptor::initWithOptions(void *       buffers,
 
        _length      = totalLength;
        _pages       = pages;
-       _rangesCount = count;
 
         // Auto-prepare memory at creation time.
         // Implied completion when descriptor is free-ed
+
+
         if ((kIOMemoryTypePhysical == type) || (kIOMemoryTypePhysical64 == type))
             _wireCount++;      // Physical MDs are, by definition, wired
         else { /* kIOMemoryTypeVirtual | kIOMemoryTypeVirtual64 | kIOMemoryTypeUIO */
@@ -1626,6 +1701,13 @@ IOGeneralMemoryDescriptor::initWithOptions(void *        buffers,
             dataP = getDataP(_memoryEntries);
             dataP->fPageCnt = _pages;
 
+            if (((_task != kernel_task) || (kIOMemoryBufferPageable & _flags))
+             && (VM_KERN_MEMORY_NONE == _kernelTag))
+            {
+               _kernelTag = IOMemoryTag(kernel_map);
+                if (_kernelTag == gIOSurfaceTag) _userTag = VM_MEMORY_IOSURFACE;
+            }
+
            if ( (kIOMemoryPersistent & _flags) && !_memRef)
            {
                IOReturn 
@@ -1660,10 +1742,10 @@ void IOGeneralMemoryDescriptor::free()
     if ((kIOMemoryTypePhysical == type) || (kIOMemoryTypePhysical64 == type))
     {
        ioGMDData * dataP;
-       if (_memoryEntries && (dataP = getDataP(_memoryEntries)) && dataP->fMappedBase)
+       if (_memoryEntries && (dataP = getDataP(_memoryEntries)) && dataP->fMappedBaseValid)
        {
-           dataP->fMapper->iovmUnmapMemory(this, NULL, dataP->fMappedBase, dataP->fMappedLength);
-           dataP->fMappedBase = 0;
+           dmaUnmap(dataP->fMapper, NULL, 0, dataP->fMappedBase, dataP->fMappedLength);
+           dataP->fMappedBaseValid = dataP->fMappedBase = 0;
        }
     }
     else
@@ -1752,6 +1834,11 @@ IOOptionBits IOMemoryDescriptor::getTag( void )
     return( _tag);
 }
 
+uint64_t IOMemoryDescriptor::getFlags(void)
+{
+    return (_flags);
+}
+
 #ifndef __LP64__
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
@@ -1788,6 +1875,9 @@ IOByteCount IOMemoryDescriptor::readBytes
         return 0;
     }
 
+    assert (!(kIOMemoryRemote & _flags));
+    if (kIOMemoryRemote & _flags) return (0);
+
     if (kIOMemoryThreadSafe & _flags)
        LOCK;
 
@@ -1839,6 +1929,9 @@ IOByteCount IOMemoryDescriptor::writeBytes
         return 0;
     }
 
+    assert (!(kIOMemoryRemote & _flags));
+    if (kIOMemoryRemote & _flags) return (0);
+
     if (kIOMemoryThreadSafe & _flags)
        LOCK;
 
@@ -1871,7 +1964,11 @@ IOByteCount IOMemoryDescriptor::writeBytes
 
     assert(!remaining);
 
+#if defined(__x86_64__)
+    // copypv does not cppvFsnk on intel
+#else
     if (!srcAddr) performOperation(kIOMemoryIncoherentIOFlush, inoffset, length);
+#endif
 
     return length - remaining;
 }
@@ -1939,22 +2036,21 @@ uint64_t IOMemoryDescriptor::getPreparationID( void )
 
 void IOMemoryDescriptor::setVMTags(vm_tag_t kernelTag, vm_tag_t userTag)
 {
-    if (!getKernelReserved()) return;
-    reserved->kernelTag = kernelTag;
-    reserved->userTag   = userTag;
+    _kernelTag = kernelTag;
+    _userTag   = userTag;
 }
 
 vm_tag_t IOMemoryDescriptor::getVMTag(vm_map_t map)
 {
-    if (!reserved
-      || (VM_KERN_MEMORY_NONE == reserved->kernelTag)
-      || (VM_KERN_MEMORY_NONE == reserved->userTag))
+    if (vm_kernel_map_is_kernel(map))
     {
-        return (IOMemoryTag(map));
+         if (VM_KERN_MEMORY_NONE != _kernelTag) return (_kernelTag);
     }
-
-    if (vm_kernel_map_is_kernel(map)) return (reserved->kernelTag);
-    return (reserved->userTag);
+    else
+    {
+         if (VM_KERN_MEMORY_NONE != _userTag)   return (_userTag);
+    }
+    return (IOMemoryTag(map));
 }
 
 IOReturn IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *vData, UInt dataSize) const
@@ -1988,32 +2084,47 @@ IOReturn IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *
            keepMap = (data->fMapper == gIOSystemMapper);
            keepMap &= ((data->fOffset == 0) && (data->fLength == _length));
 
+           if ((data->fMapper == gIOSystemMapper) && _prepareLock) IOLockLock(_prepareLock);
+
            remap = (!keepMap);
            remap |= (dataP->fDMAMapNumAddressBits < 64)
                  && ((dataP->fMappedBase + _length) > (1ULL << dataP->fDMAMapNumAddressBits));
            remap |= (dataP->fDMAMapAlignment > page_size);
 
-           if (remap || !dataP->fMappedBase)
+           if (remap || !dataP->fMappedBaseValid)
            {
-//             if (dataP->fMappedBase) OSReportWithBacktrace("kIOMDDMAMap whole %d remap %d params %d\n", whole, remap, params);
+//             if (dataP->fMappedBaseValid) OSReportWithBacktrace("kIOMDDMAMap whole %d remap %d params %d\n", whole, remap, params);
                err = md->dmaMap(data->fMapper, data->fCommand, &data->fMapSpec, data->fOffset, data->fLength, &data->fAlloc, &data->fAllocLength);
-               if (keepMap && (kIOReturnSuccess == err) && !dataP->fMappedBase)
+               if (keepMap && (kIOReturnSuccess == err) && !dataP->fMappedBaseValid)
                {
-                   dataP->fMappedBase   = data->fAlloc;
-                   dataP->fMappedLength = data->fAllocLength;
-                   data->fAllocLength   = 0;                   // IOMD owns the alloc now
+                   dataP->fMappedBase      = data->fAlloc;
+                   dataP->fMappedBaseValid = true;
+                   dataP->fMappedLength    = data->fAllocLength;
+                   data->fAllocLength      = 0;                        // IOMD owns the alloc now
                }
            }
            else
            {
                data->fAlloc = dataP->fMappedBase;
                data->fAllocLength = 0;                         // give out IOMD map
+               md->dmaMapRecord(data->fMapper, data->fCommand, dataP->fMappedLength);
            }
            data->fMapContig = !dataP->fDiscontig;
-       }
 
+           if ((data->fMapper == gIOSystemMapper) && _prepareLock) IOLockUnlock(_prepareLock);
+       }
        return (err);                           
     }
+    if (kIOMDDMAUnmap == op)
+    {
+        if (dataSize < sizeof(IOMDDMAMapArgs))
+            return kIOReturnUnderrun;
+        IOMDDMAMapArgs * data = (IOMDDMAMapArgs *) vData;
+
+        err = md->dmaUnmap(data->fMapper, data->fCommand, data->fOffset, data->fAlloc, data->fAllocLength);
+
+        return kIOReturnSuccess;
+    }
 
     if (kIOMDAddDMAMapSpec == op)
     {
@@ -2061,9 +2172,24 @@ IOReturn IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *
            }
        }
 
-       return kIOReturnSuccess;
+        return kIOReturnSuccess;
+    }
 
-    } else if (kIOMDWalkSegments != op)
+    else if (kIOMDDMAActive == op)
+    {
+        if (params)
+        {
+           int16_t prior;
+           prior = OSAddAtomic16(1, &md->_dmaReferences);
+           if (!prior) md->_mapName = NULL;
+        }
+        else
+        {
+            if (md->_dmaReferences) OSAddAtomic16(-1, &md->_dmaReferences);
+            else                    panic("_dmaReferences underflow");
+        }
+    }
+    else if (kIOMDWalkSegments != op)
        return kIOReturnBadArgument;
 
     // Get the next segment
@@ -2080,12 +2206,15 @@ IOReturn IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *
 
     isP = (InternalState *) vData;
     UInt offset = isP->fIO.fOffset;
-    bool mapped = isP->fIO.fMapped;
+    uint8_t mapped = isP->fIO.fMapped;
+    uint64_t mappedBase;
+
+    if (mapped && (kIOMemoryRemote & _flags)) return (kIOReturnNotAttached);
 
     if (IOMapper::gSystem && mapped
         && (!(kIOMemoryHostOnly & _flags))
-       && (!_memoryEntries || !getDataP(_memoryEntries)->fMappedBase))
-//     && (_memoryEntries && !getDataP(_memoryEntries)->fMappedBase))
+       && (!_memoryEntries || !getDataP(_memoryEntries)->fMappedBaseValid))
+//     && (_memoryEntries && !getDataP(_memoryEntries)->fMappedBaseValid))
     {
        if (!_memoryEntries 
            && !md->initMemoryEntries(computeDataSize(0, 0), kIOMapperWaitSystem)) return (kIOReturnNoMemory);
@@ -2099,9 +2228,24 @@ IOReturn IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *
            mapSpec.alignment = dataP->fDMAMapAlignment;
            err = md->dmaMap(dataP->fMapper, NULL, &mapSpec, 0, _length, &dataP->fMappedBase, &dataP->fMappedLength);
            if (kIOReturnSuccess != err) return (err);
+           dataP->fMappedBaseValid = true;
        }
     }
 
+    if (kIOMDDMAWalkMappedLocal == mapped) mappedBase = isP->fIO.fMappedBase;
+    else if (mapped)
+    {
+       if (IOMapper::gSystem
+               && (!(kIOMemoryHostOnly & _flags))
+               && _memoryEntries
+               && (dataP = getDataP(_memoryEntries))
+               && dataP->fMappedBaseValid)
+       {
+           mappedBase = dataP->fMappedBase;
+       }
+       else mapped = 0;
+    }
+
     if (offset >= _length)
        return (offset == _length)? kIOReturnOverrun : kIOReturnInternalError;
 
@@ -2117,7 +2261,6 @@ IOReturn IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *
     UInt length;
     UInt64 address;
 
-
     if ( (_flags & kIOMemoryTypeMask) == kIOMemoryTypePhysical) {
 
        // Physical address based memory descriptor
@@ -2134,10 +2277,9 @@ IOReturn IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *
        length   = off2Ind - offset;
        address  = physP[ind - 1].address + len - length;
 
-       if (true && mapped && _memoryEntries 
-               && (dataP = getDataP(_memoryEntries)) && dataP->fMappedBase)
+       if (true && mapped)
        {
-           address = dataP->fMappedBase + offset;
+           address = mappedBase + offset;
        }
        else
        {
@@ -2171,10 +2313,9 @@ IOReturn IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *
        length   = off2Ind - offset;
        address  = physP[ind - 1].address + len - length;
 
-       if (true && mapped && _memoryEntries 
-               && (dataP = getDataP(_memoryEntries)) && dataP->fMappedBase)
+       if (true && mapped)
        {
-           address = dataP->fMappedBase + offset;
+           address = mappedBase + offset;
        }
        else
        {
@@ -2223,9 +2364,9 @@ IOReturn IOGeneralMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *
 
        // If a mapped address is requested and this is a pre-mapped IOPL
        // then just need to compute an offset relative to the mapped base.
-       if (mapped && dataP->fMappedBase) {
+       if (mapped) {
            offset += (ioplInfo.fPageOffset & PAGE_MASK);
-           address = trunc_page_64(dataP->fMappedBase) + ptoa_64(ioplInfo.fMappedPage) + offset;
+           address = trunc_page_64(mappedBase) + ptoa_64(ioplInfo.fMappedPage) + offset;
            continue;   // Done leave do/while(false) now
        }
 
@@ -2346,7 +2487,7 @@ IOGeneralMemoryDescriptor::getPhysicalSegment(IOByteCount offset, IOByteCount *l
 
        state->fOffset = offset;
        state->fLength = _length - offset;
-       state->fMapped = (0 == (options & kIOMemoryMapperNone)) && !(_flags & kIOMemoryHostOnly);
+       state->fMapped = (0 == (options & kIOMemoryMapperNone)) && !(_flags & kIOMemoryHostOrRemote);
 
        ret = dmaCommandOperation(kIOMDFirstSegment, _state, sizeof(_state));
 
@@ -2551,8 +2692,19 @@ IOMemoryDescriptor::dmaCommandOperation(DMACommandOps op, void *vData, UInt data
 
        data->fMapContig = true;
        err = md->dmaMap(data->fMapper, data->fCommand, &data->fMapSpec, data->fOffset, data->fLength, &data->fAlloc, &data->fAllocLength);
+
        return (err);                           
     }
+    else if (kIOMDDMAUnmap == op)
+    {
+        if (dataSize < sizeof(IOMDDMAMapArgs))
+            return kIOReturnUnderrun;
+        IOMDDMAMapArgs * data = (IOMDDMAMapArgs *) vData;
+
+        err = md->dmaUnmap(data->fMapper, data->fCommand, data->fOffset, data->fAlloc, data->fAllocLength);
+
+        return (kIOReturnSuccess);
+    }
     else return kIOReturnBadArgument;
 
     return kIOReturnSuccess;
@@ -2567,6 +2719,9 @@ IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState,
     vm_purgable_t control;
     int           state;
 
+    assert (!(kIOMemoryRemote & _flags));
+    if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
+
     if (_memRef)
     {
        err = super::setPurgeable(newState, oldState);
@@ -2590,7 +2745,14 @@ IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState,
                break;
            }
            else
+           {
                curMap = get_task_map(_task);
+               if (NULL == curMap)
+               {
+                   err = KERN_INVALID_ARGUMENT;
+                   break;
+               }
+           }
 
            // can only do one range
            Ranges vec = _ranges;
@@ -2602,7 +2764,7 @@ IOGeneralMemoryDescriptor::setPurgeable( IOOptionBits newState,
            err = purgeableControlBits(newState, &control, &state);
            if (kIOReturnSuccess != err)
                break;
-           err = mach_vm_purgable_control(curMap, addr, control, &state);
+           err = vm_map_purgable_control(curMap, addr, control, &state);
            if (oldState)
            {
                if (kIOReturnSuccess == err)
@@ -2637,6 +2799,9 @@ IOReturn IOMemoryDescriptor::getPageCounts( IOByteCount * residentPageCount,
 {
     IOReturn err = kIOReturnNotReady;
 
+    assert (!(kIOMemoryRemote & _flags));
+    if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
+
     if (kIOMemoryThreadSafe & _flags) LOCK;
     if (_memRef) err = IOGeneralMemoryDescriptor::memoryReferenceGetPageCounts(_memRef, residentPageCount, dirtyPageCount);
     else
@@ -2658,8 +2823,13 @@ IOReturn IOMemoryDescriptor::getPageCounts( IOByteCount * residentPageCount,
 }
  
 
+#if defined(__arm__) || defined(__arm64__)
+extern "C" void dcache_incoherent_io_flush64(addr64_t pa, unsigned int count, unsigned int remaining, unsigned int *res);
+extern "C" void dcache_incoherent_io_store64(addr64_t pa, unsigned int count, unsigned int remaining, unsigned int *res);
+#else /* defined(__arm__) || defined(__arm64__) */
 extern "C" void dcache_incoherent_io_flush64(addr64_t pa, unsigned int count);
 extern "C" void dcache_incoherent_io_store64(addr64_t pa, unsigned int count);
+#endif /* defined(__arm__) || defined(__arm64__) */
 
 static void SetEncryptOp(addr64_t pa, unsigned int count)
 {
@@ -2691,15 +2861,41 @@ IOReturn IOMemoryDescriptor::performOperation( IOOptionBits options,
     IOByteCount remaining;
     unsigned int res;
     void (*func)(addr64_t pa, unsigned int count) = 0;
+#if defined(__arm__) || defined(__arm64__)
+    void (*func_ext)(addr64_t pa, unsigned int count, unsigned int remaining, unsigned int *result) = 0;
+#endif
+
+    assert (!(kIOMemoryRemote & _flags));
+    if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
 
     switch (options)
     {
         case kIOMemoryIncoherentIOFlush:
+#if defined(__arm__) || defined(__arm64__)
+            func_ext = &dcache_incoherent_io_flush64;
+#if __ARM_COHERENT_IO__
+            func_ext(0, 0, 0, &res);
+            return kIOReturnSuccess;
+#else /* __ARM_COHERENT_IO__ */
+            break;
+#endif /* __ARM_COHERENT_IO__ */
+#else /* defined(__arm__) || defined(__arm64__) */
             func = &dcache_incoherent_io_flush64;
             break;
+#endif /* defined(__arm__) || defined(__arm64__) */
         case kIOMemoryIncoherentIOStore:
+#if defined(__arm__) || defined(__arm64__)
+            func_ext = &dcache_incoherent_io_store64;
+#if __ARM_COHERENT_IO__
+            func_ext(0, 0, 0, &res);
+            return kIOReturnSuccess;
+#else /* __ARM_COHERENT_IO__ */
+            break;
+#endif /* __ARM_COHERENT_IO__ */
+#else /* defined(__arm__) || defined(__arm64__) */
             func = &dcache_incoherent_io_store64;
             break;
+#endif /* defined(__arm__) || defined(__arm64__) */
 
         case kIOMemorySetEncrypted:
             func = &SetEncryptOp;
@@ -2709,8 +2905,13 @@ IOReturn IOMemoryDescriptor::performOperation( IOOptionBits options,
             break;
     }
 
+#if defined(__arm__) || defined(__arm64__)
+    if ((func == 0) && (func_ext == 0))
+        return (kIOReturnUnsupported);
+#else /* defined(__arm__) || defined(__arm64__) */
     if (!func)
         return (kIOReturnUnsupported);
+#endif /* defined(__arm__) || defined(__arm64__) */
 
     if (kIOMemoryThreadSafe & _flags)
        LOCK;
@@ -2731,7 +2932,19 @@ IOReturn IOMemoryDescriptor::performOperation( IOOptionBits options,
         if (dstLen > remaining)
             dstLen = remaining;
 
+#if defined(__arm__) || defined(__arm64__)
+        if (func)
+            (*func)(dstAddr64, dstLen);
+        if (func_ext) {
+            (*func_ext)(dstAddr64, dstLen, remaining, &res);
+            if (res != 0x0UL) {
+                remaining = 0;
+                break;
+            }
+        }
+#else /* defined(__arm__) || defined(__arm64__) */
        (*func)(dstAddr64, dstLen);
+#endif /* defined(__arm__) || defined(__arm64__) */
 
         offset    += dstLen;
         remaining -= dstLen;
@@ -2752,6 +2965,18 @@ IOReturn IOMemoryDescriptor::performOperation( IOOptionBits options,
 #define io_kernel_static_start vm_kernel_stext
 #define io_kernel_static_end   vm_kernel_etext
 
+#elif defined(__arm__) || defined(__arm64__)
+
+extern vm_offset_t             static_memory_end;
+
+#if defined(__arm64__)
+#define io_kernel_static_start vm_kext_base
+#else /* defined(__arm64__) */
+#define io_kernel_static_start vm_kernel_stext
+#endif /* defined(__arm64__) */
+
+#define io_kernel_static_end   static_memory_end
+
 #else
 #error io_kernel_static_end is undefined for this architecture
 #endif
@@ -2796,43 +3021,6 @@ io_get_kernel_static_upl(
     return ((page >= pageCount) ? kIOReturnSuccess : kIOReturnVMError);
 }
 
-/*
- *
- */
-#if IOTRACKING
-static void
-IOMemoryDescriptorUpdateWireOwner(ioGMDData * dataP, OSData * memoryEntries, vm_tag_t tag)
-{
-    ioPLBlock *ioplList;
-    UInt ind, count;
-    vm_tag_t prior;
-
-    count = getNumIOPL(memoryEntries, dataP);
-    if (!count) return;
-    ioplList = getIOPLList(dataP);
-
-    if (VM_KERN_MEMORY_NONE == tag) tag = dataP->fAllocTag;
-    assert(VM_KERN_MEMORY_NONE != tag);
-
-    for (ind = 0; ind < count; ind++)
-    {
-        if (!ioplList[ind].fIOPL) continue;
-        prior = iopl_set_tag(ioplList[ind].fIOPL, tag);
-        if (VM_KERN_MEMORY_NONE == dataP->fAllocTag) dataP->fAllocTag = prior;
-#if 0
-        if (tag != prior)
-        {
-            char name[2][48];
-            vm_tag_get_kext(prior, &name[0][0], sizeof(name[0]));
-            vm_tag_get_kext(tag,   &name[1][0], sizeof(name[1]));
-            IOLog("switched %48s to %48s\n", name[0], name[1]);
-        }
-#endif
-    }
-}
-#endif /* IOTRACKING */
-
-
 IOReturn IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection)
 {
     IOOptionBits type = _flags & kIOMemoryTypeMask;
@@ -2840,28 +3028,33 @@ IOReturn IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection)
     ioGMDData *dataP;
     upl_page_info_array_t pageInfo;
     ppnum_t mapBase;
+    vm_tag_t tag = VM_KERN_MEMORY_NONE;
 
     assert(kIOMemoryTypeVirtual == type || kIOMemoryTypeVirtual64 == type || kIOMemoryTypeUIO == type);
 
     if ((kIODirectionOutIn & forDirection) == kIODirectionNone)
         forDirection = (IODirection) (forDirection | getDirection());
 
+    dataP = getDataP(_memoryEntries);
     upl_control_flags_t uplFlags;    // This Mem Desc's default flags for upl creation
     switch (kIODirectionOutIn & forDirection)
     {
-    case kIODirectionOut:
-        // Pages do not need to be marked as dirty on commit
-        uplFlags = UPL_COPYOUT_FROM;
-        break;
+       case kIODirectionOut:
+           // Pages do not need to be marked as dirty on commit
+           uplFlags = UPL_COPYOUT_FROM;
+           dataP->fDMAAccess = kIODMAMapReadAccess;
+           break;
 
-    case kIODirectionIn:
-    default:
-        uplFlags = 0;  // i.e. ~UPL_COPYOUT_FROM
-        break;
-    }
-    dataP = getDataP(_memoryEntries);
+       case kIODirectionIn:
+           dataP->fDMAAccess = kIODMAMapWriteAccess;
+           uplFlags = 0;       // i.e. ~UPL_COPYOUT_FROM
+           break;
 
-    if (kIODirectionDMACommand & forDirection) assert(_wireCount);
+       default:
+           dataP->fDMAAccess = kIODMAMapReadAccess | kIODMAMapWriteAccess;
+           uplFlags = 0;       // i.e. ~UPL_COPYOUT_FROM
+           break;
+    }
 
     if (_wireCount)
     {
@@ -2874,11 +3067,13 @@ IOReturn IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection)
     else
     {
         IOMapper *mapper;
+
         mapper = dataP->fMapper;
-        dataP->fMappedBase = 0;
+        dataP->fMappedBaseValid = dataP->fMappedBase = 0;
 
         uplFlags |= UPL_SET_IO_WIRE | UPL_SET_LITE;
-        uplFlags |= UPL_MEMORY_TAG_MAKE(getVMTag(kernel_map));
+       tag = _kernelTag;
+       if (VM_KERN_MEMORY_NONE == tag) tag = IOMemoryTag(kernel_map);
 
         if (kIODirectionPrepareToPhys32 & forDirection)
         {
@@ -2914,14 +3109,15 @@ IOReturn IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection)
 
         for (UInt range = 0; range < _rangesCount; range++) {
             ioPLBlock iopl;
-            mach_vm_address_t startPage;
+            mach_vm_address_t startPage, startPageOffset;
             mach_vm_size_t    numBytes;
             ppnum_t highPage = 0;
 
             // Get the startPage address and length of vec[range]
             getAddrLenForInd(startPage, numBytes, type, vec, range);
-            iopl.fPageOffset = startPage & PAGE_MASK;
-            numBytes += iopl.fPageOffset;
+            startPageOffset = startPage & PAGE_MASK;
+            iopl.fPageOffset = startPageOffset;
+            numBytes += startPageOffset;
             startPage = trunc_page_64(startPage);
 
             if (mapper)
@@ -2982,7 +3178,8 @@ IOReturn IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection)
                                                        &iopl.fIOPL,
                                                        baseInfo,
                                                        &numPageInfo,
-                                                       &ioplFlags);
+                                                       &ioplFlags,
+                                                       tag);
                 }
                 else {
                     assert(theMap);
@@ -2992,7 +3189,8 @@ IOReturn IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection)
                                                     &iopl.fIOPL,
                                                     baseInfo,
                                                     &numPageInfo,
-                                                    &ioplFlags);
+                                                    &ioplFlags,
+                                                    tag);
                 }
 
                 if (error != KERN_SUCCESS) goto abortExit;
@@ -3014,7 +3212,7 @@ IOReturn IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection)
 
                 iopl.fIOMDOffset = mdOffset;
                 iopl.fPageInfo = pageIndex;
-                if (mapper && pageIndex && (page_mask & (mdOffset + iopl.fPageOffset))) dataP->fDiscontig = true;
+                if (mapper && pageIndex && (page_mask & (mdOffset + startPageOffset))) dataP->fDiscontig = true;
 
                 if (!_memoryEntries->appendBytes(&iopl, sizeof(iopl))) {
                     // Clean up partial created and unsaved iopl
@@ -3049,23 +3247,13 @@ IOReturn IOGeneralMemoryDescriptor::wireVirtual(IODirection forDirection)
     }
 
 #if IOTRACKING
-    if (kIOReturnSuccess == error)
+    if (!(_flags & kIOMemoryAutoPrepare) && (kIOReturnSuccess == error))
     {
-        vm_tag_t      tag;
-
-        dataP = getDataP(_memoryEntries);
-        if (forDirection & kIODirectionDMACommand) tag = (forDirection & kIODirectionDMACommandMask) >> kIODirectionDMACommandShift;
-        else                                       tag = IOMemoryTag(kernel_map);
-
-        if (!_wireCount) vm_tag_set_init(&dataP->fWireTags, kMaxWireTags);
-        vm_tag_set_enter(&dataP->fWireTags, kMaxWireTags, tag);
-
-        IOMemoryDescriptorUpdateWireOwner(dataP, _memoryEntries, tag);
-        if (!_wireCount)
-        {
-           //if (!(_flags & kIOMemoryAutoPrepare))
-           IOTrackingAdd(gIOWireTracking, &dataP->fWireTracking, ptoa(_pages), false);
-        }
+       dataP = getDataP(_memoryEntries);
+       if (!dataP->fWireTracking.link.next)
+       {
+           IOTrackingAdd(gIOWireTracking, &dataP->fWireTracking, ptoa(_pages), false, tag);
+       }
     }
 #endif /* IOTRACKING */
 
@@ -3123,6 +3311,7 @@ bool IOGeneralMemoryDescriptor::initMemoryEntries(size_t size, IOMapper * mapper
     dataP->fPreparationID        = kIOPreparationIDUnprepared;
     dataP->fDiscontig            = false;
     dataP->fCompletionError      = false;
+    dataP->fMappedBaseValid      = false;
 
     return (true);
 }
@@ -3136,16 +3325,83 @@ IOReturn IOMemoryDescriptor::dmaMap(
     uint64_t                    * mapAddress,
     uint64_t                    * mapLength)
 {
-    IOReturn ret;
+    IOReturn err;
     uint32_t mapOptions;
 
     mapOptions = 0;
     mapOptions |= kIODMAMapReadAccess;
     if (!(kIOMemoryPreparedReadOnly & _flags)) mapOptions |= kIODMAMapWriteAccess;
 
-    ret = mapper->iovmMapMemory(this, offset, length, mapOptions, 
+    err = mapper->iovmMapMemory(this, offset, length, mapOptions,
                                mapSpec, command, NULL, mapAddress, mapLength);
 
+    if (kIOReturnSuccess == err) dmaMapRecord(mapper, command, *mapLength);
+
+    return (err);
+}
+
+void IOMemoryDescriptor::dmaMapRecord(
+    IOMapper                    * mapper,
+    IODMACommand                * command,
+    uint64_t                      mapLength)
+{
+    kern_allocation_name_t alloc;
+    int16_t                prior;
+
+    if ((alloc = mapper->fAllocName) /* && mapper != IOMapper::gSystem */)
+    {
+       kern_allocation_update_size(mapper->fAllocName, mapLength);
+    }
+
+    if (!command) return;
+    prior = OSAddAtomic16(1, &_dmaReferences);
+    if (!prior)
+    {
+       if (alloc && (VM_KERN_MEMORY_NONE != _kernelTag))
+       {
+           _mapName  = alloc;
+           mapLength = _length;
+           kern_allocation_update_subtotal(alloc, _kernelTag, mapLength);
+       }
+       else _mapName = NULL;
+    }
+}
+
+IOReturn IOMemoryDescriptor::dmaUnmap(
+    IOMapper                    * mapper,
+    IODMACommand                * command,
+    uint64_t                      offset,
+    uint64_t                      mapAddress,
+    uint64_t                      mapLength)
+{
+    IOReturn ret;
+    kern_allocation_name_t alloc;
+    kern_allocation_name_t mapName;
+    int16_t prior;
+
+    mapName = 0;
+    prior = 0;
+    if (command)
+    {
+       mapName = _mapName;
+        if (_dmaReferences) prior = OSAddAtomic16(-1, &_dmaReferences);
+        else                panic("_dmaReferences underflow");
+    }
+
+    if (!mapLength) return (kIOReturnSuccess);
+
+    ret = mapper->iovmUnmapMemory(this, command, mapAddress, mapLength);
+
+    if ((alloc = mapper->fAllocName))
+    {
+        kern_allocation_update_size(alloc, -mapLength);
+        if ((1 == prior) && mapName && (VM_KERN_MEMORY_NONE != _kernelTag))
+        {
+           mapLength = _length;
+            kern_allocation_update_subtotal(mapName, _kernelTag, -mapLength);
+        }
+    }
+
     return (ret);
 }
 
@@ -3164,6 +3420,7 @@ IOReturn IOGeneralMemoryDescriptor::dmaMap(
 
     *mapAddress = 0;
     if (kIOMemoryHostOnly & _flags) return (kIOReturnSuccess);
+    if (kIOMemoryRemote & _flags)   return (kIOReturnNotAttached);
 
     if ((type == kIOMemoryTypePhysical) || (type == kIOMemoryTypePhysical64)
      || offset || (length != _length))
@@ -3195,8 +3452,8 @@ IOReturn IOGeneralMemoryDescriptor::dmaMap(
            mapOptions |= kIODMAMapPageListFullyOccupied;
        }
 
-       mapOptions |= kIODMAMapReadAccess;
-       if (!(kIOMemoryPreparedReadOnly & _flags)) mapOptions |= kIODMAMapWriteAccess;
+       assert(dataP->fDMAAccess);
+        mapOptions |= dataP->fDMAAccess;
 
        // Check for direct device non-paged memory
        if (ioplList->fFlags & kIOPLOnDevice) mapOptions |= kIODMAMapPhysicallyContiguous;
@@ -3209,6 +3466,8 @@ IOReturn IOGeneralMemoryDescriptor::dmaMap(
        };
        err = mapper->iovmMapMemory(this, offset, length, mapOptions, &mapSpec, 
                                    command, &dmaPageList, mapAddress, mapLength);
+
+       if (kIOReturnSuccess == err) dmaMapRecord(mapper, command, *mapLength);
     }
 
     return (err);
@@ -3232,20 +3491,17 @@ IOReturn IOGeneralMemoryDescriptor::prepare(IODirection forDirection)
     if ((kIOMemoryTypePhysical == type) || (kIOMemoryTypePhysical64 == type))
        return kIOReturnSuccess;
 
+    assert (!(kIOMemoryRemote & _flags));
+    if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
+
     if (_prepareLock) IOLockLock(_prepareLock);
 
-    if (kIODirectionDMACommand & forDirection)
-    {
-#if IOMD_DEBUG_DMAACTIVE
-       OSIncrementAtomic(&__iomd_reservedA);
-#endif /* IOMD_DEBUG_DMAACTIVE */
-    }
     if (kIOMemoryTypeVirtual == type || kIOMemoryTypeVirtual64 == type || kIOMemoryTypeUIO == type)
     {
         error = wireVirtual(forDirection);
     }
 
-    if ((kIOReturnSuccess == error) && !(kIODirectionDMACommand & forDirection))
+    if (kIOReturnSuccess == error)
     {
         if (1 == ++_wireCount)
         {
@@ -3278,6 +3534,9 @@ IOReturn IOGeneralMemoryDescriptor::complete(IODirection forDirection)
     if ((kIOMemoryTypePhysical == type) || (kIOMemoryTypePhysical64 == type))
        return kIOReturnSuccess;
 
+    assert (!(kIOMemoryRemote & _flags));
+    if (kIOMemoryRemote & _flags) return (kIOReturnNotAttached);
+
     if (_prepareLock) IOLockLock(_prepareLock);
     do
     {
@@ -3286,26 +3545,6 @@ IOReturn IOGeneralMemoryDescriptor::complete(IODirection forDirection)
         dataP = getDataP(_memoryEntries);
         if (!dataP)      break;
 
-#if IOMD_DEBUG_DMAACTIVE
-        if (kIODirectionDMACommand & forDirection)
-        {
-            if (__iomd_reservedA) OSDecrementAtomic(&__iomd_reservedA);
-            else                  panic("kIOMDSetDMAInactive");
-        }
-#endif /* IOMD_DEBUG_DMAACTIVE */
-#if IOTRACKING
-        if (kIOMemoryTypeVirtual == type || kIOMemoryTypeVirtual64 == type || kIOMemoryTypeUIO == type)
-        {
-            vm_tag_t      tag;
-
-            if (forDirection & kIODirectionDMACommand) tag = (forDirection & kIODirectionDMACommandMask) >> kIODirectionDMACommandShift;
-            else                                       tag = IOMemoryTag(kernel_map);
-            vm_tag_set_remove(&dataP->fWireTags, kMaxWireTags, tag, &tag);
-            IOMemoryDescriptorUpdateWireOwner(dataP, _memoryEntries, tag);
-        }
-        if (kIODirectionDMACommand & forDirection)   break;
-#endif /* IOTRACKING */
-
         if (kIODirectionCompleteWithError & forDirection)  dataP->fCompletionError = true;
 
         if ((kIOMemoryClearEncrypt & _flags) && (1 == _wireCount))
@@ -3324,30 +3563,28 @@ IOReturn IOGeneralMemoryDescriptor::complete(IODirection forDirection)
                 // kIODirectionCompleteWithDataValid & forDirection
                 if (kIOMemoryTypeVirtual == type || kIOMemoryTypeVirtual64 == type || kIOMemoryTypeUIO == type)
                 {
+                    vm_tag_t tag;
+                    tag = getVMTag(kernel_map);
                     for (ind = 0; ind < count; ind++)
                     {
-                        if (ioplList[ind].fIOPL) iopl_valid_data(ioplList[ind].fIOPL);
+                        if (ioplList[ind].fIOPL) iopl_valid_data(ioplList[ind].fIOPL, tag);
                     }
                 }
             }
             else
             {
-#if IOMD_DEBUG_DMAACTIVE
-                if (__iomd_reservedA) panic("complete() while dma active");
-#endif /* IOMD_DEBUG_DMAACTIVE */
+                if (_dmaReferences) panic("complete() while dma active");
 
-                if (dataP->fMappedBase) {
-                    dataP->fMapper->iovmUnmapMemory(this, NULL, dataP->fMappedBase, dataP->fMappedLength);
-                    dataP->fMappedBase = 0;
+                if (dataP->fMappedBaseValid) {
+                    dmaUnmap(dataP->fMapper, NULL, 0, dataP->fMappedBase, dataP->fMappedLength);
+                    dataP->fMappedBaseValid = dataP->fMappedBase = 0;
                 }
-                // Only complete iopls that we created which are for TypeVirtual
-                if (kIOMemoryTypeVirtual == type || kIOMemoryTypeVirtual64 == type || kIOMemoryTypeUIO == type) {
 #if IOTRACKING
-                    //if (!(_flags & kIOMemoryAutoPrepare))
-                    {
-                        IOTrackingRemove(gIOWireTracking, &dataP->fWireTracking, ptoa(_pages));
-                    }
+               if (dataP->fWireTracking.link.next) IOTrackingRemove(gIOWireTracking, &dataP->fWireTracking, ptoa(_pages));
 #endif /* IOTRACKING */
+                // Only complete iopls that we created which are for TypeVirtual
+                if (kIOMemoryTypeVirtual == type || kIOMemoryTypeVirtual64 == type || kIOMemoryTypeUIO == type)
+                {
                     for (ind = 0; ind < count; ind++)
                         if (ioplList[ind].fIOPL) {
                             if (dataP->fCompletionError)
@@ -3363,7 +3600,7 @@ IOReturn IOGeneralMemoryDescriptor::complete(IODirection forDirection)
                 (void) _memoryEntries->initWithBytes(dataP, computeDataSize(0, 0)); // == setLength()
 
                 dataP->fPreparationID = kIOPreparationIDUnprepared;
-                dataP->fAllocTag = VM_KERN_MEMORY_NONE;
+                _flags &= ~kIOMemoryPreparedReadOnly;
             }
         }
     }
@@ -3400,6 +3637,9 @@ IOReturn IOGeneralMemoryDescriptor::doMap(
     if ((offset >= _length) || ((offset + length) > _length))
        return( kIOReturnBadArgument );
 
+    assert (!(kIOMemoryRemote & _flags));
+    if (kIOMemoryRemote & _flags) return (0);
+
     if (vec.v)
        getAddrLenForInd(range0Addr, range0Len, type, vec, 0);
 
@@ -3408,6 +3648,7 @@ IOReturn IOGeneralMemoryDescriptor::doMap(
      && (mapping->fAddressTask == _task)
      && (mapping->fAddressMap == get_task_map(_task)) 
      && (options & kIOMapAnywhere)
+     && (!(kIOMapUnique & options))
      && (1 == _rangesCount) 
      && (0 == offset)
      && range0Addr 
@@ -3457,12 +3698,11 @@ IOReturn IOGeneralMemoryDescriptor::doMap(
 
            size = round_page(mapping->fLength);
            flags = UPL_COPYOUT_FROM | UPL_SET_INTERNAL 
-                       | UPL_SET_LITE | UPL_SET_IO_WIRE | UPL_BLOCK_ACCESS
-                       | UPL_MEMORY_TAG_MAKE(getVMTag(kernel_map));
+                       | UPL_SET_LITE | UPL_SET_IO_WIRE | UPL_BLOCK_ACCESS;
 
            if (KERN_SUCCESS != memory_object_iopl_request(_memRef->entries[0].entry, 0, &size, &redirUPL2,
                                            NULL, NULL,
-                                           &flags))
+                                           &flags, getVMTag(kernel_map)))
                redirUPL2 = NULL;
 
            for (lock_count = 0;
@@ -3503,7 +3743,7 @@ IOReturn IOGeneralMemoryDescriptor::doMap(
     // upl_transpose> //
     else
     {
-       err = memoryReferenceMap(_memRef, mapping->fAddressMap, offset, length, options, &mapping->fAddress);
+        err = memoryReferenceMap(_memRef, mapping->fAddressMap, offset, length, options, &mapping->fAddress);
 #if IOTRACKING
         if ((err == KERN_SUCCESS) && ((kIOTracking & gIOKitDebug) || _task))
         {
@@ -3725,11 +3965,14 @@ IOReturn IOMemoryDescriptor::populateDevicePager(
        // faulting in later can't take place from interrupt level.
        if ((addressMap == kernel_map) && !(kIOMemoryRedirected & _flags))
        {
-           vm_fault(addressMap, 
-                    (vm_map_offset_t)trunc_page_64(address),
-                    VM_PROT_READ|VM_PROT_WRITE, 
-                    FALSE, THREAD_UNINT, NULL, 
-                    (vm_map_offset_t)0);
+           err = vm_fault(addressMap, 
+                          (vm_map_offset_t)trunc_page_64(address),
+                          options & kIOMapReadOnly ? VM_PROT_READ : VM_PROT_READ|VM_PROT_WRITE, 
+                          FALSE, VM_KERN_MEMORY_NONE,
+                          THREAD_UNINT, NULL,
+                          (vm_map_offset_t)0);
+
+           if (KERN_SUCCESS != err) break;
        }
 
        sourceOffset += segLen - pageOffset;
@@ -4081,8 +4324,7 @@ IOReturn IOMemoryMap::wireRange(
     prot = (kIODirectionOutIn & options);
     if (prot)
     {
-       prot |= VM_PROT_MEMORY_TAG_MAKE(fMemory->getVMTag(kernel_map));
-       kr = vm_map_wire(fAddressMap, start, end, prot, FALSE);
+       kr = vm_map_wire_kernel(fAddressMap, start, end, prot, fMemory->getVMTag(kernel_map), FALSE);
     }
     else
     {
@@ -4244,11 +4486,10 @@ IOReturn IOMemoryMap::redirect(IOMemoryDescriptor * newBackingMemory,
        {
            upl_size_t          size = round_page(fLength);
            upl_control_flags_t flags = UPL_COPYOUT_FROM | UPL_SET_INTERNAL 
-                                       | UPL_SET_LITE | UPL_SET_IO_WIRE | UPL_BLOCK_ACCESS
-                                       | UPL_MEMORY_TAG_MAKE(fMemory->getVMTag(kernel_map));
+                                       | UPL_SET_LITE | UPL_SET_IO_WIRE | UPL_BLOCK_ACCESS;
            if (KERN_SUCCESS != memory_object_iopl_request(fMemory->_memRef->entries[0].entry, 0, &size, &fRedirUPL,
                                            NULL, NULL,
-                                           &flags))
+                                           &flags, fMemory->getVMTag(kernel_map)))
                fRedirUPL = 0;
 
            if (physMem)
@@ -4301,9 +4542,8 @@ IOMemoryMap * IOMemoryDescriptor::makeMapping(
     if (!(kIOMap64Bit & options)) panic("IOMemoryDescriptor::makeMapping !64bit");
 #endif /* !__LP64__ */
 
-    IOMemoryDescriptor * mapDesc = 0;
-    IOMemoryMap *       result = 0;
-    OSIterator *        iter;
+    IOMemoryDescriptor *  mapDesc = 0;
+    __block IOMemoryMap * result  = 0;
 
     IOMemoryMap *  mapping = (IOMemoryMap *) __address;
     mach_vm_size_t offset  = mapping->fOffset + __offset;
@@ -4348,20 +4588,17 @@ IOMemoryMap * IOMemoryDescriptor::makeMapping(
        else
        {
            // look for a compatible existing mapping
-           if( (iter = OSCollectionIterator::withCollection(_mappings)))
+           if (_mappings) _mappings->iterateObjects(^(OSObject * object)
            {
-               IOMemoryMap * lookMapping;
-               while ((lookMapping = (IOMemoryMap *) iter->getNextObject()))
+               IOMemoryMap * lookMapping = (IOMemoryMap *) object;
+               if ((result = lookMapping->copyCompatible(mapping)))
                {
-                   if ((result = lookMapping->copyCompatible(mapping)))
-                   {
-                       addMapping(result);
-                       result->setMemoryDescriptor(this, offset);
-                       break;
-                   }
+                   addMapping(result);
+                   result->setMemoryDescriptor(this, offset);
+                   return (true);
                }
-               iter->release();
-           }
+               return (false);
+           });
            if (result || (options & kIOMapReference))
            {
                if (result != mapping)
@@ -4481,16 +4718,17 @@ void * IOMemoryDescriptor::getVirtualSegment(IOByteCount offset,
 
 bool IOGeneralMemoryDescriptor::serialize(OSSerialize * s) const
 {
-    OSSymbol const *keys[2];
-    OSObject *values[2];
+    OSSymbol const *keys[2] = {0};
+    OSObject *values[2] = {0};
     OSArray * array;
+    vm_size_t vcopy_size;
 
     struct SerData {
        user_addr_t address;
        user_size_t length;
-    } *vcopy;
+    } *vcopy = NULL;
     unsigned int index, nRanges;
-    bool result;
+    bool result = false;
 
     IOOptionBits type = _flags & kIOMemoryTypeMask;
 
@@ -4500,17 +4738,19 @@ bool IOGeneralMemoryDescriptor::serialize(OSSerialize * s) const
     if (!array)  return (false);
 
     nRanges = _rangesCount;
-    vcopy = (SerData *) IOMalloc(sizeof(SerData) * nRanges);
-    if (vcopy == 0) return false;
+    if (os_mul_overflow(sizeof(SerData), nRanges, &vcopy_size)) {
+        result = false;
+        goto bail;
+    }
+    vcopy = (SerData *) IOMalloc(vcopy_size);
+    if (vcopy == 0) {
+        result = false;
+        goto bail;
+    }
 
     keys[0] = OSSymbol::withCString("address");
     keys[1] = OSSymbol::withCString("length");
 
-    result = false;
-    values[0] = values[1] = 0;
-
-    // From this point on we can go to bail.
-
     // Copy the volatile data so we don't have to allocate memory
     // while the lock is held.
     LOCK;
@@ -4570,7 +4810,7 @@ bool IOGeneralMemoryDescriptor::serialize(OSSerialize * s) const
     if (keys[1])
       keys[1]->release();
     if (vcopy)
-        IOFree(vcopy, sizeof(SerData) * nRanges);
+      IOFree(vcopy, vcopy_size);
 
     return result;
 }