]> git.saurik.com Git - apple/xnu.git/blobdiff - bsd/vfs/vfs_subr.c
xnu-1699.32.7.tar.gz
[apple/xnu.git] / bsd / vfs / vfs_subr.c
index be1ba3291a06ae7516bf95c53d6c888458854bc0..43352545d1e931171fd2cf9420ee85d70401b074 100644 (file)
@@ -1,5 +1,5 @@
 /*
 /*
- * Copyright (c) 2000-2007 Apple Inc. All rights reserved.
+ * Copyright (c) 2000-2010 Apple Inc. All rights reserved.
  *
  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
  * 
  *
  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
  * 
 #include <sys/kdebug.h>
 #include <sys/kauth.h>
 #include <sys/user.h>
 #include <sys/kdebug.h>
 #include <sys/kauth.h>
 #include <sys/user.h>
+#include <sys/kern_memorystatus.h>
 #include <miscfs/fifofs/fifo.h>
 
 #include <string.h>
 #include <miscfs/fifofs/fifo.h>
 
 #include <string.h>
 
 #include <mach/mach_types.h>
 #include <mach/memory_object_types.h>
 
 #include <mach/mach_types.h>
 #include <mach/memory_object_types.h>
+#include <mach/memory_object_control.h>
 
 #include <kern/kalloc.h>       /* kalloc()/kfree() */
 #include <kern/clock.h>                /* delay_for_interval() */
 #include <libkern/OSAtomic.h>  /* OSAddAtomic() */
 
 
 
 #include <kern/kalloc.h>       /* kalloc()/kfree() */
 #include <kern/clock.h>                /* delay_for_interval() */
 #include <libkern/OSAtomic.h>  /* OSAddAtomic() */
 
 
+#ifdef JOE_DEBUG
+#include <libkern/OSDebug.h>
+#endif
+
 #include <vm/vm_protos.h>      /* vnode_pager_vrele() */
 
 #if CONFIG_MACF
 #include <vm/vm_protos.h>      /* vnode_pager_vrele() */
 
 #if CONFIG_MACF
 extern lck_grp_t *vnode_lck_grp;
 extern lck_attr_t *vnode_lck_attr;
 
 extern lck_grp_t *vnode_lck_grp;
 extern lck_attr_t *vnode_lck_attr;
 
+#if CONFIG_TRIGGERS
+extern lck_grp_t *trigger_vnode_lck_grp;
+extern lck_attr_t *trigger_vnode_lck_attr;
+#endif
 
 extern lck_mtx_t * mnt_list_mtx_lock;
 
 
 extern lck_mtx_t * mnt_list_mtx_lock;
 
@@ -144,6 +154,16 @@ int        vttoif_tab[9] = {
        S_IFSOCK, S_IFIFO, S_IFMT,
 };
 
        S_IFSOCK, S_IFIFO, S_IFMT,
 };
 
+
+/* XXX These should be in a BSD accessible Mach header, but aren't. */
+extern void             memory_object_mark_used(
+       memory_object_control_t         control);
+
+extern void             memory_object_mark_unused(
+       memory_object_control_t         control,
+       boolean_t                       rage);
+
+
 /* XXX next protptype should be from <nfs/nfs.h> */
 extern int       nfs_vinvalbuf(vnode_t, int, vfs_context_t, int);
 
 /* XXX next protptype should be from <nfs/nfs.h> */
 extern int       nfs_vinvalbuf(vnode_t, int, vfs_context_t, int);
 
@@ -160,8 +180,11 @@ __private_extern__ kern_return_t reset_vmobjectcache(unsigned int val1,
                        unsigned int val2);
 __private_extern__ int unlink1(vfs_context_t, struct nameidata *, int);
 
                        unsigned int val2);
 __private_extern__ int unlink1(vfs_context_t, struct nameidata *, int);
 
+extern int system_inshutdown;
+
 static void vnode_list_add(vnode_t);
 static void vnode_list_remove(vnode_t);
 static void vnode_list_add(vnode_t);
 static void vnode_list_remove(vnode_t);
+static void vnode_list_remove_locked(vnode_t);
 
 static errno_t vnode_drain(vnode_t);
 static void vgone(vnode_t, int flags);
 
 static errno_t vnode_drain(vnode_t);
 static void vgone(vnode_t, int flags);
@@ -169,8 +192,6 @@ static void vclean(vnode_t vp, int flag);
 static void vnode_reclaim_internal(vnode_t, int, int, int);
 
 static void vnode_dropiocount (vnode_t);
 static void vnode_reclaim_internal(vnode_t, int, int, int);
 
 static void vnode_dropiocount (vnode_t);
-static errno_t vnode_getiocount(vnode_t vp, int vid, int vflags);
-static int vget_internal(vnode_t, int, int);
 
 static vnode_t checkalias(vnode_t vp, dev_t nvp_rdev);
 static int  vnode_reload(vnode_t);
 
 static vnode_t checkalias(vnode_t vp, dev_t nvp_rdev);
 static int  vnode_reload(vnode_t);
@@ -180,13 +201,26 @@ static void insmntque(vnode_t vp, mount_t mp);
 static int mount_getvfscnt(void);
 static int mount_fillfsids(fsid_t *, int );
 static void vnode_iterate_setup(mount_t);
 static int mount_getvfscnt(void);
 static int mount_fillfsids(fsid_t *, int );
 static void vnode_iterate_setup(mount_t);
-static int vnode_umount_preflight(mount_t, vnode_t, int);
+int vnode_umount_preflight(mount_t, vnode_t, int);
 static int vnode_iterate_prepare(mount_t);
 static int vnode_iterate_reloadq(mount_t);
 static void vnode_iterate_clear(mount_t);
 static int vnode_iterate_prepare(mount_t);
 static int vnode_iterate_reloadq(mount_t);
 static void vnode_iterate_clear(mount_t);
+static mount_t vfs_getvfs_locked(fsid_t *);
+static int vn_create_reg(vnode_t dvp, vnode_t *vpp, struct nameidata *ndp,
+               struct vnode_attr *vap, uint32_t flags, int fmode, uint32_t *statusp, vfs_context_t ctx);
+static int vnode_authattr_new_internal(vnode_t dvp, struct vnode_attr *vap, int noauth, uint32_t *defaulted_fieldsp, vfs_context_t ctx);
 
 errno_t rmdir_remove_orphaned_appleDouble(vnode_t, vfs_context_t, int *); 
 
 
 errno_t rmdir_remove_orphaned_appleDouble(vnode_t, vfs_context_t, int *); 
 
+#ifdef JOE_DEBUG
+static void record_vp(vnode_t vp, int count);
+#endif
+
+#if CONFIG_TRIGGERS
+static int vnode_resolver_create(mount_t, vnode_t, struct vnode_trigger_param *, boolean_t external);
+static void vnode_resolver_detach(vnode_t);
+#endif
+
 TAILQ_HEAD(freelst, vnode) vnode_free_list;    /* vnode free list */
 TAILQ_HEAD(deadlst, vnode) vnode_dead_list;    /* vnode dead list */
 
 TAILQ_HEAD(freelst, vnode) vnode_free_list;    /* vnode free list */
 TAILQ_HEAD(deadlst, vnode) vnode_dead_list;    /* vnode dead list */
 
@@ -259,7 +293,7 @@ static int nummounts = 0;
  * place for now...  it should be deprecated out of the
  * exports and removed eventually.
  */
  * place for now...  it should be deprecated out of the
  * exports and removed eventually.
  */
-unsigned long vnodetarget;             /* target for vnreclaim() */
+u_int32_t vnodetarget;         /* target for vnreclaim() */
 #define VNODE_FREE_TARGET      20      /* Default value for vnodetarget */
 
 /*
 #define VNODE_FREE_TARGET      20      /* Default value for vnodetarget */
 
 /*
@@ -304,6 +338,10 @@ reset_vmobjectcache(unsigned int val1, unsigned int val2)
        vm_size_t oval = val1 - VNODE_FREE_MIN;
        vm_size_t nval;
        
        vm_size_t oval = val1 - VNODE_FREE_MIN;
        vm_size_t nval;
        
+       if (val1 == val2) {
+               return KERN_SUCCESS;
+       }
+
        if(val2 < VNODE_FREE_MIN)
                nval = 0;
        else
        if(val2 < VNODE_FREE_MIN)
                nval = 0;
        else
@@ -323,9 +361,9 @@ vnode_waitforwrites(vnode_t vp, int output_target, int slpflag, int slptimeout,
 
        if (vp->v_numoutput > output_target) {
 
 
        if (vp->v_numoutput > output_target) {
 
-               slpflag &= ~PDROP;
+               slpflag |= PDROP;
 
 
-               vnode_lock(vp);
+               vnode_lock_spin(vp);
 
                while ((vp->v_numoutput > output_target) && error == 0) {
                        if (output_target)
 
                while ((vp->v_numoutput > output_target) && error == 0) {
                        if (output_target)
@@ -336,6 +374,8 @@ vnode_waitforwrites(vnode_t vp, int output_target, int slpflag, int slptimeout,
                        ts.tv_sec = (slptimeout/100);
                        ts.tv_nsec = (slptimeout % 1000)  * 10 * NSEC_PER_USEC * 1000 ;
                        error = msleep((caddr_t)&vp->v_numoutput, &vp->v_lock, (slpflag | (PRIBIO + 1)), msg, &ts);
                        ts.tv_sec = (slptimeout/100);
                        ts.tv_nsec = (slptimeout % 1000)  * 10 * NSEC_PER_USEC * 1000 ;
                        error = msleep((caddr_t)&vp->v_numoutput, &vp->v_lock, (slpflag | (PRIBIO + 1)), msg, &ts);
+
+                       vnode_lock_spin(vp);
                }
                vnode_unlock(vp);
        }
                }
                vnode_unlock(vp);
        }
@@ -356,29 +396,27 @@ void
 vnode_writedone(vnode_t vp)
 {
        if (vp) {
 vnode_writedone(vnode_t vp)
 {
        if (vp) {
-               OSAddAtomic(-1, &vp->v_numoutput);
+               int need_wakeup = 0;
 
 
-               if (vp->v_numoutput <= 1) {
-                       int need_wakeup = 0;
+               OSAddAtomic(-1, &vp->v_numoutput);
 
 
-                       vnode_lock_spin(vp);
+               vnode_lock_spin(vp);
 
 
-                       if (vp->v_numoutput < 0)
-                               panic("vnode_writedone: numoutput < 0");
+               if (vp->v_numoutput < 0)
+                       panic("vnode_writedone: numoutput < 0");
 
 
-                       if ((vp->v_flag & VTHROTTLED) && (vp->v_numoutput <= 1)) {
-                               vp->v_flag &= ~VTHROTTLED;
-                               need_wakeup = 1;
-                       }
-                       if ((vp->v_flag & VBWAIT) && (vp->v_numoutput == 0)) {
-                               vp->v_flag &= ~VBWAIT;
-                               need_wakeup = 1;
-                       }
-                       vnode_unlock(vp);
-               
-                       if (need_wakeup)
-                               wakeup((caddr_t)&vp->v_numoutput);
+               if ((vp->v_flag & VTHROTTLED)) {
+                       vp->v_flag &= ~VTHROTTLED;
+                       need_wakeup = 1;
+               }
+               if ((vp->v_flag & VBWAIT) && (vp->v_numoutput == 0)) {
+                       vp->v_flag &= ~VBWAIT;
+                       need_wakeup = 1;
                }
                }
+               vnode_unlock(vp);
+               
+               if (need_wakeup)
+                       wakeup((caddr_t)&vp->v_numoutput);
        }
 }
 
        }
 }
 
@@ -437,7 +475,7 @@ vnode_iterate_setup(mount_t mp)
 
 }
 
 
 }
 
-static int
+int
 vnode_umount_preflight(mount_t mp, vnode_t skipvp, int flags)
 {
        vnode_t vp;
 vnode_umount_preflight(mount_t mp, vnode_t skipvp, int flags)
 {
        vnode_t vp;
@@ -645,6 +683,12 @@ mount_lock(mount_t mp)
        lck_mtx_lock(&mp->mnt_mlock);
 }
 
        lck_mtx_lock(&mp->mnt_mlock);
 }
 
+void
+mount_lock_spin(mount_t mp)
+{
+       lck_mtx_lock_spin(&mp->mnt_mlock);
+}
+
 void
 mount_unlock(mount_t mp)
 {
 void
 mount_unlock(mount_t mp)
 {
@@ -656,7 +700,7 @@ void
 mount_ref(mount_t mp, int locked)
 {
         if ( !locked)
 mount_ref(mount_t mp, int locked)
 {
         if ( !locked)
-               mount_lock(mp);
+               mount_lock_spin(mp);
        
        mp->mnt_count++;
 
        
        mp->mnt_count++;
 
@@ -669,7 +713,7 @@ void
 mount_drop(mount_t mp, int locked)
 {
         if ( !locked)
 mount_drop(mount_t mp, int locked)
 {
         if ( !locked)
-               mount_lock(mp);
+               mount_lock_spin(mp);
        
        mp->mnt_count--;
 
        
        mp->mnt_count--;
 
@@ -761,6 +805,13 @@ mount_refdrain(mount_t mp)
        return(0);
 }
 
        return(0);
 }
 
+/* Tags the mount point as not supportine extended readdir for NFS exports */
+void 
+mount_set_noreaddirext(mount_t mp) {
+       mount_lock (mp);
+       mp->mnt_kern_flag |= MNTK_DENY_READDIREXT;
+       mount_unlock (mp);
+}
 
 /*
  * Mark a mount point as busy. Used to synchronize access and to delay
 
 /*
  * Mark a mount point as busy. Used to synchronize access and to delay
@@ -852,8 +903,8 @@ vfs_rootmountalloc_internal(struct vfstable *vfsp, const char *devname)
 {
        mount_t mp;
 
 {
        mount_t mp;
 
-       mp = _MALLOC_ZONE((u_long)sizeof(struct mount), M_MOUNT, M_WAITOK);
-       bzero((char *)mp, (u_long)sizeof(struct mount));
+       mp = _MALLOC_ZONE(sizeof(struct mount), M_MOUNT, M_WAITOK);
+       bzero((char *)mp, sizeof(struct mount));
 
        /* Initialize the default IO constraints */
        mp->mnt_maxreadcnt = mp->mnt_maxwritecnt = MAXPHYS;
 
        /* Initialize the default IO constraints */
        mp->mnt_maxreadcnt = mp->mnt_maxwritecnt = MAXPHYS;
@@ -862,9 +913,13 @@ vfs_rootmountalloc_internal(struct vfstable *vfsp, const char *devname)
        mp->mnt_maxsegwritesize = mp->mnt_maxwritecnt;
        mp->mnt_devblocksize = DEV_BSIZE;
        mp->mnt_alignmentmask = PAGE_MASK;
        mp->mnt_maxsegwritesize = mp->mnt_maxwritecnt;
        mp->mnt_devblocksize = DEV_BSIZE;
        mp->mnt_alignmentmask = PAGE_MASK;
+       mp->mnt_ioqueue_depth = MNT_DEFAULT_IOQUEUE_DEPTH;
+       mp->mnt_ioscale = 1;
        mp->mnt_ioflags = 0;
        mp->mnt_realrootvp = NULLVP;
        mp->mnt_authcache_ttl = CACHED_LOOKUP_RIGHT_TTL;
        mp->mnt_ioflags = 0;
        mp->mnt_realrootvp = NULLVP;
        mp->mnt_authcache_ttl = CACHED_LOOKUP_RIGHT_TTL;
+       mp->mnt_throttle_mask = LOWPRI_MAX_NUM_DEV - 1;
+       mp->mnt_devbsdunit = 0;
 
        mount_lock_init(mp);
        (void)vfs_busy(mp, LK_NOWAIT);
 
        mount_lock_init(mp);
        (void)vfs_busy(mp, LK_NOWAIT);
@@ -1045,9 +1100,12 @@ vfs_mountroot(void)
                                dounmount(mp, MNT_FORCE, 0, ctx);
                                goto fail;
                        }
                                dounmount(mp, MNT_FORCE, 0, ctx);
                                goto fail;
                        }
-
-                       /* VFS_ROOT provides reference so flags = 0 */
                        error = vnode_label(mp, NULL, vp, NULL, 0, ctx);
                        error = vnode_label(mp, NULL, vp, NULL, 0, ctx);
+                       /*
+                        * get rid of reference provided by VFS_ROOT
+                        */
+                       vnode_put(vp);
+
                        if (error) {
                                printf("%s() vnode_label() returned %d\n",
                                    __func__, error);
                        if (error) {
                                printf("%s() vnode_label() returned %d\n",
                                    __func__, error);
@@ -1071,7 +1129,6 @@ fail:
 /*
  * Lookup a mount point by filesystem identifier.
  */
 /*
  * Lookup a mount point by filesystem identifier.
  */
-extern mount_t vfs_getvfs_locked(fsid_t *);
 
 struct mount *
 vfs_getvfs(fsid_t *fsid)
 
 struct mount *
 vfs_getvfs(fsid_t *fsid)
@@ -1079,7 +1136,7 @@ vfs_getvfs(fsid_t *fsid)
        return (mount_list_lookupby_fsid(fsid, 0, 0));
 }
 
        return (mount_list_lookupby_fsid(fsid, 0, 0));
 }
 
-struct mount *
+static struct mount *
 vfs_getvfs_locked(fsid_t *fsid)
 {
        return(mount_list_lookupby_fsid(fsid, 1, 0));
 vfs_getvfs_locked(fsid_t *fsid)
 {
        return(mount_list_lookupby_fsid(fsid, 1, 0));
@@ -1096,6 +1153,8 @@ vfs_getvfs_by_mntonname(char *path)
                if (!strncmp(mp->mnt_vfsstat.f_mntonname, path,
                                        sizeof(mp->mnt_vfsstat.f_mntonname))) {
                        retmp = mp;
                if (!strncmp(mp->mnt_vfsstat.f_mntonname, path,
                                        sizeof(mp->mnt_vfsstat.f_mntonname))) {
                        retmp = mp;
+                       if (mount_iterref(retmp, 1))
+                               retmp = NULL;
                        goto out;
                }
        }
                        goto out;
                }
        }
@@ -1160,7 +1219,7 @@ insmntque(vnode_t vp, mount_t mp)
                        panic("insmntque: vp not in mount vnode list");
                vp->v_lflag &= ~VNAMED_MOUNT;
 
                        panic("insmntque: vp not in mount vnode list");
                vp->v_lflag &= ~VNAMED_MOUNT;
 
-               mount_lock(lmp);
+               mount_lock_spin(lmp);
 
                mount_drop(lmp, 1);
 
 
                mount_drop(lmp, 1);
 
@@ -1185,7 +1244,7 @@ insmntque(vnode_t vp, mount_t mp)
         * Insert into list of vnodes for the new mount point, if available.
         */
        if ((vp->v_mount = mp) != NULL) {
         * Insert into list of vnodes for the new mount point, if available.
         */
        if ((vp->v_mount = mp) != NULL) {
-               mount_lock(mp);
+               mount_lock_spin(mp);
                if ((vp->v_mntvnodes.tqe_next != 0) && (vp->v_mntvnodes.tqe_prev != 0))
                        panic("vp already in mount list");
                if (mp->mnt_lflag & MNT_LITER)
                if ((vp->v_mntvnodes.tqe_next != 0) && (vp->v_mntvnodes.tqe_prev != 0))
                        panic("vp already in mount list");
                if (mp->mnt_lflag & MNT_LITER)
@@ -1194,8 +1253,6 @@ insmntque(vnode_t vp, mount_t mp)
                        TAILQ_INSERT_HEAD(&mp->mnt_vnodelist, vp, v_mntvnodes);
                if (vp->v_lflag & VNAMED_MOUNT)
                        panic("insmntque: vp already in mount vnode list");
                        TAILQ_INSERT_HEAD(&mp->mnt_vnodelist, vp, v_mntvnodes);
                if (vp->v_lflag & VNAMED_MOUNT)
                        panic("insmntque: vp already in mount vnode list");
-               if ((vp->v_freelist.tqe_prev != (struct vnode **)0xdeadb))
-                       panic("insmntque: vp on the free list\n");
                vp->v_lflag |= VNAMED_MOUNT;
                mount_ref(mp, 1);
                mount_unlock(mp);
                vp->v_lflag |= VNAMED_MOUNT;
                mount_ref(mp, 1);
                mount_unlock(mp);
@@ -1289,6 +1346,7 @@ checkalias(struct vnode *nvp, dev_t nvp_rdev)
 {
        struct vnode *vp;
        struct vnode **vpp;
 {
        struct vnode *vp;
        struct vnode **vpp;
+       struct specinfo *sin = NULL;
        int vid = 0;
 
        vpp = &speclisth[SPECHASH(nvp_rdev)];
        int vid = 0;
 
        vpp = &speclisth[SPECHASH(nvp_rdev)];
@@ -1304,6 +1362,7 @@ loop:
        SPECHASH_UNLOCK();
 
        if (vp) {
        SPECHASH_UNLOCK();
 
        if (vp) {
+found_alias:
                if (vnode_getwithvid(vp,vid)) {
                        goto loop;
                }
                if (vnode_getwithvid(vp,vid)) {
                        goto loop;
                }
@@ -1316,41 +1375,67 @@ loop:
                 * Alias, but not in use, so flush it out.
                 */
                if ((vp->v_iocount == 1) && (vp->v_usecount == 0)) {
                 * Alias, but not in use, so flush it out.
                 */
                if ((vp->v_iocount == 1) && (vp->v_usecount == 0)) {
-                       vnode_reclaim_internal(vp, 1, 0, 0);
+                       vnode_reclaim_internal(vp, 1, 1, 0);
+                       vnode_put_locked(vp);
                        vnode_unlock(vp);
                        vnode_unlock(vp);
-                       vnode_put(vp);
                        goto loop;
                }
                        goto loop;
                }
+               
        }
        if (vp == NULL || vp->v_tag != VT_NON) {
        }
        if (vp == NULL || vp->v_tag != VT_NON) {
-retnullvp:
-               MALLOC_ZONE(nvp->v_specinfo, struct specinfo *, sizeof(struct specinfo),
-                           M_SPECINFO, M_WAITOK);
+               if (sin == NULL) {
+                       MALLOC_ZONE(sin, struct specinfo *, sizeof(struct specinfo),
+                                       M_SPECINFO, M_WAITOK);
+               }
+
+               nvp->v_specinfo = sin;
                bzero(nvp->v_specinfo, sizeof(struct specinfo));
                nvp->v_rdev = nvp_rdev;
                nvp->v_specflags = 0;
                nvp->v_speclastr = -1;
                bzero(nvp->v_specinfo, sizeof(struct specinfo));
                nvp->v_rdev = nvp_rdev;
                nvp->v_specflags = 0;
                nvp->v_speclastr = -1;
+               nvp->v_specinfo->si_opencount = 0;
+               nvp->v_specinfo->si_initted = 0;
+               nvp->v_specinfo->si_throttleable = 0;
 
                SPECHASH_LOCK();
 
                SPECHASH_LOCK();
+               
+               /* We dropped the lock, someone could have added */
+               if (vp == NULLVP) {
+                       for (vp = *vpp; vp; vp = vp->v_specnext) {
+                               if (nvp_rdev == vp->v_rdev && nvp->v_type == vp->v_type) {
+                                       vid = vp->v_id;
+                                       SPECHASH_UNLOCK();
+                                       goto found_alias;
+                               }
+                       }
+               } 
+
                nvp->v_hashchain = vpp;
                nvp->v_specnext = *vpp;
                *vpp = nvp;
                nvp->v_hashchain = vpp;
                nvp->v_specnext = *vpp;
                *vpp = nvp;
-               SPECHASH_UNLOCK();
 
                if (vp != NULLVP) {
 
                if (vp != NULLVP) {
-                       nvp->v_flag |= VALIASED;
-                       vp->v_flag |= VALIASED;
+                       nvp->v_specflags |= SI_ALIASED;
+                       vp->v_specflags |= SI_ALIASED;
+                       SPECHASH_UNLOCK();
+                       vnode_put_locked(vp);
                        vnode_unlock(vp);
                        vnode_unlock(vp);
-                       vnode_put(vp);
+               } else {
+                       SPECHASH_UNLOCK();
                }
                }
+
                return (NULLVP);
        }
                return (NULLVP);
        }
+
+       if (sin) {
+               FREE_ZONE(sin, sizeof(struct specinfo), M_SPECINFO);
+       }
+
        if ((vp->v_flag & (VBDEVVP | VDEVFLUSH)) != 0)
                return(vp);
        if ((vp->v_flag & (VBDEVVP | VDEVFLUSH)) != 0)
                return(vp);
-       else  {
-               panic("checkalias with VT_NON vp that shouldn't: %x", (unsigned int)vp);
-               goto retnullvp;
-       }
+
+       panic("checkalias with VT_NON vp that shouldn't: %p", vp);
+
        return (vp);
 }
 
        return (vp);
 }
 
@@ -1365,26 +1450,20 @@ retnullvp:
  * and an error returned to indicate that the vnode is no longer
  * usable (possibly having been changed to a new file system type).
  */
  * and an error returned to indicate that the vnode is no longer
  * usable (possibly having been changed to a new file system type).
  */
-static int
+int
 vget_internal(vnode_t vp, int vid, int vflags)
 {
        int error = 0;
 vget_internal(vnode_t vp, int vid, int vflags)
 {
        int error = 0;
-       int vpid;
 
        vnode_lock_spin(vp);
 
 
        vnode_lock_spin(vp);
 
-       if (vflags & VNODE_WITHID)
-               vpid = vid;
-       else
-               vpid = vp->v_id;    // save off the original v_id
-
        if ((vflags & VNODE_WRITEABLE) && (vp->v_writecount == 0))
                /*
                 * vnode to be returned only if it has writers opened 
                 */
                error = EINVAL;
        else
        if ((vflags & VNODE_WRITEABLE) && (vp->v_writecount == 0))
                /*
                 * vnode to be returned only if it has writers opened 
                 */
                error = EINVAL;
        else
-               error = vnode_getiocount(vp, vpid, vflags);
+               error = vnode_getiocount(vp, vid, vflags);
 
        vnode_unlock(vp);
 
 
        vnode_unlock(vp);
 
@@ -1399,7 +1478,7 @@ int
 vnode_ref(vnode_t vp)
 {
 
 vnode_ref(vnode_t vp)
 {
 
-        return (vnode_ref_ext(vp, 0));
+        return (vnode_ref_ext(vp, 0, 0));
 }
 
 /*
 }
 
 /*
@@ -1407,7 +1486,7 @@ vnode_ref(vnode_t vp)
  *             ENOENT                  No such file or directory [terminating]
  */
 int
  *             ENOENT                  No such file or directory [terminating]
  */
 int
-vnode_ref_ext(vnode_t vp, int fmode)
+vnode_ref_ext(vnode_t vp, int fmode, int flags)
 {
        int     error = 0;
 
 {
        int     error = 0;
 
@@ -1424,10 +1503,12 @@ vnode_ref_ext(vnode_t vp, int fmode)
        /*
         * if you are the owner of drain/termination, can acquire usecount
         */
        /*
         * if you are the owner of drain/termination, can acquire usecount
         */
-       if ((vp->v_lflag & (VL_DRAIN | VL_TERMINATE | VL_DEAD))) {
-               if (vp->v_owner != current_thread()) {
-                       error = ENOENT;
-                       goto out;
+       if ((flags & VNODE_REF_FORCE) == 0) {
+               if ((vp->v_lflag & (VL_DRAIN | VL_TERMINATE | VL_DEAD))) {
+                       if (vp->v_owner != current_thread()) {
+                               error = ENOENT;
+                               goto out;
+                       }
                }
        }
        vp->v_usecount++;
                }
        }
        vp->v_usecount++;
@@ -1460,6 +1541,13 @@ vnode_ref_ext(vnode_t vp, int fmode)
                        vnode_list_remove(vp);
                }
        }
                        vnode_list_remove(vp);
                }
        }
+       if (vp->v_usecount == 1 && vp->v_type == VREG && !(vp->v_flag & VSYSTEM)) {
+
+               if (vp->v_ubcinfo) {
+                       vnode_lock_convert(vp);
+                       memory_object_mark_used(vp->v_ubcinfo->ui_control);
+               }
+       }
 out:
        vnode_unlock(vp);
 
 out:
        vnode_unlock(vp);
 
@@ -1474,11 +1562,15 @@ out:
 static void
 vnode_list_add(vnode_t vp)
 {
 static void
 vnode_list_add(vnode_t vp)
 {
+#if DIAGNOSTIC
+       lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
+#endif
        /*
         * if it is already on a list or non zero references return 
         */
        /*
         * if it is already on a list or non zero references return 
         */
-       if (VONLIST(vp) || (vp->v_usecount != 0) || (vp->v_iocount != 0))
+       if (VONLIST(vp) || (vp->v_usecount != 0) || (vp->v_iocount != 0) || (vp->v_lflag & VL_TERMINATE))
                return;
                return;
+
        vnode_list_lock();
 
        if ((vp->v_flag & VRAGE) && !(vp->v_lflag & VL_DEAD)) {
        vnode_list_lock();
 
        if ((vp->v_flag & VRAGE) && !(vp->v_lflag & VL_DEAD)) {
@@ -1523,12 +1615,40 @@ vnode_list_add(vnode_t vp)
        vnode_list_unlock();
 }
 
        vnode_list_unlock();
 }
 
+
+/*
+ * remove the vnode from appropriate free list.
+ * called with vnode LOCKED and
+ * the list lock held
+ */
+static void
+vnode_list_remove_locked(vnode_t vp)
+{
+       if (VONLIST(vp)) {
+               /*
+                * the v_listflag field is
+                * protected by the vnode_list_lock
+                */
+               if (vp->v_listflag & VLIST_RAGE)
+                       VREMRAGE("vnode_list_remove", vp);
+               else if (vp->v_listflag & VLIST_DEAD)
+                       VREMDEAD("vnode_list_remove", vp);
+               else
+                       VREMFREE("vnode_list_remove", vp);
+       }
+}
+
+
 /*
  * remove the vnode from appropriate free list.
 /*
  * remove the vnode from appropriate free list.
+ * called with vnode LOCKED
  */
 static void
 vnode_list_remove(vnode_t vp)
 {
  */
 static void
 vnode_list_remove(vnode_t vp)
 {
+#if DIAGNOSTIC
+       lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
+#endif
         /*
         * we want to avoid taking the list lock
         * in the case where we're not on the free
         /*
         * we want to avoid taking the list lock
         * in the case where we're not on the free
@@ -1548,24 +1668,16 @@ vnode_list_remove(vnode_t vp)
                /*
                 * however, we're not guaranteed that
                 * we won't go from the on-list state
                /*
                 * however, we're not guaranteed that
                 * we won't go from the on-list state
-                * to the non-on-list state until we
+                * to the not-on-list state until we
                 * hold the vnode_list_lock... this 
                 * hold the vnode_list_lock... this 
-                * is due to new_vnode removing vnodes
+                * is due to "new_vnode" removing vnodes
                 * from the free list uder the list_lock
                 * w/o the vnode lock... so we need to
                 * check again whether we're currently
                 * on the free list
                 */
                 * from the free list uder the list_lock
                 * w/o the vnode lock... so we need to
                 * check again whether we're currently
                 * on the free list
                 */
-               if (VONLIST(vp)) {
-                       if (vp->v_listflag & VLIST_RAGE)
-                               VREMRAGE("vnode_list_remove", vp);
-                       else if (vp->v_listflag & VLIST_DEAD)
-                               VREMDEAD("vnode_list_remove", vp);
-                       else
-                               VREMFREE("vnode_list_remove", vp);
+               vnode_list_remove_locked(vp);
 
 
-                       VLISTNONE(vp);
-               }
                vnode_list_unlock();
        }
 }
                vnode_list_unlock();
        }
 }
@@ -1588,22 +1700,27 @@ vnode_rele_ext(vnode_t vp, int fmode, int dont_reenter)
 void
 vnode_rele_internal(vnode_t vp, int fmode, int dont_reenter, int locked)
 {
 void
 vnode_rele_internal(vnode_t vp, int fmode, int dont_reenter, int locked)
 {
+
        if ( !locked)
                vnode_lock_spin(vp);
        if ( !locked)
                vnode_lock_spin(vp);
-
+#if DIAGNOSTIC
+       else
+               lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
+#endif
        if (--vp->v_usecount < 0)
        if (--vp->v_usecount < 0)
-               panic("vnode_rele_ext: vp %p usecount -ve : %d", vp,  vp->v_usecount);
+               panic("vnode_rele_ext: vp %p usecount -ve : %d.  v_tag = %d, v_type = %d, v_flag = %x.", vp,  vp->v_usecount, vp->v_tag, vp->v_type, vp->v_flag);
 
        if (fmode & FWRITE) {
                if (--vp->v_writecount < 0)
 
        if (fmode & FWRITE) {
                if (--vp->v_writecount < 0)
-                       panic("vnode_rele_ext: vp %p writecount -ve : %ld", vp,  vp->v_writecount);
+                       panic("vnode_rele_ext: vp %p writecount -ve : %d.  v_tag = %d, v_type = %d, v_flag = %x.", vp,  vp->v_writecount, vp->v_tag, vp->v_type, vp->v_flag);
        }
        if (fmode & O_EVTONLY) {
                if (--vp->v_kusecount < 0)
        }
        if (fmode & O_EVTONLY) {
                if (--vp->v_kusecount < 0)
-                       panic("vnode_rele_ext: vp %p kusecount -ve : %d", vp,  vp->v_kusecount);
+                       panic("vnode_rele_ext: vp %p kusecount -ve : %d.  v_tag = %d, v_type = %d, v_flag = %x.", vp,  vp->v_kusecount, vp->v_tag, vp->v_type, vp->v_flag);
        }
        if (vp->v_kusecount > vp->v_usecount)
        }
        if (vp->v_kusecount > vp->v_usecount)
-               panic("vnode_rele_ext: vp %p kusecount(%d) out of balance with usecount(%d)\n",vp, vp->v_kusecount, vp->v_usecount);
+               panic("vnode_rele_ext: vp %p kusecount(%d) out of balance with usecount(%d).  v_tag = %d, v_type = %d, v_flag = %x.",vp, vp->v_kusecount, vp->v_usecount, vp->v_tag, vp->v_type, vp->v_flag);
+
        if ((vp->v_iocount > 0) || (vp->v_usecount > 0)) {
                /*
                 * vnode is still busy... if we're the last
        if ((vp->v_iocount > 0) || (vp->v_usecount > 0)) {
                /*
                 * vnode is still busy... if we're the last
@@ -1614,9 +1731,7 @@ vnode_rele_internal(vnode_t vp, int fmode, int dont_reenter, int locked)
                        vp->v_lflag |= VL_NEEDINACTIVE;
                        vp->v_flag  &= ~(VNOCACHE_DATA | VRAOFF | VOPENEVT);
                }
                        vp->v_lflag |= VL_NEEDINACTIVE;
                        vp->v_flag  &= ~(VNOCACHE_DATA | VRAOFF | VOPENEVT);
                }
-               if ( !locked)
-                       vnode_unlock(vp);
-               return;
+               goto done;
        }
        vp->v_flag  &= ~(VNOCACHE_DATA | VRAOFF | VOPENEVT);
 
        }
        vp->v_flag  &= ~(VNOCACHE_DATA | VRAOFF | VOPENEVT);
 
@@ -1634,9 +1749,8 @@ vnode_rele_internal(vnode_t vp, int fmode, int dont_reenter, int locked)
                        vp->v_flag |= VAGE;
                }
                vnode_list_add(vp);
                        vp->v_flag |= VAGE;
                }
                vnode_list_add(vp);
-               if ( !locked)
-                       vnode_unlock(vp);
-               return;
+
+               goto done;
        }
        /*
         * at this point both the iocount and usecount
        }
        /*
         * at this point both the iocount and usecount
@@ -1671,15 +1785,22 @@ vnode_rele_internal(vnode_t vp, int fmode, int dont_reenter, int locked)
                
                if (ut->uu_defer_reclaims) {
                        vp->v_defer_reclaimlist = ut->uu_vreclaims;
                
                if (ut->uu_defer_reclaims) {
                        vp->v_defer_reclaimlist = ut->uu_vreclaims;
-                               ut->uu_vreclaims = vp;
-                       goto defer_reclaim;
+                       ut->uu_vreclaims = vp;
+                       goto done;
                }
                vnode_lock_convert(vp);
                }
                vnode_lock_convert(vp);
-               vnode_reclaim_internal(vp, 1, 0, 0);
+               vnode_reclaim_internal(vp, 1, 1, 0);
        }
        vnode_dropiocount(vp);
        vnode_list_add(vp);
        }
        vnode_dropiocount(vp);
        vnode_list_add(vp);
-defer_reclaim:
+done:
+       if (vp->v_usecount == 0 && vp->v_type == VREG && !(vp->v_flag & VSYSTEM)) {
+
+               if (vp->v_ubcinfo) {
+                       vnode_lock_convert(vp);
+                       memory_object_mark_unused(vp->v_ubcinfo->ui_control, (vp->v_flag & VRAGE) == VRAGE);
+               }
+       }
        if ( !locked)
                vnode_unlock(vp);
        return;
        if ( !locked)
                vnode_unlock(vp);
        return;
@@ -1707,7 +1828,7 @@ vflush(struct mount *mp, struct vnode *skipvp, int flags)
        int busy = 0;
        int reclaimed = 0;
        int retval;
        int busy = 0;
        int reclaimed = 0;
        int retval;
-       int vid;
+       unsigned int vid;
 
        mount_lock(mp);
        vnode_iterate_setup(mp);
 
        mount_lock(mp);
        vnode_iterate_setup(mp);
@@ -1735,17 +1856,20 @@ loop:
                return(retval);
        }
 
                return(retval);
        }
 
-    /* iterate over all the vnodes */
-    while (!TAILQ_EMPTY(&mp->mnt_workerqueue)) {
-        vp = TAILQ_FIRST(&mp->mnt_workerqueue);
-        TAILQ_REMOVE(&mp->mnt_workerqueue, vp, v_mntvnodes);
-        TAILQ_INSERT_TAIL(&mp->mnt_vnodelist, vp, v_mntvnodes);
-        if ( (vp->v_mount != mp) || (vp == skipvp)) {
-            continue;
-        }
-        vid = vp->v_id;
-        mount_unlock(mp);
-               vnode_lock(vp);
+       /* iterate over all the vnodes */
+       while (!TAILQ_EMPTY(&mp->mnt_workerqueue)) {
+
+               vp = TAILQ_FIRST(&mp->mnt_workerqueue);
+               TAILQ_REMOVE(&mp->mnt_workerqueue, vp, v_mntvnodes);
+               TAILQ_INSERT_TAIL(&mp->mnt_vnodelist, vp, v_mntvnodes);
+
+               if ( (vp->v_mount != mp) || (vp == skipvp)) {
+                       continue;
+               }
+               vid = vp->v_id;
+               mount_unlock(mp);
+
+               vnode_lock_spin(vp);
 
                if ((vp->v_id != vid) || ((vp->v_lflag & (VL_DEAD | VL_TERMINATE)))) {
                                vnode_unlock(vp);
 
                if ((vp->v_id != vid) || ((vp->v_lflag & (VL_DEAD | VL_TERMINATE)))) {
                                vnode_unlock(vp);
@@ -1772,7 +1896,7 @@ loop:
                        continue;
                }
                /*
                        continue;
                }
                /*
-                * If requested, skip over vnodes marked VSWAP.
+                * If requested, skip over vnodes marked VROOT.
                 */
                if ((flags & SKIPROOT) && (vp->v_flag & VROOT)) {
                        vnode_unlock(vp);
                 */
                if ((flags & SKIPROOT) && (vp->v_flag & VROOT)) {
                        vnode_unlock(vp);
@@ -1795,15 +1919,17 @@ loop:
                 */
                if (((vp->v_usecount == 0) ||
                    ((vp->v_usecount - vp->v_kusecount) == 0))) {
                 */
                if (((vp->v_usecount == 0) ||
                    ((vp->v_usecount - vp->v_kusecount) == 0))) {
+
+                       vnode_lock_convert(vp);
                        vp->v_iocount++;        /* so that drain waits for * other iocounts */
 #ifdef JOE_DEBUG
                        record_vp(vp, 1);
 #endif
                        vp->v_iocount++;        /* so that drain waits for * other iocounts */
 #ifdef JOE_DEBUG
                        record_vp(vp, 1);
 #endif
-                       vnode_reclaim_internal(vp, 1, 0, 0);
+                       vnode_reclaim_internal(vp, 1, 1, 0);
                        vnode_dropiocount(vp);
                        vnode_list_add(vp);
                        vnode_dropiocount(vp);
                        vnode_list_add(vp);
-
                        vnode_unlock(vp);
                        vnode_unlock(vp);
+
                        reclaimed++;
                        mount_lock(mp);
                        continue;
                        reclaimed++;
                        mount_lock(mp);
                        continue;
@@ -1814,12 +1940,14 @@ loop:
                 * anonymous device. For all other files, just kill them.
                 */
                if (flags & FORCECLOSE) {
                 * anonymous device. For all other files, just kill them.
                 */
                if (flags & FORCECLOSE) {
+                       vnode_lock_convert(vp);
+
                        if (vp->v_type != VBLK && vp->v_type != VCHR) {
                                vp->v_iocount++;        /* so that drain waits * for other iocounts */
 #ifdef JOE_DEBUG
                                record_vp(vp, 1);
 #endif
                        if (vp->v_type != VBLK && vp->v_type != VCHR) {
                                vp->v_iocount++;        /* so that drain waits * for other iocounts */
 #ifdef JOE_DEBUG
                                record_vp(vp, 1);
 #endif
-                               vnode_reclaim_internal(vp, 1, 0, 0);
+                               vnode_reclaim_internal(vp, 1, 1, 0);
                                vnode_dropiocount(vp);
                                vnode_list_add(vp);
                                vnode_unlock(vp);
                                vnode_dropiocount(vp);
                                vnode_list_add(vp);
                                vnode_unlock(vp);
@@ -1864,7 +1992,7 @@ loop:
        return (0);
 }
 
        return (0);
 }
 
-long num_recycledvnodes = 0;   /* long for OSAddAtomic */
+long num_recycledvnodes = 0;
 /*
  * Disassociate the underlying file system from a vnode.
  * The vnode lock is held on entry.
 /*
  * Disassociate the underlying file system from a vnode.
  * The vnode lock is held on entry.
@@ -1877,6 +2005,9 @@ vclean(vnode_t vp, int flags)
        int need_inactive;
        int already_terminating;
        int clflags = 0;
        int need_inactive;
        int already_terminating;
        int clflags = 0;
+#if NAMEDSTREAMS
+       int is_namedstream;
+#endif
 
        /*
         * Check to see if the vnode is in use.
 
        /*
         * Check to see if the vnode is in use.
@@ -1908,13 +2039,13 @@ vclean(vnode_t vp, int flags)
         */
        insmntque(vp, (struct mount *)0);
 
         */
        insmntque(vp, (struct mount *)0);
 
+#if NAMEDSTREAMS
+       is_namedstream = vnode_isnamedstream(vp);
+#endif
+
        vnode_unlock(vp);
 
        vnode_unlock(vp);
 
-       OSAddAtomic(1, &num_recycledvnodes);
-       /*
-        * purge from the name cache as early as possible...
-        */
-       cache_purge(vp);
+       OSAddAtomicLong(1, &num_recycledvnodes);
 
        if (flags & DOCLOSE)
                clflags |= IO_NDELAY;
 
        if (flags & DOCLOSE)
                clflags |= IO_NDELAY;
@@ -1935,17 +2066,40 @@ vclean(vnode_t vp, int flags)
 #endif
                {
                        VNOP_FSYNC(vp, MNT_WAIT, ctx);
 #endif
                {
                        VNOP_FSYNC(vp, MNT_WAIT, ctx);
-                       buf_invalidateblks(vp, BUF_WRITE_DATA, 0, 0);
+                       buf_invalidateblks(vp, BUF_WRITE_DATA | BUF_INVALIDATE_LOCKED, 0, 0);
                }
                if (UBCINFOEXISTS(vp))
                        /*
                         * Clean the pages in VM.
                         */
                }
                if (UBCINFOEXISTS(vp))
                        /*
                         * Clean the pages in VM.
                         */
-                       (void)ubc_sync_range(vp, (off_t)0, ubc_getsize(vp), UBC_PUSHALL);
+                       (void)ubc_msync(vp, (off_t)0, ubc_getsize(vp), NULL, UBC_PUSHALL | UBC_INVALIDATE | UBC_SYNC);
        }
        if (active || need_inactive) 
                VNOP_INACTIVE(vp, ctx);
 
        }
        if (active || need_inactive) 
                VNOP_INACTIVE(vp, ctx);
 
+#if NAMEDSTREAMS
+       if ((is_namedstream != 0) && (vp->v_parent != NULLVP)) {
+               vnode_t pvp = vp->v_parent;
+           
+               /* Delete the shadow stream file before we reclaim its vnode */
+               if (vnode_isshadow(vp)) {
+                       vnode_relenamedstream(pvp, vp, ctx);
+               }
+               
+               /* 
+                * No more streams associated with the parent.  We
+                * have a ref on it, so its identity is stable.
+                * If the parent is on an opaque volume, then we need to know
+                * whether it has associated named streams.
+                */
+               if (vfs_authopaque(pvp->v_mount)) {
+                       vnode_lock_spin(pvp);
+                       pvp->v_lflag &= ~VL_HASSTREAMS;
+                       vnode_unlock(pvp);
+               }
+       }
+#endif
+
        /*
         * Destroy ubc named reference
         * cluster_release is done on this path
        /*
         * Destroy ubc named reference
         * cluster_release is done on this path
@@ -1953,6 +2107,14 @@ vclean(vnode_t vp, int flags)
         */
        ubc_destroy_named(vp);
 
         */
        ubc_destroy_named(vp);
 
+#if CONFIG_TRIGGERS
+       /*
+        * cleanup trigger info from vnode (if any)
+        */
+       if (vp->v_resolve)
+               vnode_resolver_detach(vp);
+#endif
+
        /*
         * Reclaim the vnode.
         */
        /*
         * Reclaim the vnode.
         */
@@ -1960,7 +2122,7 @@ vclean(vnode_t vp, int flags)
                panic("vclean: cannot reclaim");
        
        // make sure the name & parent ptrs get cleaned out!
                panic("vclean: cannot reclaim");
        
        // make sure the name & parent ptrs get cleaned out!
-       vnode_update_identity(vp, NULLVP, NULL, 0, 0, VNODE_UPDATE_PARENT | VNODE_UPDATE_NAME);
+       vnode_update_identity(vp, NULLVP, NULL, 0, 0, VNODE_UPDATE_PARENT | VNODE_UPDATE_NAME | VNODE_UPDATE_PURGE);
 
        vnode_lock(vp);
 
 
        vnode_lock(vp);
 
@@ -2002,23 +2164,20 @@ vn_revoke(vnode_t vp, __unused int flags, __unused vfs_context_t a_context)
                panic("vnop_revoke");
 #endif
 
                panic("vnop_revoke");
 #endif
 
-       if (vp->v_flag & VALIASED) {
+       if (vnode_isaliased(vp)) {
                /*
                 * If a vgone (or vclean) is already in progress,
                /*
                 * If a vgone (or vclean) is already in progress,
-                * wait until it is done and return.
+                * return an immediate error
                 */
                 */
-               vnode_lock(vp);
-               if (vp->v_lflag & VL_TERMINATE) {
-                       vnode_unlock(vp);
+               if (vp->v_lflag & VL_TERMINATE)
                        return(ENOENT);
                        return(ENOENT);
-               }
-               vnode_unlock(vp);
+
                /*
                 * Ensure that vp will not be vgone'd while we
                 * are eliminating its aliases.
                 */
                SPECHASH_LOCK();
                /*
                 * Ensure that vp will not be vgone'd while we
                 * are eliminating its aliases.
                 */
                SPECHASH_LOCK();
-               while (vp->v_flag & VALIASED) {
+               while ((vp->v_specflags & SI_ALIASED)) {
                        for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
                                if (vq->v_rdev != vp->v_rdev ||
                                    vq->v_type != vp->v_type || vp == vq)
                        for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
                                if (vq->v_rdev != vp->v_rdev ||
                                    vq->v_type != vp->v_type || vp == vq)
@@ -2029,7 +2188,7 @@ vn_revoke(vnode_t vp, __unused int flags, __unused vfs_context_t a_context)
                                        SPECHASH_LOCK();        
                                        break;
                                }
                                        SPECHASH_LOCK();        
                                        break;
                                }
-                               vnode_reclaim_internal(vq, 0, 0, 0);
+                               vnode_reclaim_internal(vq, 0, 1, 0);
                                vnode_put(vq);
                                SPECHASH_LOCK();
                                break;
                                vnode_put(vq);
                                SPECHASH_LOCK();
                                break;
@@ -2049,14 +2208,16 @@ vn_revoke(vnode_t vp, __unused int flags, __unused vfs_context_t a_context)
 int
 vnode_recycle(struct vnode *vp)
 {
 int
 vnode_recycle(struct vnode *vp)
 {
-       vnode_lock(vp);
+       vnode_lock_spin(vp);
 
        if (vp->v_iocount || vp->v_usecount) {
                vp->v_lflag |= VL_MARKTERM;
                vnode_unlock(vp);
                return(0);
        } 
 
        if (vp->v_iocount || vp->v_usecount) {
                vp->v_lflag |= VL_MARKTERM;
                vnode_unlock(vp);
                return(0);
        } 
+       vnode_lock_convert(vp);
        vnode_reclaim_internal(vp, 1, 0, 0);
        vnode_reclaim_internal(vp, 1, 0, 0);
+
        vnode_unlock(vp);
 
        return (1);
        vnode_unlock(vp);
 
        return (1);
@@ -2113,7 +2274,7 @@ vgone(vnode_t vp, int flags)
                        if (vq == NULL)
                                panic("missing bdev");
                        }
                        if (vq == NULL)
                                panic("missing bdev");
                        }
-                       if (vp->v_flag & VALIASED) {
+                       if (vp->v_specflags & SI_ALIASED) {
                                vx = NULL;
                                for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
                                        if (vq->v_rdev != vp->v_rdev ||
                                vx = NULL;
                                for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
                                        if (vq->v_rdev != vp->v_rdev ||
@@ -2126,8 +2287,8 @@ vgone(vnode_t vp, int flags)
                                if (vx == NULL)
                                        panic("missing alias");
                                if (vq == NULL)
                                if (vx == NULL)
                                        panic("missing alias");
                                if (vq == NULL)
-                                       vx->v_flag &= ~VALIASED;
-                               vp->v_flag &= ~VALIASED;
+                                       vx->v_specflags &= ~SI_ALIASED;
+                               vp->v_specflags &= ~SI_ALIASED;
                        }
                        SPECHASH_UNLOCK();
                        {
                        }
                        SPECHASH_UNLOCK();
                        {
@@ -2182,8 +2343,8 @@ vcount(vnode_t vp)
        int vid;
 
 loop:
        int vid;
 
 loop:
-       if ((vp->v_flag & VALIASED) == 0)
-               return (vp->v_usecount - vp->v_kusecount);
+       if (!vnode_isaliased(vp))
+               return (vp->v_specinfo->si_opencount);
        count = 0;
 
        SPECHASH_LOCK();
        count = 0;
 
        SPECHASH_LOCK();
@@ -2209,12 +2370,12 @@ loop:
                                /*
                                 * Alias, but not in use, so flush it out.
                                 */
                                /*
                                 * Alias, but not in use, so flush it out.
                                 */
-                               vnode_reclaim_internal(vq, 1, 0, 0);
+                               vnode_reclaim_internal(vq, 1, 1, 0);
+                               vnode_put_locked(vq);
                                vnode_unlock(vq);
                                vnode_unlock(vq);
-                               vnode_put(vq);
                                goto loop;
                        }
                                goto loop;
                        }
-                       count += (vq->v_usecount - vq->v_kusecount);
+                       count += vq->v_specinfo->si_opencount;
                }
                vnode_unlock(vq);
 
                }
                vnode_unlock(vq);
 
@@ -2242,10 +2403,8 @@ int      prtactive = 0;          /* 1 => print out reclaim of active vnodes */
 /*
  * Print out a description of a vnode.
  */
 /*
  * Print out a description of a vnode.
  */
-#if !CONFIG_NO_PRINTF_STRINGS
 static const char *typename[] =
    { "VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD" };
 static const char *typename[] =
    { "VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD" };
-#endif
 
 void
 vprint(const char *label, struct vnode *vp)
 
 void
 vprint(const char *label, struct vnode *vp)
@@ -2254,7 +2413,7 @@ vprint(const char *label, struct vnode *vp)
 
        if (label != NULL)
                printf("%s: ", label);
 
        if (label != NULL)
                printf("%s: ", label);
-       printf("type %s, usecount %d, writecount %ld",
+       printf("type %s, usecount %d, writecount %d",
               typename[vp->v_type], vp->v_usecount, vp->v_writecount);
        sbuf[0] = '\0';
        if (vp->v_flag & VROOT)
               typename[vp->v_type], vp->v_usecount, vp->v_writecount);
        sbuf[0] = '\0';
        if (vp->v_flag & VROOT)
@@ -2267,7 +2426,7 @@ vprint(const char *label, struct vnode *vp)
                strlcat(sbuf, "|VNOFLUSH", sizeof(sbuf));
        if (vp->v_flag & VBWAIT)
                strlcat(sbuf, "|VBWAIT", sizeof(sbuf));
                strlcat(sbuf, "|VNOFLUSH", sizeof(sbuf));
        if (vp->v_flag & VBWAIT)
                strlcat(sbuf, "|VBWAIT", sizeof(sbuf));
-       if (vp->v_flag & VALIASED)
+       if (vnode_isaliased(vp))
                strlcat(sbuf, "|VALIASED", sizeof(sbuf));
        if (sbuf[0] != '\0')
                printf(" flags (%s)", &sbuf[1]);
                strlcat(sbuf, "|VALIASED", sizeof(sbuf));
        if (sbuf[0] != '\0')
                printf(" flags (%s)", &sbuf[1]);
@@ -2280,6 +2439,11 @@ vn_getpath(struct vnode *vp, char *pathbuf, int *len)
        return build_path(vp, pathbuf, *len, len, BUILDPATH_NO_FS_ENTER, vfs_context_current());
 }
 
        return build_path(vp, pathbuf, *len, len, BUILDPATH_NO_FS_ENTER, vfs_context_current());
 }
 
+int
+vn_getpath_fsenter(struct vnode *vp, char *pathbuf, int *len)
+{
+       return build_path(vp, pathbuf, *len, len, 0, vfs_context_current());
+}
 
 int
 vn_getcdhash(struct vnode *vp, off_t offset, unsigned char *cdhash)
 
 int
 vn_getcdhash(struct vnode *vp, off_t offset, unsigned char *cdhash)
@@ -2311,32 +2475,47 @@ extension_cmp(const void *a, const void *b)
 // them (i.e. a short 8 character name can't have an 8
 // character extension).
 //
 // them (i.e. a short 8 character name can't have an 8
 // character extension).
 //
+extern lck_mtx_t *pkg_extensions_lck;
+
 __private_extern__ int
 __private_extern__ int
-set_package_extensions_table(void *data, int nentries, int maxwidth)
+set_package_extensions_table(user_addr_t data, int nentries, int maxwidth)
 {
 {
-    char *new_exts;
+    char *new_exts, *old_exts;
     int error;
     
     if (nentries <= 0 || nentries > 1024 || maxwidth <= 0 || maxwidth > 255) {
        return EINVAL;
     }
 
     int error;
     
     if (nentries <= 0 || nentries > 1024 || maxwidth <= 0 || maxwidth > 255) {
        return EINVAL;
     }
 
-    MALLOC(new_exts, char *, nentries * maxwidth, M_TEMP, M_WAITOK);
+
+    // allocate one byte extra so we can guarantee null termination
+    MALLOC(new_exts, char *, (nentries * maxwidth) + 1, M_TEMP, M_WAITOK);
+    if (new_exts == NULL) {
+       return ENOMEM;
+    }
     
     
-    error = copyin(CAST_USER_ADDR_T(data), new_exts, nentries * maxwidth);
+    error = copyin(data, new_exts, nentries * maxwidth);
     if (error) {
        FREE(new_exts, M_TEMP);
        return error;
     }
 
     if (error) {
        FREE(new_exts, M_TEMP);
        return error;
     }
 
-    if (extension_table) {
-       FREE(extension_table, M_TEMP);
-    }
+    new_exts[(nentries * maxwidth)] = '\0';   // guarantee null termination of the block
+
+    qsort(new_exts, nentries, maxwidth, extension_cmp);
+
+    lck_mtx_lock(pkg_extensions_lck);
+
+    old_exts        = extension_table;
     extension_table = new_exts;
     nexts           = nentries;
     max_ext_width   = maxwidth;
 
     extension_table = new_exts;
     nexts           = nentries;
     max_ext_width   = maxwidth;
 
-    qsort(extension_table, nexts, maxwidth, extension_cmp);
+    lck_mtx_unlock(pkg_extensions_lck);
+
+    if (old_exts) {
+       FREE(old_exts, M_TEMP);
+    }
 
     return 0;
 }
 
     return 0;
 }
@@ -2367,16 +2546,21 @@ is_package_name(const char *name, int len)
     // advance over the "."
     name_ext++;
 
     // advance over the "."
     name_ext++;
 
+    lck_mtx_lock(pkg_extensions_lck);
+
     // now iterate over all the extensions to see if any match
     ptr = &extension_table[0];
     for(i=0; i < nexts; i++, ptr+=max_ext_width) {
        extlen = strlen(ptr);
        if (strncasecmp(name_ext, ptr, extlen) == 0 && name_ext[extlen] == '\0') {
            // aha, a match!
     // now iterate over all the extensions to see if any match
     ptr = &extension_table[0];
     for(i=0; i < nexts; i++, ptr+=max_ext_width) {
        extlen = strlen(ptr);
        if (strncasecmp(name_ext, ptr, extlen) == 0 && name_ext[extlen] == '\0') {
            // aha, a match!
+           lck_mtx_unlock(pkg_extensions_lck);
            return 1;
        }
     }
 
            return 1;
        }
     }
 
+    lck_mtx_unlock(pkg_extensions_lck);
+
     // if we get here, no extension matched
     return 0;
 }
     // if we get here, no extension matched
     return 0;
 }
@@ -2422,6 +2606,25 @@ vn_path_package_check(__unused vnode_t vp, char *path, int pathlen, int *compone
     return 0;
 }
 
     return 0;
 }
 
+/* 
+ * Determine if a name is inappropriate for a searchfs query.
+ * This list consists of /System currently.
+ */
+
+int vn_searchfs_inappropriate_name(const char *name, int len) {
+       const char *bad_names[] = { "System" };
+       int   bad_len[]   = { 6 };
+       int  i;
+
+       for(i=0; i < (int) (sizeof(bad_names) / sizeof(bad_names[0])); i++) {
+               if (len == bad_len[i] && strncmp(name, bad_names[i], strlen(bad_names[i]) + 1) == 0) {
+                       return 1;
+               }
+       }
+
+       // if we get here, no name matched
+       return 0;
+}
 
 /*
  * Top level filesystem related information gathering.
 
 /*
  * Top level filesystem related information gathering.
@@ -2436,7 +2639,7 @@ vfs_sysctl(int *name, u_int namelen, user_addr_t oldp, size_t *oldlenp,
        int *username;
        u_int usernamelen;
        int error;
        int *username;
        u_int usernamelen;
        int error;
-       struct vfsconf *vfsc;
+       struct vfsconf vfsc;
 
        /* All non VFS_GENERIC and in VFS_GENERIC, 
         * VFS_MAXTYPENUM, VFS_CONF, VFS_SET_PACKAGE_EXTS
 
        /* All non VFS_GENERIC and in VFS_GENERIC, 
         * VFS_MAXTYPENUM, VFS_CONF, VFS_SET_PACKAGE_EXTS
@@ -2468,16 +2671,27 @@ vfs_sysctl(int *name, u_int namelen, user_addr_t oldp, size_t *oldlenp,
        if (namelen < 2)
                return (EISDIR);                /* overloaded */
        if (name[0] != VFS_GENERIC) {
        if (namelen < 2)
                return (EISDIR);                /* overloaded */
        if (name[0] != VFS_GENERIC) {
-               for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
-                       if (vfsp->vfc_typenum == name[0])
+
+               mount_list_lock();
+               for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) 
+                       if (vfsp->vfc_typenum == name[0]) {
+                               vfsp->vfc_refcount++;
                                break;
                                break;
+                       }
+               mount_list_unlock();
+
                if (vfsp == NULL)
                        return (ENOTSUP);
 
                /* XXX current context proxy for proc p? */
                if (vfsp == NULL)
                        return (ENOTSUP);
 
                /* XXX current context proxy for proc p? */
-               return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
+               error = ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
                            oldp, oldlenp, newp, newlen,
                            vfs_context_current()));
                            oldp, oldlenp, newp, newlen,
                            vfs_context_current()));
+
+               mount_list_lock();
+               vfsp->vfc_refcount--;
+               mount_list_unlock();
+               return error;
        }
        switch (name[1]) {
        case VFS_MAXTYPENUM:
        }
        switch (name[1]) {
        case VFS_MAXTYPENUM:
@@ -2485,31 +2699,31 @@ vfs_sysctl(int *name, u_int namelen, user_addr_t oldp, size_t *oldlenp,
        case VFS_CONF:
                if (namelen < 3)
                        return (ENOTDIR);       /* overloaded */
        case VFS_CONF:
                if (namelen < 3)
                        return (ENOTDIR);       /* overloaded */
+
+               mount_list_lock();
                for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
                        if (vfsp->vfc_typenum == name[2])
                                break;
                for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
                        if (vfsp->vfc_typenum == name[2])
                                break;
-               if (vfsp == NULL)
+
+               if (vfsp == NULL) {
+                       mount_list_unlock();
                        return (ENOTSUP);
                        return (ENOTSUP);
-               vfsc = (struct vfsconf *)vfsp;
-               if (proc_is64bit(p)) {
-                   struct user_vfsconf  usr_vfsc;
-                   usr_vfsc.vfc_vfsops = CAST_USER_ADDR_T(vfsc->vfc_vfsops);
-               bcopy(vfsc->vfc_name, usr_vfsc.vfc_name, sizeof(usr_vfsc.vfc_name));
-                   usr_vfsc.vfc_typenum = vfsc->vfc_typenum;
-                   usr_vfsc.vfc_refcount = vfsc->vfc_refcount;
-                   usr_vfsc.vfc_flags = vfsc->vfc_flags;
-                   usr_vfsc.vfc_mountroot = CAST_USER_ADDR_T(vfsc->vfc_mountroot);
-                   usr_vfsc.vfc_next = CAST_USER_ADDR_T(vfsc->vfc_next);
-            return (sysctl_rdstruct(oldp, oldlenp, newp, &usr_vfsc,
-                                    sizeof(usr_vfsc)));
-               }
-               else {
-            return (sysctl_rdstruct(oldp, oldlenp, newp, vfsc,
-                                    sizeof(struct vfsconf)));
                }
                }
+
+               vfsc.vfc_reserved1 = 0;
+               bcopy(vfsp->vfc_name, vfsc.vfc_name, sizeof(vfsc.vfc_name));
+               vfsc.vfc_typenum = vfsp->vfc_typenum;
+               vfsc.vfc_refcount = vfsp->vfc_refcount;
+               vfsc.vfc_flags = vfsp->vfc_flags;
+               vfsc.vfc_reserved2 = 0;
+               vfsc.vfc_reserved3 = 0;
+
+               mount_list_unlock();
+               return (sysctl_rdstruct(oldp, oldlenp, newp, &vfsc,
+                                       sizeof(struct vfsconf)));
                
        case VFS_SET_PACKAGE_EXTS:
                
        case VFS_SET_PACKAGE_EXTS:
-               return set_package_extensions_table((void *)name[1], name[2], name[3]);
+               return set_package_extensions_table((user_addr_t)((unsigned)name[1]), name[2], name[3]);
        }
        /*
         * We need to get back into the general MIB, so we need to re-prepend
        }
        /*
         * We need to get back into the general MIB, so we need to re-prepend
@@ -2521,7 +2735,7 @@ vfs_sysctl(int *name, u_int namelen, user_addr_t oldp, size_t *oldlenp,
        bcopy(name, username + 1, namelen * sizeof(*name));
        username[0] = CTL_VFS;
        error = userland_sysctl(p, username, usernamelen, oldp, 
        bcopy(name, username + 1, namelen * sizeof(*name));
        username[0] = CTL_VFS;
        error = userland_sysctl(p, username, usernamelen, oldp, 
-                               oldlenp, 1, newp, newlen, oldlenp);
+                               oldlenp, newp, newlen, oldlenp);
        FREE(username, M_TEMP);
        return (error);
 }
        FREE(username, M_TEMP);
        return (error);
 }
@@ -2539,7 +2753,7 @@ sysctl_vnode
 }
 
 SYSCTL_PROC(_kern, KERN_VNODE, vnode,
 }
 
 SYSCTL_PROC(_kern, KERN_VNODE, vnode,
-               CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_MASKED,
+               CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_MASKED | CTLFLAG_LOCKED,
                0, 0, sysctl_vnode, "S,", "");
 
 
                0, 0, sysctl_vnode, "S,", "");
 
 
@@ -2557,7 +2771,7 @@ vfs_mountedon(struct vnode *vp)
                error = EBUSY;
                goto out;
        }
                error = EBUSY;
                goto out;
        }
-       if (vp->v_flag & VALIASED) {
+       if (vp->v_specflags & SI_ALIASED) {
                for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
                        if (vq->v_rdev != vp->v_rdev ||
                            vq->v_type != vp->v_type)
                for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
                        if (vq->v_rdev != vp->v_rdev ||
                            vq->v_type != vp->v_type)
@@ -2599,7 +2813,7 @@ vfs_unmountall(void)
                        continue;
                } else if (error == EBUSY) {
                        /* If EBUSY is returned,  the unmount was already in progress */
                        continue;
                } else if (error == EBUSY) {
                        /* If EBUSY is returned,  the unmount was already in progress */
-                       printf("unmount of %x failed (", (unsigned int)mp);
+                       printf("unmount of %p failed (", mp);
                        printf("BUSY)\n");      
                } 
                mount_list_lock();
                        printf("BUSY)\n");      
                } 
                mount_list_lock();
@@ -2618,58 +2832,62 @@ vnode_pager_vrele(vnode_t vp)
 {
         struct ubc_info *uip;
 
 {
         struct ubc_info *uip;
 
-       vnode_lock(vp);
+       vnode_lock_spin(vp);
 
        vp->v_lflag &= ~VNAMED_UBC;
 
        uip = vp->v_ubcinfo;
        vp->v_ubcinfo = UBC_INFO_NULL;
 
 
        vp->v_lflag &= ~VNAMED_UBC;
 
        uip = vp->v_ubcinfo;
        vp->v_ubcinfo = UBC_INFO_NULL;
 
-       ubc_info_deallocate(uip);
-
        vnode_unlock(vp);
        vnode_unlock(vp);
+
+       ubc_info_deallocate(uip);
 }
 
 
 #include <sys/disk.h>
 
 }
 
 
 #include <sys/disk.h>
 
+u_int32_t rootunit = (u_int32_t)-1;
+
 errno_t
 vfs_init_io_attributes(vnode_t devvp, mount_t mp)
 {
        int     error;
 errno_t
 vfs_init_io_attributes(vnode_t devvp, mount_t mp)
 {
        int     error;
-       off_t   readblockcnt;
-       off_t   writeblockcnt;
-       off_t   readmaxcnt;
-       off_t   writemaxcnt;
-       off_t   readsegcnt;
-       off_t   writesegcnt;
-       off_t   readsegsize;
-       off_t   writesegsize;
-       off_t   alignment;
-       u_long  blksize;
+       off_t   readblockcnt = 0;
+       off_t   writeblockcnt = 0;
+       off_t   readmaxcnt = 0;
+       off_t   writemaxcnt = 0;
+       off_t   readsegcnt = 0;
+       off_t   writesegcnt = 0;
+       off_t   readsegsize = 0;
+       off_t   writesegsize = 0;
+       off_t   alignment = 0;
+       off_t   ioqueue_depth = 0;
+       u_int32_t blksize;
        u_int64_t temp;
        u_int32_t features;
        vfs_context_t ctx = vfs_context_current();
        u_int64_t temp;
        u_int32_t features;
        vfs_context_t ctx = vfs_context_current();
-
+       int isssd = 0;
        int isvirtual = 0;
        int isvirtual = 0;
+
+
+       VNOP_IOCTL(devvp, DKIOCGETTHROTTLEMASK, (caddr_t)&mp->mnt_throttle_mask, 0, NULL);
        /*
        /*
-        * determine if this mount point exists on the same device as the root
-        * partition... if so, then it comes under the hard throttle control
+        * as a reasonable approximation, only use the lowest bit of the mask
+        * to generate a disk unit number
         */
         */
-       int        thisunit = -1;
-       static int rootunit = -1;
+       mp->mnt_devbsdunit = num_trailing_0(mp->mnt_throttle_mask);
 
 
-       if (rootunit == -1) {
-               if (VNOP_IOCTL(rootvp, DKIOCGETBSDUNIT, (caddr_t)&rootunit, 0, ctx))
-                       rootunit = -1; 
-               else if (rootvp == devvp)
-                       mp->mnt_kern_flag |= MNTK_ROOTDEV;
-       }
-       if (devvp != rootvp && rootunit != -1) {
-               if (VNOP_IOCTL(devvp, DKIOCGETBSDUNIT, (caddr_t)&thisunit, 0, ctx) == 0) {
-                       if (thisunit == rootunit)
-                               mp->mnt_kern_flag |= MNTK_ROOTDEV;
-               }
+       if (devvp == rootvp)
+               rootunit = mp->mnt_devbsdunit;
+
+       if (mp->mnt_devbsdunit == rootunit) {
+               /*
+                * this mount point exists on the same device as the root
+                * partition, so it comes under the hard throttle control...
+                * this is true even for the root mount point itself
+                */
+               mp->mnt_kern_flag |= MNTK_ROOTDEV;
        }
        /*
         * force the spec device to re-cache
        }
        /*
         * force the spec device to re-cache
@@ -2685,11 +2903,24 @@ vfs_init_io_attributes(vnode_t devvp, mount_t mp)
 
        mp->mnt_devblocksize = blksize;
 
 
        mp->mnt_devblocksize = blksize;
 
+       /*
+        * set the maximum possible I/O size
+        * this may get clipped to a smaller value
+        * based on which constraints are being advertised
+        * and if those advertised constraints result in a smaller
+        * limit for a given I/O
+        */
+       mp->mnt_maxreadcnt = MAX_UPL_SIZE * PAGE_SIZE;
+       mp->mnt_maxwritecnt = MAX_UPL_SIZE * PAGE_SIZE;
+
        if (VNOP_IOCTL(devvp, DKIOCISVIRTUAL, (caddr_t)&isvirtual, 0, ctx) == 0) {
                if (isvirtual)
                        mp->mnt_kern_flag |= MNTK_VIRTUALDEV;
        }
        if (VNOP_IOCTL(devvp, DKIOCISVIRTUAL, (caddr_t)&isvirtual, 0, ctx) == 0) {
                if (isvirtual)
                        mp->mnt_kern_flag |= MNTK_VIRTUALDEV;
        }
-
+       if (VNOP_IOCTL(devvp, DKIOCISSOLIDSTATE, (caddr_t)&isssd, 0, ctx) == 0) {
+               if (isssd)
+                       mp->mnt_kern_flag |= MNTK_SSD;
+       }
        if ((error = VNOP_IOCTL(devvp, DKIOCGETFEATURES,
                                (caddr_t)&features, 0, ctx)))
                return (error);
        if ((error = VNOP_IOCTL(devvp, DKIOCGETFEATURES,
                                (caddr_t)&features, 0, ctx)))
                return (error);
@@ -2730,36 +2961,52 @@ vfs_init_io_attributes(vnode_t devvp, mount_t mp)
                                (caddr_t)&alignment, 0, ctx)))
                return (error);
 
                                (caddr_t)&alignment, 0, ctx)))
                return (error);
 
+       if ((error = VNOP_IOCTL(devvp, DKIOCGETCOMMANDPOOLSIZE,
+                               (caddr_t)&ioqueue_depth, 0, ctx)))
+               return (error);
+
        if (readmaxcnt)
        if (readmaxcnt)
-               temp = (readmaxcnt > UINT32_MAX) ? UINT32_MAX : readmaxcnt;
-       else {
-               if (readblockcnt) {
-                       temp = readblockcnt * blksize;
-                       temp = (temp > UINT32_MAX) ? UINT32_MAX : temp;
-               } else
-                       temp = MAXPHYS;
+               mp->mnt_maxreadcnt = (readmaxcnt > UINT32_MAX) ? UINT32_MAX : readmaxcnt;
+
+       if (readblockcnt) {
+               temp = readblockcnt * blksize;
+               temp = (temp > UINT32_MAX) ? UINT32_MAX : temp;
+
+               if (temp < mp->mnt_maxreadcnt)
+                       mp->mnt_maxreadcnt = (u_int32_t)temp;
        }
        }
-       mp->mnt_maxreadcnt = (u_int32_t)temp;
 
        if (writemaxcnt)
 
        if (writemaxcnt)
-               temp = (writemaxcnt > UINT32_MAX) ? UINT32_MAX : writemaxcnt;
-       else {
-               if (writeblockcnt) {
-                       temp = writeblockcnt * blksize;
-                       temp = (temp > UINT32_MAX) ? UINT32_MAX : temp;
-               } else
-                       temp = MAXPHYS;
+               mp->mnt_maxwritecnt = (writemaxcnt > UINT32_MAX) ? UINT32_MAX : writemaxcnt;
+
+       if (writeblockcnt) {
+               temp = writeblockcnt * blksize;
+               temp = (temp > UINT32_MAX) ? UINT32_MAX : temp;
+
+               if (temp < mp->mnt_maxwritecnt)
+                       mp->mnt_maxwritecnt = (u_int32_t)temp;
        }
        }
-       mp->mnt_maxwritecnt = (u_int32_t)temp;
 
        if (readsegcnt) {
                temp = (readsegcnt > UINT16_MAX) ? UINT16_MAX : readsegcnt;
 
        if (readsegcnt) {
                temp = (readsegcnt > UINT16_MAX) ? UINT16_MAX : readsegcnt;
-               mp->mnt_segreadcnt = (u_int16_t)temp;
+       } else {
+               temp = mp->mnt_maxreadcnt / PAGE_SIZE;
+
+               if (temp > UINT16_MAX)
+                       temp = UINT16_MAX;
        }
        }
+       mp->mnt_segreadcnt = (u_int16_t)temp;
+
        if (writesegcnt) {
                temp = (writesegcnt > UINT16_MAX) ? UINT16_MAX : writesegcnt;
        if (writesegcnt) {
                temp = (writesegcnt > UINT16_MAX) ? UINT16_MAX : writesegcnt;
-               mp->mnt_segwritecnt = (u_int16_t)temp;
+       } else {
+               temp = mp->mnt_maxwritecnt / PAGE_SIZE;
+
+               if (temp > UINT16_MAX)
+                       temp = UINT16_MAX;
        }
        }
+       mp->mnt_segwritecnt = (u_int16_t)temp;
+
        if (readsegsize)
                temp = (readsegsize > UINT32_MAX) ? UINT32_MAX : readsegsize;
        else
        if (readsegsize)
                temp = (readsegsize > UINT32_MAX) ? UINT32_MAX : readsegsize;
        else
@@ -2778,26 +3025,44 @@ vfs_init_io_attributes(vnode_t devvp, mount_t mp)
                temp = 0;
        mp->mnt_alignmentmask = temp;
 
                temp = 0;
        mp->mnt_alignmentmask = temp;
 
+
+       if (ioqueue_depth > MNT_DEFAULT_IOQUEUE_DEPTH)
+               temp = ioqueue_depth;
+       else
+               temp = MNT_DEFAULT_IOQUEUE_DEPTH;
+
+       mp->mnt_ioqueue_depth = temp;
+       mp->mnt_ioscale = (mp->mnt_ioqueue_depth + (MNT_DEFAULT_IOQUEUE_DEPTH - 1)) / MNT_DEFAULT_IOQUEUE_DEPTH;
+
+       if (mp->mnt_ioscale > 1)
+               printf("ioqueue_depth = %d,   ioscale = %d\n", (int)mp->mnt_ioqueue_depth, (int)mp->mnt_ioscale);
+
        if (features & DK_FEATURE_FORCE_UNIT_ACCESS)
                mp->mnt_ioflags |= MNT_IOFLAGS_FUA_SUPPORTED;
        if (features & DK_FEATURE_FORCE_UNIT_ACCESS)
                mp->mnt_ioflags |= MNT_IOFLAGS_FUA_SUPPORTED;
-       
+       if (features & DK_FEATURE_UNMAP)
+               mp->mnt_ioflags |= MNT_IOFLAGS_UNMAP_SUPPORTED;
        return (error);
 }
 
 static struct klist fs_klist;
        return (error);
 }
 
 static struct klist fs_klist;
+lck_grp_t *fs_klist_lck_grp;
+lck_mtx_t *fs_klist_lock;
 
 void
 vfs_event_init(void)
 {
 
        klist_init(&fs_klist);
 
 void
 vfs_event_init(void)
 {
 
        klist_init(&fs_klist);
+       fs_klist_lck_grp = lck_grp_alloc_init("fs_klist", NULL);
+       fs_klist_lock = lck_mtx_alloc_init(fs_klist_lck_grp, NULL);
 }
 
 void
 vfs_event_signal(__unused fsid_t *fsid, u_int32_t event, __unused intptr_t data)
 {
 }
 
 void
 vfs_event_signal(__unused fsid_t *fsid, u_int32_t event, __unused intptr_t data)
 {
-
+       lck_mtx_lock(fs_klist_lock);
        KNOTE(&fs_klist, event);
        KNOTE(&fs_klist, event);
+       lck_mtx_unlock(fs_klist_lock);
 }
 
 /*
 }
 
 /*
@@ -2896,6 +3161,10 @@ again:
                return (ENOMEM);
 
        MALLOC(fsidlst, fsid_t *, req->oldlen, M_TEMP, M_WAITOK);
                return (ENOMEM);
 
        MALLOC(fsidlst, fsid_t *, req->oldlen, M_TEMP, M_WAITOK);
+       if (fsidlst == NULL) {
+               return (ENOMEM);
+       }
+
        error = sysctl_vfs_getvfslist(fsidlst, req->oldlen / sizeof(fsid_t),
            &actual);
        /*
        error = sysctl_vfs_getvfslist(fsidlst, req->oldlen / sizeof(fsid_t),
            &actual);
        /*
@@ -2921,8 +3190,7 @@ static int
 sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid *oidp, void *arg1, int arg2,
                struct sysctl_req *req)
 {
 sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid *oidp, void *arg1, int arg2,
                struct sysctl_req *req)
 {
-       struct vfsidctl vc;
-       struct user_vfsidctl user_vc;
+       union union_vfsidctl vc;
        struct mount *mp;
        struct vfsstatfs *sp;
        int *name, flags, namelen;
        struct mount *mp;
        struct vfsstatfs *sp;
        int *name, flags, namelen;
@@ -2935,26 +3203,14 @@ sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid *oidp, void *arg1, int arg2,
        namelen = arg2;
        is_64_bit = proc_is64bit(p);
 
        namelen = arg2;
        is_64_bit = proc_is64bit(p);
 
-       if (is_64_bit) {
-               error = SYSCTL_IN(req, &user_vc, sizeof(user_vc));
-               if (error)
-                       goto out;
-               if (user_vc.vc_vers != VFS_CTL_VERS1) {
-                       error = EINVAL;
-                       goto out;
-               }
-               mp = mount_list_lookupby_fsid(&user_vc.vc_fsid, 0, 1);
-       } 
-       else {
-               error = SYSCTL_IN(req, &vc, sizeof(vc));
-               if (error)
-                       goto out;
-               if (vc.vc_vers != VFS_CTL_VERS1) {
-                       error = EINVAL;
-                       goto out;
-               }
-               mp = mount_list_lookupby_fsid(&vc.vc_fsid, 0, 1);
+       error = SYSCTL_IN(req, &vc, is_64_bit? sizeof(vc.vc64):sizeof(vc.vc32));
+       if (error)
+               goto out;
+       if (vc.vc32.vc_vers != VFS_CTL_VERS1) { /* works for 32 and 64 */
+               error = EINVAL;
+               goto out;
        }
        }
+       mp = mount_list_lookupby_fsid(&vc.vc32.vc_fsid, 0, 1); /* works for 32 and 64 */
        if (mp == NULL) {
                error = ENOENT;
                goto out;
        if (mp == NULL) {
                error = ENOENT;
                goto out;
@@ -2993,12 +3249,12 @@ sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid *oidp, void *arg1, int arg2,
        case VFS_CTL_UMOUNT:
                req->newidx = 0;
                if (is_64_bit) {
        case VFS_CTL_UMOUNT:
                req->newidx = 0;
                if (is_64_bit) {
-                       req->newptr = user_vc.vc_ptr;
-                       req->newlen = (size_t)user_vc.vc_len;
+                       req->newptr = vc.vc64.vc_ptr;
+                       req->newlen = (size_t)vc.vc64.vc_len;
                }
                else {
                }
                else {
-                       req->newptr = CAST_USER_ADDR_T(vc.vc_ptr);
-                       req->newlen = vc.vc_len;
+                       req->newptr = CAST_USER_ADDR_T(vc.vc32.vc_ptr);
+                       req->newlen = vc.vc32.vc_len;
                }
                error = SYSCTL_IN(req, &flags, sizeof(flags));
                if (error)
                }
                error = SYSCTL_IN(req, &flags, sizeof(flags));
                if (error)
@@ -3013,44 +3269,48 @@ sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid *oidp, void *arg1, int arg2,
        case VFS_CTL_STATFS:
                req->newidx = 0;
                if (is_64_bit) {
        case VFS_CTL_STATFS:
                req->newidx = 0;
                if (is_64_bit) {
-                       req->newptr = user_vc.vc_ptr;
-                       req->newlen = (size_t)user_vc.vc_len;
+                       req->newptr = vc.vc64.vc_ptr;
+                       req->newlen = (size_t)vc.vc64.vc_len;
                }
                else {
                }
                else {
-                       req->newptr = CAST_USER_ADDR_T(vc.vc_ptr);
-                       req->newlen = vc.vc_len;
+                       req->newptr = CAST_USER_ADDR_T(vc.vc32.vc_ptr);
+                       req->newlen = vc.vc32.vc_len;
                }
                error = SYSCTL_IN(req, &flags, sizeof(flags));
                if (error)
                        break;
                sp = &mp->mnt_vfsstat;
                }
                error = SYSCTL_IN(req, &flags, sizeof(flags));
                if (error)
                        break;
                sp = &mp->mnt_vfsstat;
-               if (((flags & MNT_NOWAIT) == 0 || (flags & MNT_WAIT)) &&
+               if (((flags & MNT_NOWAIT) == 0 || (flags & (MNT_WAIT | MNT_DWAIT))) &&
                    (error = vfs_update_vfsstat(mp, ctx, VFS_USER_EVENT)))
                        goto out;
                if (is_64_bit) {
                    (error = vfs_update_vfsstat(mp, ctx, VFS_USER_EVENT)))
                        goto out;
                if (is_64_bit) {
-                       struct user_statfs sfs;
+                       struct user64_statfs sfs;
                        bzero(&sfs, sizeof(sfs));
                        sfs.f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
                        sfs.f_type = mp->mnt_vtable->vfc_typenum;
                        bzero(&sfs, sizeof(sfs));
                        sfs.f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
                        sfs.f_type = mp->mnt_vtable->vfc_typenum;
-                       sfs.f_bsize = (user_long_t)sp->f_bsize;
-                       sfs.f_iosize = (user_long_t)sp->f_iosize;
-                       sfs.f_blocks = (user_long_t)sp->f_blocks;
-                       sfs.f_bfree = (user_long_t)sp->f_bfree;
-                       sfs.f_bavail = (user_long_t)sp->f_bavail;
-                       sfs.f_files = (user_long_t)sp->f_files;
-                       sfs.f_ffree = (user_long_t)sp->f_ffree;
+                       sfs.f_bsize = (user64_long_t)sp->f_bsize;
+                       sfs.f_iosize = (user64_long_t)sp->f_iosize;
+                       sfs.f_blocks = (user64_long_t)sp->f_blocks;
+                       sfs.f_bfree = (user64_long_t)sp->f_bfree;
+                       sfs.f_bavail = (user64_long_t)sp->f_bavail;
+                       sfs.f_files = (user64_long_t)sp->f_files;
+                       sfs.f_ffree = (user64_long_t)sp->f_ffree;
                        sfs.f_fsid = sp->f_fsid;
                        sfs.f_owner = sp->f_owner;
     
                        sfs.f_fsid = sp->f_fsid;
                        sfs.f_owner = sp->f_owner;
     
-                       strlcpy(sfs.f_fstypename, sp->f_fstypename, MFSNAMELEN);
+                       if (mp->mnt_kern_flag & MNTK_TYPENAME_OVERRIDE) {
+                               strlcpy(&sfs.f_fstypename[0], &mp->fstypename_override[0], MFSTYPENAMELEN);
+                       } else {
+                               strlcpy(sfs.f_fstypename, sp->f_fstypename, MFSNAMELEN);
+                       }
                        strlcpy(sfs.f_mntonname, sp->f_mntonname, MNAMELEN);
                        strlcpy(sfs.f_mntfromname, sp->f_mntfromname, MNAMELEN);
             
                        error = SYSCTL_OUT(req, &sfs, sizeof(sfs));
                }
                else {
                        strlcpy(sfs.f_mntonname, sp->f_mntonname, MNAMELEN);
                        strlcpy(sfs.f_mntfromname, sp->f_mntfromname, MNAMELEN);
             
                        error = SYSCTL_OUT(req, &sfs, sizeof(sfs));
                }
                else {
-                       struct statfs sfs;
-                       bzero(&sfs, sizeof(struct statfs));
+                       struct user32_statfs sfs;
+                       bzero(&sfs, sizeof(sfs));
                        sfs.f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
                        sfs.f_type = mp->mnt_vtable->vfc_typenum;
 
                        sfs.f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
                        sfs.f_type = mp->mnt_vtable->vfc_typenum;
 
@@ -3059,7 +3319,7 @@ sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid *oidp, void *arg1, int arg2,
                         * have to fudge the numbers here in that case.   We inflate the blocksize in order
                         * to reflect the filesystem size as best we can.
                         */
                         * have to fudge the numbers here in that case.   We inflate the blocksize in order
                         * to reflect the filesystem size as best we can.
                         */
-                       if (sp->f_blocks > LONG_MAX) {
+                       if (sp->f_blocks > INT_MAX) {
                                int             shift;
 
                                /*
                                int             shift;
 
                                /*
@@ -3072,31 +3332,35 @@ sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid *oidp, void *arg1, int arg2,
                                 * being smaller than f_bsize.
                                 */
                                for (shift = 0; shift < 32; shift++) {
                                 * being smaller than f_bsize.
                                 */
                                for (shift = 0; shift < 32; shift++) {
-                                       if ((sp->f_blocks >> shift) <= LONG_MAX)
+                                       if ((sp->f_blocks >> shift) <= INT_MAX)
                                                break;
                                                break;
-                                       if ((sp->f_bsize << (shift + 1)) > LONG_MAX)
+                                       if ((((long long)sp->f_bsize) << (shift + 1)) > INT_MAX)
                                                break;
                                }
                                                break;
                                }
-#define __SHIFT_OR_CLIP(x, s)  ((((x) >> (s)) > LONG_MAX) ? LONG_MAX : ((x) >> (s)))
-                               sfs.f_blocks = (long)__SHIFT_OR_CLIP(sp->f_blocks, shift);
-                               sfs.f_bfree = (long)__SHIFT_OR_CLIP(sp->f_bfree, shift);
-                               sfs.f_bavail = (long)__SHIFT_OR_CLIP(sp->f_bavail, shift);
+#define __SHIFT_OR_CLIP(x, s)  ((((x) >> (s)) > INT_MAX) ? INT_MAX : ((x) >> (s)))
+                               sfs.f_blocks = (user32_long_t)__SHIFT_OR_CLIP(sp->f_blocks, shift);
+                               sfs.f_bfree = (user32_long_t)__SHIFT_OR_CLIP(sp->f_bfree, shift);
+                               sfs.f_bavail = (user32_long_t)__SHIFT_OR_CLIP(sp->f_bavail, shift);
 #undef __SHIFT_OR_CLIP
 #undef __SHIFT_OR_CLIP
-                               sfs.f_bsize = (long)(sp->f_bsize << shift);
+                               sfs.f_bsize = (user32_long_t)(sp->f_bsize << shift);
                                sfs.f_iosize = lmax(sp->f_iosize, sp->f_bsize);
                        } else {
                                sfs.f_iosize = lmax(sp->f_iosize, sp->f_bsize);
                        } else {
-                               sfs.f_bsize = (long)sp->f_bsize;
-                               sfs.f_iosize = (long)sp->f_iosize;
-                               sfs.f_blocks = (long)sp->f_blocks;
-                               sfs.f_bfree = (long)sp->f_bfree;
-                               sfs.f_bavail = (long)sp->f_bavail;
+                               sfs.f_bsize = (user32_long_t)sp->f_bsize;
+                               sfs.f_iosize = (user32_long_t)sp->f_iosize;
+                               sfs.f_blocks = (user32_long_t)sp->f_blocks;
+                               sfs.f_bfree = (user32_long_t)sp->f_bfree;
+                               sfs.f_bavail = (user32_long_t)sp->f_bavail;
                        }
                        }
-                       sfs.f_files = (long)sp->f_files;
-                       sfs.f_ffree = (long)sp->f_ffree;
+                       sfs.f_files = (user32_long_t)sp->f_files;
+                       sfs.f_ffree = (user32_long_t)sp->f_ffree;
                        sfs.f_fsid = sp->f_fsid;
                        sfs.f_owner = sp->f_owner;
     
                        sfs.f_fsid = sp->f_fsid;
                        sfs.f_owner = sp->f_owner;
     
-                       strlcpy(sfs.f_fstypename, sp->f_fstypename, MFSNAMELEN);
+                       if (mp->mnt_kern_flag & MNTK_TYPENAME_OVERRIDE) {
+                               strlcpy(&sfs.f_fstypename[0], &mp->fstypename_override[0], MFSTYPENAMELEN);
+                       } else {
+                               strlcpy(sfs.f_fstypename, sp->f_fstypename, MFSNAMELEN);
+                       }
                        strlcpy(sfs.f_mntonname, sp->f_mntonname, MNAMELEN);
                        strlcpy(sfs.f_mntfromname, sp->f_mntfromname, MNAMELEN);
             
                        strlcpy(sfs.f_mntonname, sp->f_mntonname, MNAMELEN);
                        strlcpy(sfs.f_mntfromname, sp->f_mntfromname, MNAMELEN);
             
@@ -3116,24 +3380,29 @@ out:
 static int     filt_fsattach(struct knote *kn);
 static void    filt_fsdetach(struct knote *kn);
 static int     filt_fsevent(struct knote *kn, long hint);
 static int     filt_fsattach(struct knote *kn);
 static void    filt_fsdetach(struct knote *kn);
 static int     filt_fsevent(struct knote *kn, long hint);
-
-struct filterops fs_filtops =
-       { 0, filt_fsattach, filt_fsdetach, filt_fsevent };
+struct filterops fs_filtops = {
+        .f_attach = filt_fsattach,
+        .f_detach = filt_fsdetach,
+        .f_event = filt_fsevent,
+};
 
 static int
 filt_fsattach(struct knote *kn)
 {
 
 
 static int
 filt_fsattach(struct knote *kn)
 {
 
+       lck_mtx_lock(fs_klist_lock);
        kn->kn_flags |= EV_CLEAR;
        KNOTE_ATTACH(&fs_klist, kn);
        kn->kn_flags |= EV_CLEAR;
        KNOTE_ATTACH(&fs_klist, kn);
+       lck_mtx_unlock(fs_klist_lock);
        return (0);
 }
 
 static void
 filt_fsdetach(struct knote *kn)
 {
        return (0);
 }
 
 static void
 filt_fsdetach(struct knote *kn)
 {
-
+       lck_mtx_lock(fs_klist_lock);
        KNOTE_DETACH(&fs_klist, kn);
        KNOTE_DETACH(&fs_klist, kn);
+       lck_mtx_unlock(fs_klist_lock);
 }
 
 static int
 }
 
 static int
@@ -3189,27 +3458,27 @@ sysctl_vfs_noremotehang(__unused struct sysctl_oid *oidp,
        }
 
        if (pid < 0)
        }
 
        if (pid < 0)
-               OSBitAndAtomic(~((uint32_t)P_NOREMOTEHANG), (UInt32 *)&p->p_flag);
+               OSBitAndAtomic(~((uint32_t)P_NOREMOTEHANG), &p->p_flag);
        else
        else
-               OSBitOrAtomic(P_NOREMOTEHANG, (UInt32 *)&p->p_flag);
+               OSBitOrAtomic(P_NOREMOTEHANG, &p->p_flag);
        proc_rele(p);
 
        return (0);
 }
 
 /* the vfs.generic. branch. */
        proc_rele(p);
 
        return (0);
 }
 
 /* the vfs.generic. branch. */
-SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RW|CTLFLAG_LOCKED, NULL, "vfs generic hinge");
+SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RW | CTLFLAG_LOCKED, NULL, "vfs generic hinge");
 /* retreive a list of mounted filesystem fsid_t */
 /* retreive a list of mounted filesystem fsid_t */
-SYSCTL_PROC(_vfs_generic, OID_AUTO, vfsidlist, CTLFLAG_RD,
+SYSCTL_PROC(_vfs_generic, OID_AUTO, vfsidlist, CTLFLAG_RD | CTLFLAG_LOCKED,
     NULL, 0, sysctl_vfs_vfslist, "S,fsid", "List of mounted filesystem ids");
 /* perform operations on filesystem via fsid_t */
     NULL, 0, sysctl_vfs_vfslist, "S,fsid", "List of mounted filesystem ids");
 /* perform operations on filesystem via fsid_t */
-SYSCTL_NODE(_vfs_generic, OID_AUTO, ctlbyfsid, CTLFLAG_RW|CTLFLAG_LOCKED,
+SYSCTL_NODE(_vfs_generic, OID_AUTO, ctlbyfsid, CTLFLAG_RW | CTLFLAG_LOCKED,
     sysctl_vfs_ctlbyfsid, "ctlbyfsid");
     sysctl_vfs_ctlbyfsid, "ctlbyfsid");
-SYSCTL_PROC(_vfs_generic, OID_AUTO, noremotehang, CTLFLAG_RW|CTLFLAG_ANYBODY,
+SYSCTL_PROC(_vfs_generic, OID_AUTO, noremotehang, CTLFLAG_RW | CTLFLAG_ANYBODY,
     NULL, 0, sysctl_vfs_noremotehang, "I", "noremotehang");
        
        
     NULL, 0, sysctl_vfs_noremotehang, "I", "noremotehang");
        
        
-long num_reusedvnodes = 0;     /* long for OSAddAtomic */
+long num_reusedvnodes = 0;
 
 static int
 new_vnode(vnode_t *vpp)
 
 static int
 new_vnode(vnode_t *vpp)
@@ -3217,12 +3486,13 @@ new_vnode(vnode_t *vpp)
        vnode_t vp;
        int retries = 0;                                /* retry incase of tablefull */
        int force_alloc = 0, walk_count = 0;
        vnode_t vp;
        int retries = 0;                                /* retry incase of tablefull */
        int force_alloc = 0, walk_count = 0;
-       int vpid;
+       unsigned int  vpid;
        struct timespec ts;
         struct timeval current_tv;
        struct timespec ts;
         struct timeval current_tv;
+#ifndef __LP64__
         struct unsafe_fsnode *l_unsafefs = 0;
         struct unsafe_fsnode *l_unsafefs = 0;
+#endif /* __LP64__ */
        proc_t  curproc = current_proc();
        proc_t  curproc = current_proc();
-       pid_t current_pid = proc_pid(curproc);
 
 retry:
        microuptime(&current_tv);
 
 retry:
        microuptime(&current_tv);
@@ -3231,33 +3501,37 @@ retry:
 
        vnode_list_lock();
 
 
        vnode_list_lock();
 
-       if ( !TAILQ_EMPTY(&vnode_dead_list)) {
-               /*
-                * Can always reuse a dead one
+       if ((numvnodes - deadvnodes) < desiredvnodes || force_alloc) {
+               if ( !TAILQ_EMPTY(&vnode_dead_list)) {
+                       /*
+                        * Can always reuse a dead one
+                        */
+                       vp = TAILQ_FIRST(&vnode_dead_list);
+                       goto steal_this_vp;
+               }
+               /*
+                * no dead vnodes available... if we're under
+                * the limit, we'll create a new vnode
                 */
                 */
-               vp = TAILQ_FIRST(&vnode_dead_list);
-               goto steal_this_vp;
-       }
-       /*
-        * no dead vnodes available... if we're under
-        * the limit, we'll create a new vnode
-        */
-       if (numvnodes < desiredvnodes || force_alloc) {
                numvnodes++;
                vnode_list_unlock();
                numvnodes++;
                vnode_list_unlock();
+
                MALLOC_ZONE(vp, struct vnode *, sizeof(*vp), M_VNODE, M_WAITOK);
                bzero((char *)vp, sizeof(*vp));
                VLISTNONE(vp);          /* avoid double queue removal */
                lck_mtx_init(&vp->v_lock, vnode_lck_grp, vnode_lck_attr);
 
                MALLOC_ZONE(vp, struct vnode *, sizeof(*vp), M_VNODE, M_WAITOK);
                bzero((char *)vp, sizeof(*vp));
                VLISTNONE(vp);          /* avoid double queue removal */
                lck_mtx_init(&vp->v_lock, vnode_lck_grp, vnode_lck_attr);
 
+               klist_init(&vp->v_knotes);
                nanouptime(&ts);
                vp->v_id = ts.tv_nsec;
                vp->v_flag = VSTANDARD;
 
 #if CONFIG_MACF
                nanouptime(&ts);
                vp->v_id = ts.tv_nsec;
                vp->v_flag = VSTANDARD;
 
 #if CONFIG_MACF
-               mac_vnode_label_init(vp);
+               if (mac_vnode_label_init_needed(vp))
+                       mac_vnode_label_init(vp);
 #endif /* MAC */
 
 #endif /* MAC */
 
+               vp->v_iocount = 1;
                goto done;
        }
 
                goto done;
        }
 
@@ -3268,21 +3542,26 @@ retry:
              (current_tv.tv_sec - rage_tv.tv_sec) >= RAGE_TIME_LIMIT)) {
 
                TAILQ_FOREACH(vp, &vnode_rage_list, v_freelist) {
              (current_tv.tv_sec - rage_tv.tv_sec) >= RAGE_TIME_LIMIT)) {
 
                TAILQ_FOREACH(vp, &vnode_rage_list, v_freelist) {
-                   if ( !(vp->v_listflag & VLIST_RAGE) || !(vp->v_flag & VRAGE))
-                       panic("new_vnode: vp on RAGE list not marked both VLIST_RAGE and VRAGE");
-
-                   // skip vnodes which have a dependency on this process
-                   // (i.e. they're vnodes in a disk image and this process
-                   // is diskimages-helper)
-                   //
-                   if (vp->v_mount && vp->v_mount->mnt_dependent_pid != current_pid && vp->v_mount->mnt_dependent_process != curproc) {
-                       break;
+                   if ( !(vp->v_listflag & VLIST_RAGE))
+                       panic("new_vnode: vp (%p) on RAGE list not marked VLIST_RAGE", vp);
+
+                   // if we're a dependency-capable process, skip vnodes that can
+                       // cause recycling deadlocks. (i.e. this process is diskimages
+                       // helper and the vnode is in a disk image).  Querying the
+                       // mnt_kern_flag for the mount's virtual device status
+                       // is safer than checking the mnt_dependent_process, which
+                       // may not be updated if there are multiple devnode layers 
+                       // in between the disk image and the final consumer.
+
+                   if ((curproc->p_flag & P_DEPENDENCY_CAPABLE) == 0 || vp->v_mount == NULL || 
+                                       (vp->v_mount->mnt_kern_flag & MNTK_VIRTUALDEV) == 0) {
+                               break;
                    }
 
                    // don't iterate more than MAX_WALK_COUNT vnodes to
                    // avoid keeping the vnode list lock held for too long.
                    if (walk_count++ > MAX_WALK_COUNT) {
                    }
 
                    // don't iterate more than MAX_WALK_COUNT vnodes to
                    // avoid keeping the vnode list lock held for too long.
                    if (walk_count++ > MAX_WALK_COUNT) {
-                       vp = NULL;
+                               vp = NULL;
                        break;
                    }
                }
                        break;
                    }
                }
@@ -3295,12 +3574,18 @@ retry:
                 */
                walk_count = 0;
                TAILQ_FOREACH(vp, &vnode_free_list, v_freelist) {
                 */
                walk_count = 0;
                TAILQ_FOREACH(vp, &vnode_free_list, v_freelist) {
-                   // skip vnodes which have a dependency on this process
-                   // (i.e. they're vnodes in a disk image and this process
-                   // is diskimages-helper)
-                   //
-                   if (vp->v_mount && vp->v_mount->mnt_dependent_pid != current_pid && vp->v_mount->mnt_dependent_process != curproc) {
-                       break;
+
+                       // if we're a dependency-capable process, skip vnodes that can
+                       // cause recycling deadlocks. (i.e. this process is diskimages
+                       // helper and the vnode is in a disk image).  Querying the
+                       // mnt_kern_flag for the mount's virtual device status
+                       // is safer than checking the mnt_dependent_process, which
+                       // may not be updated if there are multiple devnode layers 
+                       // in between the disk image and the final consumer.
+
+                   if ((curproc->p_flag & P_DEPENDENCY_CAPABLE) == 0 || vp->v_mount == NULL || 
+                                       (vp->v_mount->mnt_kern_flag & MNTK_VIRTUALDEV) == 0) {
+                               break;
                    }
 
                    // don't iterate more than MAX_WALK_COUNT vnodes to
                    }
 
                    // don't iterate more than MAX_WALK_COUNT vnodes to
@@ -3329,7 +3614,7 @@ retry:
        }
 
        if (vp == NULL) {
        }
 
        if (vp == NULL) {
-               /*
+               /*
                 * we've reached the system imposed maximum number of vnodes
                 * but there isn't a single one available
                 * wait a bit and then retry... if we can't get a vnode
                 * we've reached the system imposed maximum number of vnodes
                 * but there isn't a single one available
                 * wait a bit and then retry... if we can't get a vnode
@@ -3346,25 +3631,34 @@ retry:
                log(LOG_EMERG, "%d desired, %d numvnodes, "
                        "%d free, %d dead, %d rage\n",
                        desiredvnodes, numvnodes, freevnodes, deadvnodes, ragevnodes);
                log(LOG_EMERG, "%d desired, %d numvnodes, "
                        "%d free, %d dead, %d rage\n",
                        desiredvnodes, numvnodes, freevnodes, deadvnodes, ragevnodes);
+#if CONFIG_EMBEDDED
+               /*
+                * Running out of vnodes tends to make a system unusable. Start killing
+                * processes that jetsam knows are killable.
+                */
+               if (jetsam_kill_top_proc(TRUE, kJetsamFlagsKilledVnodes) < 0) {
+                       /*
+                        * If jetsam can't find any more processes to kill and there
+                        * still aren't any free vnodes, panic. Hopefully we'll get a
+                        * panic log to tell us why we ran out.
+                        */
+                       panic("vnode table is full\n");
+               }
+
+               delay_for_interval(1, 1000 * 1000);
+               goto retry;
+#endif
+
                *vpp = NULL;
                return (ENFILE);
        }
 steal_this_vp:
        vpid = vp->v_id;
 
                *vpp = NULL;
                return (ENFILE);
        }
 steal_this_vp:
        vpid = vp->v_id;
 
-       /*
-        * the v_listflag field is
-        * protected by the vnode_list_lock
-        */
-       if (vp->v_listflag & VLIST_DEAD)
-               VREMDEAD("new_vnode", vp);
-       else if (vp->v_listflag & VLIST_RAGE)
-               VREMRAGE("new_vnode", vp);
-       else
-               VREMFREE("new_vnode", vp);
-       VLISTNONE(vp);
+       vnode_list_remove_locked(vp);
 
        vnode_list_unlock();
 
        vnode_list_unlock();
+
        vnode_lock_spin(vp);
 
        /* 
        vnode_lock_spin(vp);
 
        /* 
@@ -3407,30 +3701,32 @@ steal_this_vp:
                vnode_unlock(vp);
                goto retry;
        }
                vnode_unlock(vp);
                goto retry;
        }
-       OSAddAtomic(1, &num_reusedvnodes);
+       OSAddAtomicLong(1, &num_reusedvnodes);
 
        /* Checks for anyone racing us for recycle */ 
        if (vp->v_type != VBAD) {
                if (vp->v_lflag & VL_DEAD)
 
        /* Checks for anyone racing us for recycle */ 
        if (vp->v_type != VBAD) {
                if (vp->v_lflag & VL_DEAD)
-                       panic("new_vnode: the vnode is VL_DEAD but not VBAD");
+                       panic("new_vnode(%p): the vnode is VL_DEAD but not VBAD", vp);
                vnode_lock_convert(vp);
                vnode_lock_convert(vp);
-
                (void)vnode_reclaim_internal(vp, 1, 1, 0);
 
                if ((VONLIST(vp)))
                (void)vnode_reclaim_internal(vp, 1, 1, 0);
 
                if ((VONLIST(vp)))
-                       panic("new_vnode: vp on list ");
+                       panic("new_vnode(%p): vp on list", vp);
                if (vp->v_usecount || vp->v_iocount || vp->v_kusecount ||
                    (vp->v_lflag & (VNAMED_UBC | VNAMED_MOUNT | VNAMED_FSHASH)))
                if (vp->v_usecount || vp->v_iocount || vp->v_kusecount ||
                    (vp->v_lflag & (VNAMED_UBC | VNAMED_MOUNT | VNAMED_FSHASH)))
-                       panic("new_vnode: free vnode still referenced\n");
+                       panic("new_vnode(%p): free vnode still referenced", vp);
                if ((vp->v_mntvnodes.tqe_prev != 0) && (vp->v_mntvnodes.tqe_next != 0))
                if ((vp->v_mntvnodes.tqe_prev != 0) && (vp->v_mntvnodes.tqe_next != 0))
-                       panic("new_vnode: vnode seems to be on mount list ");
+                       panic("new_vnode(%p): vnode seems to be on mount list", vp);
                if ( !LIST_EMPTY(&vp->v_nclinks) || !LIST_EMPTY(&vp->v_ncchildren))
                if ( !LIST_EMPTY(&vp->v_nclinks) || !LIST_EMPTY(&vp->v_ncchildren))
-                       panic("new_vnode: vnode still hooked into the name cache");
+                       panic("new_vnode(%p): vnode still hooked into the name cache", vp);
        }
        }
+
+#ifndef __LP64__
        if (vp->v_unsafefs) {
                l_unsafefs = vp->v_unsafefs;
                vp->v_unsafefs = (struct unsafe_fsnode *)NULL;
        }
        if (vp->v_unsafefs) {
                l_unsafefs = vp->v_unsafefs;
                vp->v_unsafefs = (struct unsafe_fsnode *)NULL;
        }
+#endif /* __LP64__ */
 
 #if CONFIG_MACF
        /*
 
 #if CONFIG_MACF
        /*
@@ -3442,9 +3738,14 @@ steal_this_vp:
        if (vp->v_lflag & VL_LABELED) {
                vnode_lock_convert(vp);
                mac_vnode_label_recycle(vp);
        if (vp->v_lflag & VL_LABELED) {
                vnode_lock_convert(vp);
                mac_vnode_label_recycle(vp);
+       } else if (mac_vnode_label_init_needed(vp)) {
+               vnode_lock_convert(vp);
+               mac_vnode_label_init(vp);
        }
        }
+
 #endif /* MAC */
 
 #endif /* MAC */
 
+       vp->v_iocount = 1;
        vp->v_lflag = 0;
        vp->v_writecount = 0;
         vp->v_references = 0;
        vp->v_lflag = 0;
        vp->v_writecount = 0;
         vp->v_references = 0;
@@ -3456,10 +3757,13 @@ steal_this_vp:
 
        vnode_unlock(vp);
 
 
        vnode_unlock(vp);
 
+#ifndef __LP64__
        if (l_unsafefs) {
                lck_mtx_destroy(&l_unsafefs->fsnodelock, vnode_lck_grp);
                FREE_ZONE((void *)l_unsafefs, sizeof(struct unsafe_fsnode), M_UNSAFEFS);
        }
        if (l_unsafefs) {
                lck_mtx_destroy(&l_unsafefs->fsnodelock, vnode_lck_grp);
                FREE_ZONE((void *)l_unsafefs, sizeof(struct unsafe_fsnode), M_UNSAFEFS);
        }
+#endif /* __LP64__ */
+
 done:
        *vpp = vp;
 
 done:
        *vpp = vp;
 
@@ -3501,7 +3805,9 @@ vnode_get(struct vnode *vp)
 int
 vnode_get_locked(struct vnode *vp)
 {
 int
 vnode_get_locked(struct vnode *vp)
 {
-
+#if DIAGNOSTIC
+       lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
+#endif
        if ((vp->v_iocount == 0) && (vp->v_lflag & (VL_TERMINATE | VL_DEAD))) {
                return(ENOENT); 
        }
        if ((vp->v_iocount == 0) && (vp->v_lflag & (VL_TERMINATE | VL_DEAD))) {
                return(ENOENT); 
        }
@@ -3512,10 +3818,27 @@ vnode_get_locked(struct vnode *vp)
        return (0);
 }
 
        return (0);
 }
 
+/*
+ * vnode_getwithvid() cuts in line in front of a vnode drain (that is,
+ * while the vnode is draining, but at no point after that) to prevent
+ * deadlocks when getting vnodes from filesystem hashes while holding
+ * resources that may prevent other iocounts from being released.
+ */
+int
+vnode_getwithvid(vnode_t vp, uint32_t vid)
+{
+        return(vget_internal(vp, vid, ( VNODE_NODEAD | VNODE_WITHID | VNODE_DRAINO )));
+}
+
+/*
+ * vnode_getwithvid_drainok() is like vnode_getwithvid(), but *does* block behind a vnode
+ * drain; it exists for use in the VFS name cache, where we really do want to block behind
+ * vnode drain to prevent holding off an unmount.
+ */
 int
 int
-vnode_getwithvid(vnode_t vp, int vid)
+vnode_getwithvid_drainok(vnode_t vp, uint32_t vid)
 {
 {
-        return(vget_internal(vp, vid, ( VNODE_NODEAD| VNODE_WITHID)));
+        return(vget_internal(vp, vid, ( VNODE_NODEAD | VNODE_WITHID )));
 }
 
 int
 }
 
 int
@@ -3525,6 +3848,12 @@ vnode_getwithref(vnode_t vp)
 }
 
 
 }
 
 
+__private_extern__ int
+vnode_getalways(vnode_t vp)
+{
+        return(vget_internal(vp, 0, VNODE_ALWAYS));
+}
+
 int
 vnode_put(vnode_t vp)
 {
 int
 vnode_put(vnode_t vp)
 {
@@ -3542,6 +3871,9 @@ vnode_put_locked(vnode_t vp)
 {
        vfs_context_t ctx = vfs_context_current();      /* hoist outside loop */
 
 {
        vfs_context_t ctx = vfs_context_current();      /* hoist outside loop */
 
+#if DIAGNOSTIC
+       lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
+#endif
 retry:
        if (vp->v_iocount < 1) 
                panic("vnode_put(%p): iocount < 1", vp);
 retry:
        if (vp->v_iocount < 1) 
                panic("vnode_put(%p): iocount < 1", vp);
@@ -3550,7 +3882,7 @@ retry:
                vnode_dropiocount(vp);
                return(0);
        }
                vnode_dropiocount(vp);
                return(0);
        }
-       if ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD | VL_NEEDINACTIVE)) == VL_NEEDINACTIVE) {
+       if ((vp->v_lflag & (VL_DEAD | VL_NEEDINACTIVE)) == VL_NEEDINACTIVE) {
 
                vp->v_lflag &= ~VL_NEEDINACTIVE;
                vnode_unlock(vp);
 
                vp->v_lflag &= ~VL_NEEDINACTIVE;
                vnode_unlock(vp);
@@ -3573,7 +3905,7 @@ retry:
 
        if ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD)) == VL_MARKTERM) {
                vnode_lock_convert(vp);
 
        if ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD)) == VL_MARKTERM) {
                vnode_lock_convert(vp);
-               vnode_reclaim_internal(vp, 1, 0, 0);
+               vnode_reclaim_internal(vp, 1, 1, 0);
        }
        vnode_dropiocount(vp);
        vnode_list_add(vp);
        }
        vnode_dropiocount(vp);
        vnode_list_add(vp);
@@ -3615,17 +3947,15 @@ out:
 errno_t 
 vnode_resume(vnode_t vp)
 {
 errno_t 
 vnode_resume(vnode_t vp)
 {
+       if ((vp->v_lflag & VL_SUSPENDED) && vp->v_owner == current_thread()) {
 
 
-       vnode_lock_spin(vp);
-
-       if (vp->v_owner == current_thread()) {
+               vnode_lock_spin(vp);
                vp->v_lflag &= ~VL_SUSPENDED;
                vp->v_owner = NULL;
                vnode_unlock(vp);
                vp->v_lflag &= ~VL_SUSPENDED;
                vp->v_owner = NULL;
                vnode_unlock(vp);
-               wakeup(&vp->v_iocount);
-       } else
-               vnode_unlock(vp);
 
 
+               wakeup(&vp->v_iocount);
+       }
        return(0);
 }
 
        return(0);
 }
 
@@ -3665,7 +3995,7 @@ vnode_drain(vnode_t vp)
 {
        
        if (vp->v_lflag & VL_DRAIN) {
 {
        
        if (vp->v_lflag & VL_DRAIN) {
-               panic("vnode_drain: recursuve drain");
+               panic("vnode_drain: recursive drain");
                return(ENOENT);
        }
        vp->v_lflag |= VL_DRAIN;
                return(ENOENT);
        }
        vp->v_lflag |= VL_DRAIN;
@@ -3673,13 +4003,16 @@ vnode_drain(vnode_t vp)
 
        while (vp->v_iocount > 1)
                msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_drain", NULL);
 
        while (vp->v_iocount > 1)
                msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_drain", NULL);
+
+       vp->v_lflag &= ~VL_DRAIN;
+
        return(0);
 }
 
 
 /*
  * if the number of recent references via vnode_getwithvid or vnode_getwithref
        return(0);
 }
 
 
 /*
  * if the number of recent references via vnode_getwithvid or vnode_getwithref
- * exceeds this threshhold, than 'UN-AGE' the vnode by removing it from
+ * exceeds this threshold, than 'UN-AGE' the vnode by removing it from
  * the LRU list if it's currently on it... once the iocount and usecount both drop
  * to 0, it will get put back on the end of the list, effectively making it younger
  * this allows us to keep actively referenced vnodes in the list without having
  * the LRU list if it's currently on it... once the iocount and usecount both drop
  * to 0, it will get put back on the end of the list, effectively making it younger
  * this allows us to keep actively referenced vnodes in the list without having
@@ -3688,11 +4021,13 @@ vnode_drain(vnode_t vp)
  */
 #define UNAGE_THRESHHOLD       25
 
  */
 #define UNAGE_THRESHHOLD       25
 
-static errno_t
-vnode_getiocount(vnode_t vp, int vid, int vflags)
+errno_t
+vnode_getiocount(vnode_t vp, unsigned int vid, int vflags)
 {
        int nodead = vflags & VNODE_NODEAD;
        int nosusp = vflags & VNODE_NOSUSPEND;
 {
        int nodead = vflags & VNODE_NODEAD;
        int nosusp = vflags & VNODE_NOSUSPEND;
+       int always = vflags & VNODE_ALWAYS;
+       int beatdrain = vflags & VNODE_DRAINO;
 
        for (;;) {
                /*
 
        for (;;) {
                /*
@@ -3721,6 +4056,21 @@ vnode_getiocount(vnode_t vp, int vid, int vflags)
                    (vp->v_owner == current_thread())) {
                        break;
                }
                    (vp->v_owner == current_thread())) {
                        break;
                }
+               
+               if (always != 0) 
+                       break;
+
+               /*
+                * In some situations, we want to get an iocount
+                * even if the vnode is draining to prevent deadlock,
+                * e.g. if we're in the filesystem, potentially holding
+                * resources that could prevent other iocounts from
+                * being released.
+                */
+               if (beatdrain && (vp->v_lflag & VL_DRAIN)) {
+                       break;
+               }
+
                vnode_lock_convert(vp);
 
                if (vp->v_lflag & VL_TERMINATE) {
                vnode_lock_convert(vp);
 
                if (vp->v_lflag & VL_TERMINATE) {
@@ -3730,7 +4080,7 @@ vnode_getiocount(vnode_t vp, int vid, int vflags)
                } else
                        msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_getiocount", NULL);
        }
                } else
                        msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_getiocount", NULL);
        }
-       if (vid != vp->v_id) {
+       if (((vflags & VNODE_WITHID) != 0) && vid != vp->v_id) {
                return(ENOENT);
        }
        if (++vp->v_references >= UNAGE_THRESHHOLD) {
                return(ENOENT);
        }
        if (++vp->v_references >= UNAGE_THRESHHOLD) {
@@ -3754,10 +4104,8 @@ vnode_dropiocount (vnode_t vp)
 #ifdef JOE_DEBUG
        record_vp(vp, -1);
 #endif
 #ifdef JOE_DEBUG
        record_vp(vp, -1);
 #endif
-       if ((vp->v_lflag & (VL_DRAIN | VL_SUSPENDED)) && (vp->v_iocount <= 1)) {
-               vnode_lock_convert(vp);
+       if ((vp->v_lflag & (VL_DRAIN | VL_SUSPENDED)) && (vp->v_iocount <= 1))
                wakeup(&vp->v_iocount);
                wakeup(&vp->v_iocount);
-       }
 }
 
 
 }
 
 
@@ -3783,22 +4131,36 @@ vnode_reclaim_internal(struct vnode * vp, int locked, int reuse, int flags)
 
        vn_clearunionwait(vp, 1);
 
 
        vn_clearunionwait(vp, 1);
 
-       if (vnode_drain(vp)) {
-               panic("vnode drain failed");
-               vnode_unlock(vp);
-               return;
-       }
+       vnode_drain(vp);
+
        isfifo = (vp->v_type == VFIFO);
 
        if (vp->v_type != VBAD)
                vgone(vp, flags);               /* clean and reclaim the vnode */
 
        /*
        isfifo = (vp->v_type == VFIFO);
 
        if (vp->v_type != VBAD)
                vgone(vp, flags);               /* clean and reclaim the vnode */
 
        /*
-        * give the vnode a new identity so
-        * that vnode_getwithvid will fail
-        * on any stale cache accesses
+        * give the vnode a new identity so that vnode_getwithvid will fail
+        * on any stale cache accesses...
+        * grab the list_lock so that if we're in "new_vnode"
+        * behind the list_lock trying to steal this vnode, the v_id is stable...
+        * once new_vnode drops the list_lock, it will block trying to take
+        * the vnode lock until we release it... at that point it will evaluate
+        * whether the v_vid has changed
+        * also need to make sure that the vnode isn't on a list where "new_vnode"
+        * can find it after the v_id has been bumped until we are completely done
+        * with the vnode (i.e. putting it back on a list has to be the very last
+        * thing we do to this vnode... many of the callers of vnode_reclaim_internal
+        * are holding an io_count on the vnode... they need to drop the io_count
+        * BEFORE doing a vnode_list_add or make sure to hold the vnode lock until
+        * they are completely done with the vnode
         */
         */
+       vnode_list_lock();
+
+       vnode_list_remove_locked(vp);
        vp->v_id++;
        vp->v_id++;
+
+       vnode_list_unlock();
+
        if (isfifo) {
                struct fifoinfo * fip;
 
        if (isfifo) {
                struct fifoinfo * fip;
 
@@ -3806,13 +4168,12 @@ vnode_reclaim_internal(struct vnode * vp, int locked, int reuse, int flags)
                vp->v_fifoinfo = NULL;
                FREE(fip, M_TEMP);
        }
                vp->v_fifoinfo = NULL;
                FREE(fip, M_TEMP);
        }
-
        vp->v_type = VBAD;
 
        if (vp->v_data)
                panic("vnode_reclaim_internal: cleaned vnode isn't");
        if (vp->v_numoutput)
        vp->v_type = VBAD;
 
        if (vp->v_data)
                panic("vnode_reclaim_internal: cleaned vnode isn't");
        if (vp->v_numoutput)
-               panic("vnode_reclaim_internal: Clean vnode has pending I/O's");
+               panic("vnode_reclaim_internal: clean vnode has pending I/O's");
        if (UBCINFOEXISTS(vp))
                panic("vnode_reclaim_internal: ubcinfo not cleaned");
        if (vp->v_parent)
        if (UBCINFOEXISTS(vp))
                panic("vnode_reclaim_internal: ubcinfo not cleaned");
        if (vp->v_parent)
@@ -3823,19 +4184,22 @@ vnode_reclaim_internal(struct vnode * vp, int locked, int reuse, int flags)
        vp->v_socket = NULL;
 
        vp->v_lflag &= ~VL_TERMINATE;
        vp->v_socket = NULL;
 
        vp->v_lflag &= ~VL_TERMINATE;
-       vp->v_lflag &= ~VL_DRAIN;
        vp->v_owner = NULL;
 
        vp->v_owner = NULL;
 
+       KNOTE(&vp->v_knotes, NOTE_REVOKE);
+
+       /* Make sure that when we reuse the vnode, no knotes left over */
+       klist_init(&vp->v_knotes);
+
        if (vp->v_lflag & VL_TERMWANT) {
                vp->v_lflag &= ~VL_TERMWANT;
                wakeup(&vp->v_lflag);
        }
        if (vp->v_lflag & VL_TERMWANT) {
                vp->v_lflag &= ~VL_TERMWANT;
                wakeup(&vp->v_lflag);
        }
-       if (!reuse && vp->v_usecount == 0) {
+       if (!reuse) {
                /*
                 * make sure we get on the
                /*
                 * make sure we get on the
-                * dead list
+                * dead list if appropriate
                 */
                 */
-               vnode_list_remove(vp);
                vnode_list_add(vp);
        }
        if (!locked)
                vnode_list_add(vp);
        }
        if (!locked)
@@ -3846,10 +4210,9 @@ vnode_reclaim_internal(struct vnode * vp, int locked, int reuse, int flags)
  * The following api creates a vnode and associates all the parameter specified in vnode_fsparam
  * structure and returns a vnode handle with a reference. device aliasing is handled here so checkalias
  * is obsoleted by this.
  * The following api creates a vnode and associates all the parameter specified in vnode_fsparam
  * structure and returns a vnode handle with a reference. device aliasing is handled here so checkalias
  * is obsoleted by this.
- *  vnode_create(int flavor, size_t size, void * param,  vnode_t  *vp)
  */
 int  
  */
 int  
-vnode_create(int flavor, size_t size, void *data, vnode_t *vpp)
+vnode_create(uint32_t flavor, uint32_t size, void *data, vnode_t *vpp)
 {
        int error;
        int insert = 1;
 {
        int error;
        int insert = 1;
@@ -3859,155 +4222,210 @@ vnode_create(int flavor, size_t size, void *data, vnode_t *vpp)
         struct  uthread *ut;
        struct componentname *cnp;
        struct vnode_fsparam *param = (struct vnode_fsparam *)data;
         struct  uthread *ut;
        struct componentname *cnp;
        struct vnode_fsparam *param = (struct vnode_fsparam *)data;
-       
-       if (flavor == VNCREATE_FLAVOR && (size == VCREATESIZE) && param) {
-               if ( (error = new_vnode(&vp)) ) {
+#if CONFIG_TRIGGERS
+       struct vnode_trigger_param *tinfo = NULL;
+#endif
+       if (param == NULL)
+               return (EINVAL);
+
+#if CONFIG_TRIGGERS
+       if ((flavor == VNCREATE_TRIGGER) && (size == VNCREATE_TRIGGER_SIZE)) {
+               tinfo = (struct vnode_trigger_param *)data;
+
+               /* Validate trigger vnode input */
+               if ((param->vnfs_vtype != VDIR) ||
+                   (tinfo->vnt_resolve_func == NULL) ||
+                   (tinfo->vnt_flags & ~VNT_VALID_MASK)) {
+                       return (EINVAL);
+               }
+               /* Fall through a normal create (params will be the same) */
+               flavor = VNCREATE_FLAVOR;
+               size = VCREATESIZE;
+       }
+#endif
+       if ((flavor != VNCREATE_FLAVOR) || (size != VCREATESIZE))
+               return (EINVAL);
+
+       if ( (error = new_vnode(&vp)) )
+               return(error);
+
+       dvp = param->vnfs_dvp;
+       cnp = param->vnfs_cnp;
+
+       vp->v_op = param->vnfs_vops;
+       vp->v_type = param->vnfs_vtype;
+       vp->v_data = param->vnfs_fsnode;
+
+       if (param->vnfs_markroot)
+               vp->v_flag |= VROOT;
+       if (param->vnfs_marksystem)
+               vp->v_flag |= VSYSTEM;
+       if (vp->v_type == VREG) {
+               error = ubc_info_init_withsize(vp, param->vnfs_filesize);
+               if (error) {
+#ifdef JOE_DEBUG
+                       record_vp(vp, 1);
+#endif
+                       vp->v_mount = NULL;
+                       vp->v_op = dead_vnodeop_p;
+                       vp->v_tag = VT_NON;
+                       vp->v_data = NULL;
+                       vp->v_type = VBAD;
+                       vp->v_lflag |= VL_DEAD;
+
+                       vnode_put(vp);
                        return(error);
                        return(error);
-               } else {
-                       dvp = param->vnfs_dvp;
-                       cnp = param->vnfs_cnp;
+               }
+       }
+#ifdef JOE_DEBUG
+       record_vp(vp, 1);
+#endif
 
 
-                       vp->v_op = param->vnfs_vops;
-                       vp->v_type = param->vnfs_vtype;
-                       vp->v_data = param->vnfs_fsnode;
-                       vp->v_iocount = 1;
-
-                       if (param->vnfs_markroot)
-                               vp->v_flag |= VROOT;
-                       if (param->vnfs_marksystem)
-                               vp->v_flag |= VSYSTEM;
-                       if (vp->v_type == VREG) {
-                               error = ubc_info_init_withsize(vp, param->vnfs_filesize);
-                               if (error) {
+#if CONFIG_TRIGGERS
+       /*
+        * For trigger vnodes, attach trigger info to vnode
+        */
+       if ((vp->v_type == VDIR) && (tinfo != NULL)) {
+               /* 
+                * Note: has a side effect of incrementing trigger count on the
+                * mount if successful, which we would need to undo on a 
+                * subsequent failure.
+                */
 #ifdef JOE_DEBUG
 #ifdef JOE_DEBUG
-                                       record_vp(vp, 1);
+               record_vp(vp, -1);
 #endif
 #endif
-                                       vp->v_mount = NULL;
-                                       vp->v_op = dead_vnodeop_p;
-                                       vp->v_tag = VT_NON;
-                                       vp->v_data = NULL;
-                                       vp->v_type = VBAD;
-                                       vp->v_lflag |= VL_DEAD;
-
-                                       vnode_put(vp);
-                                       return(error);
-                               }
-                       }
+               error = vnode_resolver_create(param->vnfs_mp, vp, tinfo, FALSE);
+               if (error) {
+                       printf("vnode_create: vnode_resolver_create() err %d\n", error);
+                       vp->v_mount = NULL;
+                       vp->v_op = dead_vnodeop_p;
+                       vp->v_tag = VT_NON;
+                       vp->v_data = NULL;
+                       vp->v_type = VBAD;
+                       vp->v_lflag |= VL_DEAD;
 #ifdef JOE_DEBUG
                        record_vp(vp, 1);
 #endif
 #ifdef JOE_DEBUG
                        record_vp(vp, 1);
 #endif
-                       if (vp->v_type == VCHR || vp->v_type == VBLK) {
-                
-                               vp->v_tag = VT_DEVFS;           /* callers will reset if needed (bdevvp) */
-
-                               if ( (nvp = checkalias(vp, param->vnfs_rdev)) ) {
-                                       /*
-                                        * if checkalias returns a vnode, it will be locked
-                                        *
-                                        * first get rid of the unneeded vnode we acquired
-                                        */
-                                       vp->v_data = NULL;
-                                       vp->v_op = spec_vnodeop_p;
-                                       vp->v_type = VBAD;
-                                       vp->v_lflag = VL_DEAD;
-                                       vp->v_data = NULL; 
-                                       vp->v_tag = VT_NON;
-                                       vnode_put(vp);
+                       vnode_put(vp);
+                       return (error);
+               }
+       }
+#endif
+       if (vp->v_type == VCHR || vp->v_type == VBLK) {
 
 
-                                       /*
-                                        * switch to aliased vnode and finish
-                                        * preparing it
-                                        */
-                                       vp = nvp;
-
-                                       vclean(vp, 0);
-                                       vp->v_op = param->vnfs_vops;
-                                       vp->v_type = param->vnfs_vtype;
-                                       vp->v_data = param->vnfs_fsnode;
-                                       vp->v_lflag = 0;
-                                       vp->v_mount = NULL;
-                                       insmntque(vp, param->vnfs_mp);
-                                       insert = 0;
-                                       vnode_unlock(vp);
-                               }
-                       }
+               vp->v_tag = VT_DEVFS;           /* callers will reset if needed (bdevvp) */
 
 
-                       if (vp->v_type == VFIFO) {
-                               struct fifoinfo *fip;
+               if ( (nvp = checkalias(vp, param->vnfs_rdev)) ) {
+                       /*
+                        * if checkalias returns a vnode, it will be locked
+                        *
+                        * first get rid of the unneeded vnode we acquired
+                        */
+                       vp->v_data = NULL;
+                       vp->v_op = spec_vnodeop_p;
+                       vp->v_type = VBAD;
+                       vp->v_lflag = VL_DEAD;
+                       vp->v_data = NULL; 
+                       vp->v_tag = VT_NON;
+                       vnode_put(vp);
 
 
-                               MALLOC(fip, struct fifoinfo *,
-                                       sizeof(*fip), M_TEMP, M_WAITOK);
-                               bzero(fip, sizeof(struct fifoinfo ));
-                               vp->v_fifoinfo = fip;
-                       }
-                       /* The file systems usually pass the address of the location where
-                        * where there store  the vnode pointer. When we add the vnode in mount
-                        * point and name cache they are discoverable. So the file system node
-                        * will have the connection to vnode setup by then
+                       /*
+                        * switch to aliased vnode and finish
+                        * preparing it
                         */
                         */
-                       *vpp = vp;
+                       vp = nvp;
 
 
-                       /* Add fs named reference. */
-                       if (param->vnfs_flags & VNFS_ADDFSREF) {
-                               vp->v_lflag |= VNAMED_FSHASH;
-                       }
-                       if (param->vnfs_mp) {
-                                       if (param->vnfs_mp->mnt_kern_flag & MNTK_LOCK_LOCAL)
-                                               vp->v_flag |= VLOCKLOCAL;
-                               if (insert) {
-                                       /*
-                                        * enter in mount vnode list
-                                        */
-                                       insmntque(vp, param->vnfs_mp);
-                               }
-#ifdef INTERIM_FSNODE_LOCK     
-                               if (param->vnfs_mp->mnt_vtable->vfc_threadsafe == 0) {
-                                       MALLOC_ZONE(vp->v_unsafefs, struct unsafe_fsnode *,
-                                                   sizeof(struct unsafe_fsnode), M_UNSAFEFS, M_WAITOK);
-                                       vp->v_unsafefs->fsnode_count = 0;
-                                       vp->v_unsafefs->fsnodeowner  = (void *)NULL;
-                                       lck_mtx_init(&vp->v_unsafefs->fsnodelock, vnode_lck_grp, vnode_lck_attr);
-                               }
-#endif /* INTERIM_FSNODE_LOCK */
-                       }
-                       if (dvp && vnode_ref(dvp) == 0) {
-                               vp->v_parent = dvp;
-                       }
-                       if (cnp) {
-                               if (dvp && ((param->vnfs_flags & (VNFS_NOCACHE | VNFS_CANTCACHE)) == 0)) {
-                                       /*
-                                        * enter into name cache
-                                        * we've got the info to enter it into the name cache now
-                                        */
-                                       cache_enter(dvp, vp, cnp);
-                               }
-                               vp->v_name = vfs_addname(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, 0);
-                               if ((cnp->cn_flags & UNIONCREATED) == UNIONCREATED)
-                                       vp->v_flag |= VISUNION;
-                       }
-                       if ((param->vnfs_flags & VNFS_CANTCACHE) == 0) {
-                               /*
-                                * this vnode is being created as cacheable in the name cache
-                                * this allows us to re-enter it in the cache
-                                */
-                               vp->v_flag |= VNCACHEABLE;
-                       }
-                       ut = get_bsdthread_info(current_thread());
-               
-                       if ((current_proc()->p_lflag & P_LRAGE_VNODES) ||
-                           (ut->uu_flag & UT_RAGE_VNODES)) {
-                               /*
-                                * process has indicated that it wants any
-                                * vnodes created on its behalf to be rapidly
-                                * aged to reduce the impact on the cached set
-                                * of vnodes
-                                */
-                               vp->v_flag |= VRAGE;
-                       }
-                       return(0);
+                       vclean(vp, 0);
+                       vp->v_op = param->vnfs_vops;
+                       vp->v_type = param->vnfs_vtype;
+                       vp->v_data = param->vnfs_fsnode;
+                       vp->v_lflag = 0;
+                       vp->v_mount = NULL;
+                       insmntque(vp, param->vnfs_mp);
+                       insert = 0;
+                       vnode_unlock(vp);
+               }
+       }
+
+       if (vp->v_type == VFIFO) {
+               struct fifoinfo *fip;
+
+               MALLOC(fip, struct fifoinfo *,
+                       sizeof(*fip), M_TEMP, M_WAITOK);
+               bzero(fip, sizeof(struct fifoinfo ));
+               vp->v_fifoinfo = fip;
+       }
+       /* The file systems must pass the address of the location where
+        * they store the vnode pointer. When we add the vnode into the mount
+        * list and name cache they become discoverable. So the file system node
+        * must have the connection to vnode setup by then
+        */
+       *vpp = vp;
+
+       /* Add fs named reference. */
+       if (param->vnfs_flags & VNFS_ADDFSREF) {
+               vp->v_lflag |= VNAMED_FSHASH;
+       }
+       if (param->vnfs_mp) {
+                       if (param->vnfs_mp->mnt_kern_flag & MNTK_LOCK_LOCAL)
+                               vp->v_flag |= VLOCKLOCAL;
+               if (insert) {
+                       if ((vp->v_freelist.tqe_prev != (struct vnode **)0xdeadb))
+                               panic("insmntque: vp on the free list\n");
+
+                       /*
+                        * enter in mount vnode list
+                        */
+                       insmntque(vp, param->vnfs_mp);
                }
                }
+#ifndef __LP64__
+               if ((param->vnfs_mp->mnt_vtable->vfc_vfsflags & VFC_VFSTHREADSAFE) == 0) {
+                       MALLOC_ZONE(vp->v_unsafefs, struct unsafe_fsnode *,
+                                   sizeof(struct unsafe_fsnode), M_UNSAFEFS, M_WAITOK);
+                       vp->v_unsafefs->fsnode_count = 0;
+                       vp->v_unsafefs->fsnodeowner  = (void *)NULL;
+                       lck_mtx_init(&vp->v_unsafefs->fsnodelock, vnode_lck_grp, vnode_lck_attr);
+               }
+#endif /* __LP64__ */
+       }
+       if (dvp && vnode_ref(dvp) == 0) {
+               vp->v_parent = dvp;
+       }
+       if (cnp) {
+               if (dvp && ((param->vnfs_flags & (VNFS_NOCACHE | VNFS_CANTCACHE)) == 0)) {
+                       /*
+                        * enter into name cache
+                        * we've got the info to enter it into the name cache now
+                        * cache_enter_create will pick up an extra reference on
+                        * the name entered into the string cache
+                        */
+                       vp->v_name = cache_enter_create(dvp, vp, cnp);
+               } else
+                       vp->v_name = vfs_addname(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, 0);
+
+               if ((cnp->cn_flags & UNIONCREATED) == UNIONCREATED)
+                       vp->v_flag |= VISUNION;
+       }
+       if ((param->vnfs_flags & VNFS_CANTCACHE) == 0) {
+               /*
+                * this vnode is being created as cacheable in the name cache
+                * this allows us to re-enter it in the cache
+                */
+               vp->v_flag |= VNCACHEABLE;
        }
        }
-       return (EINVAL);
+       ut = get_bsdthread_info(current_thread());
+
+       if ((current_proc()->p_lflag & P_LRAGE_VNODES) ||
+           (ut->uu_flag & UT_RAGE_VNODES)) {
+               /*
+                * process has indicated that it wants any
+                * vnodes created on its behalf to be rapidly
+                * aged to reduce the impact on the cached set
+                * of vnodes
+                */
+               vp->v_flag |= VRAGE;
+       }
+       return (0);
 }
 
 int
 }
 
 int
@@ -4037,13 +4455,14 @@ vnode_removefsref(vnode_t vp)
 
 
 int
 
 
 int
-vfs_iterate(__unused int flags, int (*callout)(mount_t, void *), void *arg)
+vfs_iterate(int flags, int (*callout)(mount_t, void *), void *arg)
 {
        mount_t mp;
        int ret = 0;
        fsid_t * fsid_list;
        int count, actualcount,  i;
        void * allocmem;
 {
        mount_t mp;
        int ret = 0;
        fsid_t * fsid_list;
        int count, actualcount,  i;
        void * allocmem;
+       int indx_start, indx_stop, indx_incr;
 
        count = mount_getvfscnt();
        count += 10;
 
        count = mount_getvfscnt();
        count += 10;
@@ -4053,7 +4472,21 @@ vfs_iterate(__unused int flags, int (*callout)(mount_t, void *), void *arg)
 
        actualcount = mount_fillfsids(fsid_list, count);
 
 
        actualcount = mount_fillfsids(fsid_list, count);
 
-       for (i=0; i< actualcount; i++) {
+       /*
+        * Establish the iteration direction
+        * VFS_ITERATE_TAIL_FIRST overrides default head first order (oldest first)
+        */
+       if (flags & VFS_ITERATE_TAIL_FIRST) {
+               indx_start = actualcount - 1;
+               indx_stop = -1;
+               indx_incr = -1;
+       } else /* Head first by default */ {
+               indx_start = 0;
+               indx_stop = actualcount;
+               indx_incr = 1;
+       }
+
+       for (i=indx_start; i != indx_stop; i += indx_incr) {
 
                /* obtain the mount point with iteration reference */
                mp = mount_list_lookupby_fsid(&fsid_list[i], 0, 1);
 
                /* obtain the mount point with iteration reference */
                mp = mount_list_lookupby_fsid(&fsid_list[i], 0, 1);
@@ -4186,13 +4619,22 @@ vfs_update_vfsstat(mount_t mp, vfs_context_t ctx, __unused int eventtype)
        return(0);
 }
 
        return(0);
 }
 
-void 
+int
 mount_list_add(mount_t mp)
 {
 mount_list_add(mount_t mp)
 {
+       int res;
+
        mount_list_lock();
        mount_list_lock();
-       TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);    
-       nummounts++;
+       if (system_inshutdown != 0) {
+               res = -1;
+       } else {
+               TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);    
+               nummounts++;
+               res = 0;
+       }
        mount_list_unlock();
        mount_list_unlock();
+
+       return res;
 }
 
 void
 }
 
 void
@@ -4206,7 +4648,6 @@ mount_list_remove(mount_t mp)
        mount_list_unlock();
 }
 
        mount_list_unlock();
 }
 
-#if CONFIG_VOLFS
 mount_t
 mount_lookupby_volfsid(int volfs_id, int withref)
 {
 mount_t
 mount_lookupby_volfsid(int volfs_id, int withref)
 {
@@ -4240,8 +4681,6 @@ mount_lookupby_volfsid(int volfs_id, int withref)
 out:
        return(cur_mount);
 }
 out:
        return(cur_mount);
 }
-#endif
-
 
 mount_t 
 mount_list_lookupby_fsid(fsid_t *fsid, int locked, int withref)
 
 mount_t 
 mount_list_lookupby_fsid(fsid_t *fsid, int locked, int withref)
@@ -4272,7 +4711,7 @@ vnode_lookup(const char *path, int flags, vnode_t *vpp, vfs_context_t ctx)
 {
        struct nameidata nd;
        int error;
 {
        struct nameidata nd;
        int error;
-       u_long ndflags = 0;
+       u_int32_t ndflags = 0;
 
        if (ctx == NULL) {              /* XXX technically an error */
                ctx = vfs_context_current();
 
        if (ctx == NULL) {              /* XXX technically an error */
                ctx = vfs_context_current();
@@ -4289,7 +4728,8 @@ vnode_lookup(const char *path, int flags, vnode_t *vpp, vfs_context_t ctx)
                ndflags |= DOWHITEOUT;
 
        /* XXX AUDITVNPATH1 needed ? */
                ndflags |= DOWHITEOUT;
 
        /* XXX AUDITVNPATH1 needed ? */
-       NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
+       NDINIT(&nd, LOOKUP, OP_LOOKUP, ndflags, UIO_SYSSPACE,
+              CAST_USER_ADDR_T(path), ctx);
 
        if ((error = namei(&nd)))
                return (error);
 
        if ((error = namei(&nd)))
                return (error);
@@ -4304,7 +4744,7 @@ vnode_open(const char *path, int fmode, int cmode, int flags, vnode_t *vpp, vfs_
 {
        struct nameidata nd;
        int error;
 {
        struct nameidata nd;
        int error;
-       u_long ndflags = 0;
+       u_int32_t ndflags = 0;
        int lflags = flags;
 
        if (ctx == NULL) {              /* XXX technically an error */
        int lflags = flags;
 
        if (ctx == NULL) {              /* XXX technically an error */
@@ -4325,7 +4765,8 @@ vnode_open(const char *path, int fmode, int cmode, int flags, vnode_t *vpp, vfs_
                ndflags |= DOWHITEOUT;
        
        /* XXX AUDITVNPATH1 needed ? */
                ndflags |= DOWHITEOUT;
        
        /* XXX AUDITVNPATH1 needed ? */
-       NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
+       NDINIT(&nd, LOOKUP, OP_OPEN, ndflags, UIO_SYSSPACE,
+              CAST_USER_ADDR_T(path), ctx);
 
        if ((error = vn_open(&nd, fmode, cmode)))
                *vpp = NULL;
 
        if ((error = vn_open(&nd, fmode, cmode)))
                *vpp = NULL;
@@ -4378,6 +4819,18 @@ vnode_setsize(vnode_t vp, off_t size, int ioflag, vfs_context_t ctx)
        return(vnode_setattr(vp, &va, ctx));
 }
 
        return(vnode_setattr(vp, &va, ctx));
 }
 
+static int
+vn_create_reg(vnode_t dvp, vnode_t *vpp, struct nameidata *ndp, struct vnode_attr *vap, uint32_t flags, int fmode, uint32_t *statusp, vfs_context_t ctx)
+{
+       /* Only use compound VNOP for compound operation */
+       if (vnode_compound_open_available(dvp) && ((flags & VN_CREATE_DOOPEN) != 0)) {
+               *vpp = NULLVP;
+               return VNOP_COMPOUND_OPEN(dvp, vpp, ndp, VNOP_COMPOUND_OPEN_DO_CREATE, fmode, statusp, vap, ctx);
+       } else {
+               return VNOP_CREATE(dvp, vpp, &ndp->ni_cnd, vap, ctx);
+       }
+}
+
 /*
  * Create a filesystem object of arbitrary type with arbitrary attributes in
  * the spevied directory with the specified name.
 /*
  * Create a filesystem object of arbitrary type with arbitrary attributes in
  * the spevied directory with the specified name.
@@ -4420,70 +4873,48 @@ vnode_setsize(vnode_t vp, off_t size, int ioflag, vfs_context_t ctx)
  *             in the code they originated.
  */
 errno_t
  *             in the code they originated.
  */
 errno_t
-vn_create(vnode_t dvp, vnode_t *vpp, struct componentname *cnp, struct vnode_attr *vap, int flags, vfs_context_t ctx)
+vn_create(vnode_t dvp, vnode_t *vpp, struct nameidata *ndp, struct vnode_attr *vap, uint32_t flags, int fmode, uint32_t *statusp, vfs_context_t ctx)
 {
 {
-       kauth_acl_t oacl, nacl;
-       int initial_acl;
-       errno_t error;
+       errno_t error, old_error;
        vnode_t vp = (vnode_t)0;
        vnode_t vp = (vnode_t)0;
+       boolean_t batched;
+       struct componentname *cnp;
+       uint32_t defaulted;
 
 
+       cnp = &ndp->ni_cnd;
        error = 0;
        error = 0;
-       oacl = nacl = NULL;
-       initial_acl = 0;
+       batched = namei_compound_available(dvp, ndp) ? TRUE : FALSE;
 
        KAUTH_DEBUG("%p    CREATE - '%s'", dvp, cnp->cn_nameptr);
 
 
        KAUTH_DEBUG("%p    CREATE - '%s'", dvp, cnp->cn_nameptr);
 
+       if (flags & VN_CREATE_NOINHERIT) 
+               vap->va_vaflags |= VA_NOINHERIT;
+       if (flags & VN_CREATE_NOAUTH) 
+               vap->va_vaflags |= VA_NOAUTH;
        /*
        /*
-        * Handle ACL inheritance.
+        * Handle ACL inheritance, initialize vap.
         */
         */
-       if (!(flags & VN_CREATE_NOINHERIT) && vfs_extendedsecurity(dvp->v_mount)) {
-               /* save the original filesec */
-               if (VATTR_IS_ACTIVE(vap, va_acl)) {
-                       initial_acl = 1;
-                       oacl = vap->va_acl;
-               }
-
-               vap->va_acl = NULL;
-               if ((error = kauth_acl_inherit(dvp,
-                        oacl,
-                        &nacl,
-                        vap->va_type == VDIR,
-                        ctx)) != 0) {
-                       KAUTH_DEBUG("%p    CREATE - error %d processing inheritance", dvp, error);
-                       return(error);
-               }
+       error = vn_attribute_prepare(dvp, vap, &defaulted, ctx);
+       if (error) {
+               return error;
+       }
 
 
-               /*
-                * If the generated ACL is NULL, then we can save ourselves some effort
-                * by clearing the active bit.
-                */
-               if (nacl == NULL) {
-                       VATTR_CLEAR_ACTIVE(vap, va_acl);
-               } else {
-                       VATTR_SET(vap, va_acl, nacl);
-               }
+       if (vap->va_type != VREG && (fmode != 0 || (flags & VN_CREATE_DOOPEN) || statusp)) {
+               panic("Open parameters, but not a regular file.");
        }
        }
-       
-       /*
-        * Check and default new attributes.
-        * This will set va_uid, va_gid, va_mode and va_create_time at least, if the caller
-        * hasn't supplied them.
-        */
-       if ((error = vnode_authattr_new(dvp, vap, flags & VN_CREATE_NOAUTH, ctx)) != 0) {
-               KAUTH_DEBUG("%p    CREATE - error %d handing/defaulting attributes", dvp, error);
-               goto out;
+       if ((fmode != 0) && ((flags & VN_CREATE_DOOPEN) == 0)) {
+               panic("Mode for open, but not trying to open...");
        }
 
        }
 
-               
        /*
         * Create the requested node.
         */
        switch(vap->va_type) {
        case VREG:
        /*
         * Create the requested node.
         */
        switch(vap->va_type) {
        case VREG:
-               error = VNOP_CREATE(dvp, vpp, cnp, vap, ctx);
+               error = vn_create_reg(dvp, vpp, ndp, vap, flags, fmode, statusp, ctx);
                break;
        case VDIR:
                break;
        case VDIR:
-               error = VNOP_MKDIR(dvp, vpp, cnp, vap, ctx);
+               error = vn_mkdir(dvp, vpp, ndp, vap, ctx);
                break;
        case VSOCK:
        case VFIFO:
                break;
        case VSOCK:
        case VFIFO:
@@ -4500,10 +4931,11 @@ vn_create(vnode_t dvp, vnode_t *vpp, struct componentname *cnp, struct vnode_att
        }
 
        vp = *vpp;
        }
 
        vp = *vpp;
+       old_error = error;
+
 #if CONFIG_MACF
        if (!(flags & VN_CREATE_NOLABEL)) {
 #if CONFIG_MACF
        if (!(flags & VN_CREATE_NOLABEL)) {
-               error = vnode_label(vnode_mount(vp), dvp, vp, cnp,
-                   VNODE_LABEL_CREATE|VNODE_LABEL_NEEDREF, ctx);
+               error = vnode_label(vnode_mount(vp), dvp, vp, cnp, VNODE_LABEL_CREATE, ctx);
                if (error)
                        goto error;
        }
                if (error)
                        goto error;
        }
@@ -4520,24 +4952,22 @@ vn_create(vnode_t dvp, vnode_t *vpp, struct componentname *cnp, struct vnode_att
 #if CONFIG_MACF
 error:
 #endif
 #if CONFIG_MACF
 error:
 #endif
-       if ((error != 0 ) && (vp != (vnode_t)0)) {
-               *vpp = (vnode_t) 0;
-               vnode_put(vp);
+       if ((error != 0) && (vp != (vnode_t)0)) {
+
+               /* If we've done a compound open, close */
+               if (batched && (old_error == 0) && (vap->va_type == VREG)) {
+                       VNOP_CLOSE(vp, fmode, ctx);
+               }
+
+               /* Need to provide notifications if a create succeeded */
+               if (!batched) {
+                       *vpp = (vnode_t) 0;
+                       vnode_put(vp);
+               }
        }
 
 out:
        }
 
 out:
-       /*
-        * If the caller supplied a filesec in vap, it has been replaced
-        * now by the post-inheritance copy.  We need to put the original back
-        * and free the inherited product.
-        */
-       if (initial_acl) {
-               VATTR_SET(vap, va_acl, oacl);
-       } else {
-               VATTR_CLEAR_ACTIVE(vap, va_acl);
-       }
-       if (nacl != NULL)
-               kauth_acl_free(nacl);
+       vn_attribute_cleanup(vap, defaulted);
 
        return(error);
 }
 
        return(error);
 }
@@ -4568,6 +4998,433 @@ vnode_authorize_init(void)
        vnode_scope = kauth_register_scope(KAUTH_SCOPE_VNODE, vnode_authorize_callback, NULL);
 }
 
        vnode_scope = kauth_register_scope(KAUTH_SCOPE_VNODE, vnode_authorize_callback, NULL);
 }
 
+#define VATTR_PREPARE_DEFAULTED_UID            0x1
+#define VATTR_PREPARE_DEFAULTED_GID            0x2
+#define VATTR_PREPARE_DEFAULTED_MODE           0x4
+
+int
+vn_attribute_prepare(vnode_t dvp, struct vnode_attr *vap, uint32_t *defaulted_fieldsp, vfs_context_t ctx)
+{
+       kauth_acl_t nacl = NULL, oacl = NULL;
+       int error;
+
+       /*
+        * Handle ACL inheritance.
+        */
+       if (!(vap->va_vaflags & VA_NOINHERIT) && vfs_extendedsecurity(dvp->v_mount)) {
+               /* save the original filesec */
+               if (VATTR_IS_ACTIVE(vap, va_acl)) {
+                       oacl = vap->va_acl;
+               }
+
+               vap->va_acl = NULL;
+               if ((error = kauth_acl_inherit(dvp,
+                        oacl,
+                        &nacl,
+                        vap->va_type == VDIR,
+                        ctx)) != 0) {
+                       KAUTH_DEBUG("%p    CREATE - error %d processing inheritance", dvp, error);
+                       return(error);
+               }
+
+               /*
+                * If the generated ACL is NULL, then we can save ourselves some effort
+                * by clearing the active bit.
+                */
+               if (nacl == NULL) {
+                       VATTR_CLEAR_ACTIVE(vap, va_acl);
+               } else {
+                       vap->va_base_acl = oacl;
+                       VATTR_SET(vap, va_acl, nacl);
+               }
+       }
+       
+       error = vnode_authattr_new_internal(dvp, vap, (vap->va_vaflags & VA_NOAUTH), defaulted_fieldsp, ctx);
+       if (error) {
+               vn_attribute_cleanup(vap, *defaulted_fieldsp);
+       } 
+
+       return error;
+}
+
+void
+vn_attribute_cleanup(struct vnode_attr *vap, uint32_t defaulted_fields)
+{
+       /*
+        * If the caller supplied a filesec in vap, it has been replaced
+        * now by the post-inheritance copy.  We need to put the original back
+        * and free the inherited product.
+        */
+       kauth_acl_t nacl, oacl;
+
+       if (VATTR_IS_ACTIVE(vap, va_acl)) {
+               nacl = vap->va_acl;
+               oacl = vap->va_base_acl;
+
+               if (oacl)  {
+                       VATTR_SET(vap, va_acl, oacl);
+                       vap->va_base_acl = NULL;
+               } else {
+                       VATTR_CLEAR_ACTIVE(vap, va_acl);
+               }
+
+               if (nacl != NULL) {
+                       kauth_acl_free(nacl);
+               }
+       }
+
+       if ((defaulted_fields & VATTR_PREPARE_DEFAULTED_MODE) != 0) {
+               VATTR_CLEAR_ACTIVE(vap, va_mode);
+       }
+       if ((defaulted_fields & VATTR_PREPARE_DEFAULTED_GID) != 0) {
+               VATTR_CLEAR_ACTIVE(vap, va_gid);
+       }
+       if ((defaulted_fields & VATTR_PREPARE_DEFAULTED_UID) != 0) {
+               VATTR_CLEAR_ACTIVE(vap, va_uid);
+       }
+
+       return;
+}
+
+int
+vn_authorize_unlink(vnode_t dvp, vnode_t vp, struct componentname *cnp, vfs_context_t ctx, __unused void *reserved)
+{
+       int error = 0;
+
+       /*
+        * Normally, unlinking of directories is not supported. 
+        * However, some file systems may have limited support.
+        */
+       if ((vp->v_type == VDIR) &&
+                       !(vp->v_mount->mnt_vtable->vfc_vfsflags & VFC_VFSDIRLINKS)) {
+               return (EPERM); /* POSIX */
+       }
+
+       /* authorize the delete operation */
+#if CONFIG_MACF
+       if (!error)
+               error = mac_vnode_check_unlink(ctx, dvp, vp, cnp);
+#endif /* MAC */
+       if (!error)
+               error = vnode_authorize(vp, dvp, KAUTH_VNODE_DELETE, ctx);
+
+       return error;
+}
+
+int
+vn_authorize_open_existing(vnode_t vp, struct componentname *cnp, int fmode, vfs_context_t ctx, void *reserved)
+{
+       /* Open of existing case */
+       kauth_action_t action;
+       int error = 0;
+
+       if (cnp->cn_ndp == NULL) {
+               panic("NULL ndp");
+       }
+       if (reserved != NULL) {
+               panic("reserved not NULL.");
+       }
+
+#if CONFIG_MACF
+       /* XXX may do duplicate work here, but ignore that for now (idempotent) */
+       if (vfs_flags(vnode_mount(vp)) & MNT_MULTILABEL) {
+               error = vnode_label(vnode_mount(vp), NULL, vp, NULL, 0, ctx);
+               if (error)
+                       return (error);
+       }
+#endif
+
+       if ( (fmode & O_DIRECTORY) && vp->v_type != VDIR ) {
+               return (ENOTDIR);
+       }
+
+       if (vp->v_type == VSOCK && vp->v_tag != VT_FDESC) {
+               return (EOPNOTSUPP);    /* Operation not supported on socket */
+       }
+
+       if (vp->v_type == VLNK && (fmode & O_NOFOLLOW) != 0) {
+               return (ELOOP);         /* O_NOFOLLOW was specified and the target is a symbolic link */
+       }
+
+       /* disallow write operations on directories */
+       if (vnode_isdir(vp) && (fmode & (FWRITE | O_TRUNC))) {
+               return (EISDIR);
+       }
+
+       if ((cnp->cn_ndp->ni_flag & NAMEI_TRAILINGSLASH)) {
+               if (vp->v_type != VDIR) {
+                       return (ENOTDIR);
+               }
+       }
+
+#if CONFIG_MACF
+       /* If a file being opened is a shadow file containing 
+        * namedstream data, ignore the macf checks because it 
+        * is a kernel internal file and access should always 
+        * be allowed.
+        */
+       if (!(vnode_isshadow(vp) && vnode_isnamedstream(vp))) {
+               error = mac_vnode_check_open(ctx, vp, fmode);
+               if (error) {
+                       return (error);
+               }
+       }
+#endif
+
+       /* compute action to be authorized */
+       action = 0;
+       if (fmode & FREAD) {
+               action |= KAUTH_VNODE_READ_DATA;
+       }
+       if (fmode & (FWRITE | O_TRUNC)) {
+               /*
+                * If we are writing, appending, and not truncating,
+                * indicate that we are appending so that if the
+                * UF_APPEND or SF_APPEND bits are set, we do not deny
+                * the open.
+                */
+               if ((fmode & O_APPEND) && !(fmode & O_TRUNC)) {
+                       action |= KAUTH_VNODE_APPEND_DATA;
+               } else {
+                       action |= KAUTH_VNODE_WRITE_DATA;
+               }
+       }
+       return (vnode_authorize(vp, NULL, action, ctx));
+}
+
+int
+vn_authorize_create(vnode_t dvp, struct componentname *cnp, struct vnode_attr *vap, vfs_context_t ctx, void *reserved)
+{
+       /* Creation case */
+       int error;
+
+       if (cnp->cn_ndp == NULL) {
+               panic("NULL cn_ndp");
+       }
+       if (reserved != NULL) {
+               panic("reserved not NULL.");
+       }
+
+       /* Only validate path for creation if we didn't do a complete lookup */
+       if (cnp->cn_ndp->ni_flag & NAMEI_UNFINISHED) {
+               error = lookup_validate_creation_path(cnp->cn_ndp);
+               if (error)
+                       return (error);
+       }
+
+#if CONFIG_MACF
+       error = mac_vnode_check_create(ctx, dvp, cnp, vap);
+       if (error)
+               return (error);
+#endif /* CONFIG_MACF */
+
+       return (vnode_authorize(dvp, NULL, KAUTH_VNODE_ADD_FILE, ctx));
+}
+
+int 
+vn_authorize_rename(struct vnode *fdvp,  struct vnode *fvp,  struct componentname *fcnp,
+             struct vnode *tdvp,  struct vnode *tvp,  struct componentname *tcnp,
+             vfs_context_t ctx, void *reserved)
+{
+       int error = 0;
+       int moving = 0;
+
+       if (reserved != NULL) {
+               panic("Passed something other than NULL as reserved field!");
+       }
+
+       /*
+        * Avoid renaming "." and "..".
+        *
+        * XXX No need to check for this in the FS.  We should always have the leaves
+        * in VFS in this case.
+        */
+       if (fvp->v_type == VDIR &&
+           ((fdvp == fvp) ||
+            (fcnp->cn_namelen == 1 && fcnp->cn_nameptr[0] == '.') ||
+            ((fcnp->cn_flags | tcnp->cn_flags) & ISDOTDOT)) ) {
+               error = EINVAL;
+               goto out;
+       }
+
+       if (tvp == NULLVP && vnode_compound_rename_available(tdvp)) {
+               error = lookup_validate_creation_path(tcnp->cn_ndp);
+               if (error) 
+                       goto out;
+       }
+
+       /***** <MACF> *****/
+#if CONFIG_MACF
+       error = mac_vnode_check_rename_from(ctx, fdvp, fvp, fcnp);
+       if (error)
+               goto out;
+#endif
+
+#if CONFIG_MACF
+       error = mac_vnode_check_rename_to(ctx,
+                       tdvp, tvp, fdvp == tdvp, tcnp);
+       if (error)
+               goto out;
+#endif
+       /***** </MACF> *****/
+
+       /***** <MiscChecks> *****/
+       if (tvp != NULL) {
+               if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
+                       error = ENOTDIR;
+                       goto out;
+               } else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
+                       error = EISDIR;
+                       goto out;
+               }
+       }
+
+       if (fvp == tdvp) {
+               error = EINVAL;
+               goto out;
+       }
+
+       /*
+        * The following edge case is caught here:
+        * (to cannot be a descendent of from)
+        *
+        *       o fdvp
+        *      /
+        *     /
+        *    o fvp
+        *     \
+        *      \
+        *       o tdvp
+        *      /
+        *     /
+        *    o tvp
+        */
+       if (tdvp->v_parent == fvp) {
+               error = EINVAL;
+               goto out;
+       }
+       /***** </MiscChecks> *****/
+
+       /***** <Kauth> *****/
+
+       error = 0;
+       if ((tvp != NULL) && vnode_isdir(tvp)) {
+               if (tvp != fdvp)
+                       moving = 1;
+       } else if (tdvp != fdvp) {
+               moving = 1;
+       }
+
+
+       /*
+        * must have delete rights to remove the old name even in
+        * the simple case of fdvp == tdvp.
+        *
+        * If fvp is a directory, and we are changing it's parent,
+        * then we also need rights to rewrite its ".." entry as well.
+        */
+       if (vnode_isdir(fvp)) {
+               if ((error = vnode_authorize(fvp, fdvp, KAUTH_VNODE_DELETE | KAUTH_VNODE_ADD_SUBDIRECTORY, ctx)) != 0)
+                       goto out;
+       } else {
+               if ((error = vnode_authorize(fvp, fdvp, KAUTH_VNODE_DELETE, ctx)) != 0)
+                       goto out;
+       }
+       if (moving) {
+               /* moving into tdvp or tvp, must have rights to add */
+               if ((error = vnode_authorize(((tvp != NULL) && vnode_isdir(tvp)) ? tvp : tdvp,
+                                               NULL, 
+                                               vnode_isdir(fvp) ? KAUTH_VNODE_ADD_SUBDIRECTORY : KAUTH_VNODE_ADD_FILE,
+                                               ctx)) != 0) {
+                       goto out;
+               }
+       } else {
+               /* node staying in same directory, must be allowed to add new name */
+               if ((error = vnode_authorize(fdvp, NULL,
+                                               vnode_isdir(fvp) ? KAUTH_VNODE_ADD_SUBDIRECTORY : KAUTH_VNODE_ADD_FILE, ctx)) != 0)
+                       goto out;
+       }
+       /* overwriting tvp */
+       if ((tvp != NULL) && !vnode_isdir(tvp) &&
+                       ((error = vnode_authorize(tvp, tdvp, KAUTH_VNODE_DELETE, ctx)) != 0)) {
+               goto out;
+       }
+
+       /***** </Kauth> *****/
+
+       /* XXX more checks? */
+out:
+       return error;
+}
+
+int
+vn_authorize_mkdir(vnode_t dvp, struct componentname *cnp, struct vnode_attr *vap, vfs_context_t ctx, void *reserved)
+{
+       int error;
+
+       if (reserved != NULL) {
+               panic("reserved not NULL in vn_authorize_mkdir()");     
+       }
+
+       /* XXX A hack for now, to make shadow files work */
+       if (cnp->cn_ndp == NULL) {
+               return 0;
+       }
+
+       if (vnode_compound_mkdir_available(dvp)) {
+               error = lookup_validate_creation_path(cnp->cn_ndp);
+               if (error)
+                       goto out;
+       }
+
+#if CONFIG_MACF
+       error = mac_vnode_check_create(ctx,
+           dvp, cnp, vap);
+       if (error)
+               goto out;
+#endif
+
+       /* authorize addition of a directory to the parent */
+       if ((error = vnode_authorize(dvp, NULL, KAUTH_VNODE_ADD_SUBDIRECTORY, ctx)) != 0)
+               goto out;
+       
+out:
+       return error;
+}
+
+int
+vn_authorize_rmdir(vnode_t dvp, vnode_t vp, struct componentname *cnp, vfs_context_t ctx, void *reserved)
+{
+       int error;
+
+       if (reserved != NULL) {
+               panic("Non-NULL reserved argument to vn_authorize_rmdir()");
+       }
+
+       if (vp->v_type != VDIR) {
+               /*
+                * rmdir only deals with directories
+                */
+               return ENOTDIR;
+       } 
+       
+       if (dvp == vp) {
+               /*
+                * No rmdir "." please.
+                */
+               return EINVAL;
+       } 
+       
+#if CONFIG_MACF
+       error = mac_vnode_check_unlink(ctx, dvp,
+                       vp, cnp);
+       if (error)
+               return error;
+#endif
+
+       return vnode_authorize(vp, dvp, KAUTH_VNODE_DELETE, ctx);
+}
+
 /*
  * Authorize an operation on a vnode.
  *
 /*
  * Authorize an operation on a vnode.
  *
@@ -4666,8 +5523,24 @@ vauth_node_owner(struct vnode_attr *vap, kauth_cred_t cred)
        return(result);
 }
 
        return(result);
 }
 
+/*
+ * vauth_node_group
+ *
+ * Description:        Ask if a cred is a member of the group owning the vnode object
+ *
+ * Parameters:         vap             vnode attribute
+ *                             vap->va_gid     group owner of vnode object
+ *                     cred            credential to check
+ *                     ismember        pointer to where to put the answer
+ *                     idontknow       Return this if we can't get an answer
+ *
+ * Returns:            0               Success
+ *                     idontknow       Can't get information
+ *     kauth_cred_ismember_gid:?       Error from kauth subsystem
+ *     kauth_cred_ismember_gid:?       Error from kauth subsystem
+ */
 static int
 static int
-vauth_node_group(struct vnode_attr *vap, kauth_cred_t cred, int *ismember)
+vauth_node_group(struct vnode_attr *vap, kauth_cred_t cred, int *ismember, int idontknow)
 {
        int     error;
        int     result;
 {
        int     error;
        int     result;
@@ -4675,11 +5548,43 @@ vauth_node_group(struct vnode_attr *vap, kauth_cred_t cred, int *ismember)
        error = 0;
        result = 0;
 
        error = 0;
        result = 0;
 
-       /* the caller is expected to have asked the filesystem for a group at some point */
+       /*
+        * The caller is expected to have asked the filesystem for a group
+        * at some point prior to calling this function.  The answer may
+        * have been that there is no group ownership supported for the
+        * vnode object, in which case we return
+        */
        if (vap && VATTR_IS_SUPPORTED(vap, va_gid)) {
                error = kauth_cred_ismember_gid(cred, vap->va_gid, &result);
        if (vap && VATTR_IS_SUPPORTED(vap, va_gid)) {
                error = kauth_cred_ismember_gid(cred, vap->va_gid, &result);
+               /*
+                * Credentials which are opted into external group membership
+                * resolution which are not known to the external resolver
+                * will result in an ENOENT error.  We translate this into
+                * the appropriate 'idontknow' response for our caller.
+                *
+                * XXX We do not make a distinction here between an ENOENT
+                * XXX arising from a response from the external resolver,
+                * XXX and an ENOENT which is internally generated.  This is
+                * XXX a deficiency of the published kauth_cred_ismember_gid()
+                * XXX KPI which can not be overcome without new KPI.  For
+                * XXX all currently known cases, however, this wil result
+                * XXX in correct behaviour.
+                */
+               if (error == ENOENT)
+                       error = idontknow;
        }
        }
-       /* we could test the group UUID here if we had a policy for it */
+       /*
+        * XXX We could test the group UUID here if we had a policy for it,
+        * XXX but this is problematic from the perspective of synchronizing
+        * XXX group UUID and POSIX GID ownership of a file and keeping the
+        * XXX values coherent over time.  The problem is that the local
+        * XXX system will vend transient group UUIDs for unknown POSIX GID
+        * XXX values, and these are not persistent, whereas storage of values
+        * XXX is persistent.  One potential solution to this is a local
+        * XXX (persistent) replica of remote directory entries and vended
+        * XXX local ids in a local directory server (think in terms of a
+        * XXX caching DNS server).
+        */
 
        if (!error)
                *ismember = result;
 
        if (!error)
                *ismember = result;
@@ -4707,16 +5612,39 @@ vauth_file_owner(vauth_ctx vcp)
        return(result);
 }
 
        return(result);
 }
 
+
+/*
+ * vauth_file_ingroup
+ *
+ * Description:        Ask if a user is a member of the group owning the directory
+ *
+ * Parameters:         vcp             The vnode authorization context that
+ *                                     contains the user and directory info
+ *                             vcp->flags_valid        Valid flags
+ *                             vcp->flags              Flags values
+ *                             vcp->vap                File vnode attributes
+ *                             vcp->ctx                VFS Context (for user)
+ *                     ismember        pointer to where to put the answer
+ *                     idontknow       Return this if we can't get an answer
+ *
+ * Returns:            0               Success
+ *             vauth_node_group:?      Error from vauth_node_group()
+ *
+ * Implicit returns:   *ismember       0       The user is not a group member
+ *                                     1       The user is a group member
+ */
 static int
 static int
-vauth_file_ingroup(vauth_ctx vcp, int *ismember)
+vauth_file_ingroup(vauth_ctx vcp, int *ismember, int idontknow)
 {
        int     error;
 
 {
        int     error;
 
+       /* Check for a cached answer first, to avoid the check if possible */
        if (vcp->flags_valid & _VAC_IN_GROUP) {
                *ismember = (vcp->flags & _VAC_IN_GROUP) ? 1 : 0;
                error = 0;
        } else {
        if (vcp->flags_valid & _VAC_IN_GROUP) {
                *ismember = (vcp->flags & _VAC_IN_GROUP) ? 1 : 0;
                error = 0;
        } else {
-               error = vauth_node_group(vcp->vap, vcp->ctx->vc_ucred, ismember);
+               /* Otherwise, go look for it */
+               error = vauth_node_group(vcp->vap, vcp->ctx->vc_ucred, ismember, idontknow);
 
                if (!error) {
                        /* cache our result */
 
                if (!error) {
                        /* cache our result */
@@ -4753,16 +5681,38 @@ vauth_dir_owner(vauth_ctx vcp)
        return(result);
 }
 
        return(result);
 }
 
+/*
+ * vauth_dir_ingroup
+ *
+ * Description:        Ask if a user is a member of the group owning the directory
+ *
+ * Parameters:         vcp             The vnode authorization context that
+ *                                     contains the user and directory info
+ *                             vcp->flags_valid        Valid flags
+ *                             vcp->flags              Flags values
+ *                             vcp->dvap               Dir vnode attributes
+ *                             vcp->ctx                VFS Context (for user)
+ *                     ismember        pointer to where to put the answer
+ *                     idontknow       Return this if we can't get an answer
+ *
+ * Returns:            0               Success
+ *             vauth_node_group:?      Error from vauth_node_group()
+ *
+ * Implicit returns:   *ismember       0       The user is not a group member
+ *                                     1       The user is a group member
+ */
 static int
 static int
-vauth_dir_ingroup(vauth_ctx vcp, int *ismember)
+vauth_dir_ingroup(vauth_ctx vcp, int *ismember, int idontknow)
 {
        int     error;
 
 {
        int     error;
 
+       /* Check for a cached answer first, to avoid the check if possible */
        if (vcp->flags_valid & _VAC_IN_DIR_GROUP) {
                *ismember = (vcp->flags & _VAC_IN_DIR_GROUP) ? 1 : 0;
                error = 0;
        } else {
        if (vcp->flags_valid & _VAC_IN_DIR_GROUP) {
                *ismember = (vcp->flags & _VAC_IN_DIR_GROUP) ? 1 : 0;
                error = 0;
        } else {
-               error = vauth_node_group(vcp->dvap, vcp->ctx->vc_ucred, ismember);
+               /* Otherwise, go look for it */
+               error = vauth_node_group(vcp->dvap, vcp->ctx->vc_ucred, ismember, idontknow);
 
                if (!error) {
                        /* cache our result */
 
                if (!error) {
                        /* cache our result */
@@ -4870,14 +5820,25 @@ vnode_authorize_posix(vauth_ctx vcp, int action, int on_dir)
        }
 
        /* Check group membership (most expensive) */
        }
 
        /* Check group membership (most expensive) */
-       ismember = 0;
+       ismember = 0;   /* Default to allow, if the target has no group owner */
+
+       /*
+        * In the case we can't get an answer about the user from the call to
+        * vauth_dir_ingroup() or vauth_file_ingroup(), we want to fail on
+        * the side of caution, rather than simply granting access, or we will
+        * fail to correctly implement exclusion groups, so we set the third
+        * parameter on the basis of the state of 'group_ok'.
+        */
        if (on_dir) {
        if (on_dir) {
-               error = vauth_dir_ingroup(vcp, &ismember);
+               error = vauth_dir_ingroup(vcp, &ismember, (!group_ok ? EACCES : 0));
        } else {
        } else {
-               error = vauth_file_ingroup(vcp, &ismember);
+               error = vauth_file_ingroup(vcp, &ismember, (!group_ok ? EACCES : 0));
+       }
+       if (error) {
+               if (!group_ok)
+                       ismember = 1;
+               error = 0;
        }
        }
-       if (error)
-               goto out;
        if (ismember) {
                _SETWHERE("group");
                if (!group_ok)
        if (ismember) {
                _SETWHERE("group");
                if (!group_ok)
@@ -4921,15 +5882,21 @@ out:
  * - Neither the node nor the directory are immutable.
  * - The user is not the superuser.
  *
  * - Neither the node nor the directory are immutable.
  * - The user is not the superuser.
  *
- * Deletion is not permitted if the directory is sticky and the caller is not owner of the
- * node or directory.
+ * Deletion is not permitted if the directory is sticky and the caller is
+ * not owner of the node or directory.
+ *
+ * If either the node grants DELETE, or the directory grants DELETE_CHILD,
+ * the node may be deleted.  If neither denies the permission, and the
+ * caller has Posix write access to the directory, then the node may be
+ * deleted.
  *
  *
- * If either the node grants DELETE, or the directory grants DELETE_CHILD, the node may be
- * deleted.  If neither denies the permission, and the caller has Posix write access to the
- * directory, then the node may be deleted.
+ * As an optimization, we cache whether or not delete child is permitted
+ * on directories without the sticky bit set.
  */
  */
-static int
-vnode_authorize_delete(vauth_ctx vcp)
+int
+vnode_authorize_delete(vauth_ctx vcp, boolean_t cached_delete_child);
+/*static*/ int
+vnode_authorize_delete(vauth_ctx vcp, boolean_t cached_delete_child)
 {
        struct vnode_attr       *vap = vcp->vap;
        struct vnode_attr       *dvap = vcp->dvap;
 {
        struct vnode_attr       *vap = vcp->vap;
        struct vnode_attr       *dvap = vcp->dvap;
@@ -4939,33 +5906,53 @@ vnode_authorize_delete(vauth_ctx vcp)
 
        /* check the ACL on the directory */
        delete_child_denied = 0;
 
        /* check the ACL on the directory */
        delete_child_denied = 0;
-       if (VATTR_IS_NOT(dvap, va_acl, NULL)) {
+       if (!cached_delete_child && VATTR_IS_NOT(dvap, va_acl, NULL)) {
                eval.ae_requested = KAUTH_VNODE_DELETE_CHILD;
                eval.ae_acl = &dvap->va_acl->acl_ace[0];
                eval.ae_count = dvap->va_acl->acl_entrycount;
                eval.ae_options = 0;
                if (vauth_dir_owner(vcp))
                        eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
                eval.ae_requested = KAUTH_VNODE_DELETE_CHILD;
                eval.ae_acl = &dvap->va_acl->acl_ace[0];
                eval.ae_count = dvap->va_acl->acl_entrycount;
                eval.ae_options = 0;
                if (vauth_dir_owner(vcp))
                        eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
-               if ((error = vauth_dir_ingroup(vcp, &ismember)) != 0)
+               /*
+                * We use ENOENT as a marker to indicate we could not get
+                * information in order to delay evaluation until after we
+                * have the ACL evaluation answer.  Previously, we would
+                * always deny the operation at this point.
+                */
+               if ((error = vauth_dir_ingroup(vcp, &ismember, ENOENT)) != 0 && error != ENOENT)
                        return(error);
                        return(error);
-               if (ismember)
+               if (error == ENOENT)
+                       eval.ae_options |= KAUTH_AEVAL_IN_GROUP_UNKNOWN;
+               else if (ismember)
                        eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
                eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
                eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
                eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
                eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
 
                        eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
                eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
                eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
                eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
                eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
 
+               /*
+                * If there is no entry, we are going to defer to other
+                * authorization mechanisms.
+                */
                error = kauth_acl_evaluate(cred, &eval);
 
                if (error != 0) {
                        KAUTH_DEBUG("%p    ERROR during ACL processing - %d", vcp->vp, error);
                        return(error);
                }
                error = kauth_acl_evaluate(cred, &eval);
 
                if (error != 0) {
                        KAUTH_DEBUG("%p    ERROR during ACL processing - %d", vcp->vp, error);
                        return(error);
                }
-               if (eval.ae_result == KAUTH_RESULT_DENY)
+               switch(eval.ae_result) {
+               case KAUTH_RESULT_DENY:
                        delete_child_denied = 1;
                        delete_child_denied = 1;
-               if (eval.ae_result == KAUTH_RESULT_ALLOW) {
-                       KAUTH_DEBUG("%p    ALLOWED - granted by directory ACL", vcp->vp);
-                       return(0);
+                       break;
+                       /* FALLSTHROUGH */
+                case KAUTH_RESULT_ALLOW:
+                        KAUTH_DEBUG("%p    ALLOWED - granted by directory ACL", vcp->vp);
+                        return(0);
+               case KAUTH_RESULT_DEFER:
+               default:
+                       /* Effectively the same as !delete_child_denied */
+                       KAUTH_DEBUG("%p    DEFERRED - directory ACL", vcp->vp);
+                       break;
                }
        }
 
                }
        }
 
@@ -4978,9 +5965,17 @@ vnode_authorize_delete(vauth_ctx vcp)
                eval.ae_options = 0;
                if (vauth_file_owner(vcp))
                        eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
                eval.ae_options = 0;
                if (vauth_file_owner(vcp))
                        eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
-               if ((error = vauth_file_ingroup(vcp, &ismember)) != 0)
+               /*
+                * We use ENOENT as a marker to indicate we could not get
+                * information in order to delay evaluation until after we
+                * have the ACL evaluation answer.  Previously, we would
+                * always deny the operation at this point.
+                */
+               if ((error = vauth_file_ingroup(vcp, &ismember, ENOENT)) != 0 && error != ENOENT)
                        return(error);
                        return(error);
-               if (ismember)
+               if (error == ENOENT)
+                       eval.ae_options |= KAUTH_AEVAL_IN_GROUP_UNKNOWN;
+               else if (ismember)
                        eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
                eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
                eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
                        eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
                eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
                eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
@@ -4991,30 +5986,38 @@ vnode_authorize_delete(vauth_ctx vcp)
                        KAUTH_DEBUG("%p    ERROR during ACL processing - %d", vcp->vp, error);
                        return(error);
                }
                        KAUTH_DEBUG("%p    ERROR during ACL processing - %d", vcp->vp, error);
                        return(error);
                }
-               if (eval.ae_result == KAUTH_RESULT_DENY)
+
+               switch(eval.ae_result) {
+               case KAUTH_RESULT_DENY:
                        delete_denied = 1;
                        delete_denied = 1;
-               if (eval.ae_result == KAUTH_RESULT_ALLOW) {
+                       break;
+               case KAUTH_RESULT_ALLOW:
                        KAUTH_DEBUG("%p    ALLOWED - granted by file ACL", vcp->vp);
                        return(0);
                        KAUTH_DEBUG("%p    ALLOWED - granted by file ACL", vcp->vp);
                        return(0);
+               case KAUTH_RESULT_DEFER:
+               default:
+                       /* Effectively the same as !delete_child_denied */
+                       KAUTH_DEBUG("%p    DEFERRED%s - by file ACL", vcp->vp, delete_denied ? "(DENY)" : "");
+                       break;
                }
        }
 
        /* if denied by ACL on directory or node, return denial */
        if (delete_denied || delete_child_denied) {
                }
        }
 
        /* if denied by ACL on directory or node, return denial */
        if (delete_denied || delete_child_denied) {
-               KAUTH_DEBUG("%p    ALLOWED - denied by ACL", vcp->vp);
+               KAUTH_DEBUG("%p    DENIED - denied by ACL", vcp->vp);
                return(EACCES);
        }
 
        /* enforce sticky bit behaviour */
        if ((dvap->va_mode & S_ISTXT) && !vauth_file_owner(vcp) && !vauth_dir_owner(vcp)) {
                KAUTH_DEBUG("%p    DENIED - sticky bit rules (user %d  file %d  dir %d)",
                return(EACCES);
        }
 
        /* enforce sticky bit behaviour */
        if ((dvap->va_mode & S_ISTXT) && !vauth_file_owner(vcp) && !vauth_dir_owner(vcp)) {
                KAUTH_DEBUG("%p    DENIED - sticky bit rules (user %d  file %d  dir %d)",
-                   vcp->vp, cred->cr_uid, vap->va_uid, dvap->va_uid);
+                   vcp->vp, cred->cr_posix.cr_uid, vap->va_uid, dvap->va_uid);
                return(EACCES);
        }
 
        /* check the directory */
                return(EACCES);
        }
 
        /* check the directory */
-       if ((error = vnode_authorize_posix(vcp, VWRITE, 1 /* on_dir */)) != 0) {
-               KAUTH_DEBUG("%p    ALLOWED - granted by posix permisssions", vcp->vp);
+       if (!cached_delete_child && (error = vnode_authorize_posix(vcp, VWRITE, 1 /* on_dir */)) != 0) {
+               KAUTH_DEBUG("%p    DENIED - denied by posix permisssions", vcp->vp);
                return(error);
        }
 
                return(error);
        }
 
@@ -5068,9 +6071,17 @@ vnode_authorize_simple(vauth_ctx vcp, kauth_ace_rights_t acl_rights, kauth_ace_r
                eval.ae_options = 0;
                if (vauth_file_owner(vcp))
                        eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
                eval.ae_options = 0;
                if (vauth_file_owner(vcp))
                        eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
-               if ((error = vauth_file_ingroup(vcp, &ismember)) != 0)
+               /*
+                * We use ENOENT as a marker to indicate we could not get
+                * information in order to delay evaluation until after we
+                * have the ACL evaluation answer.  Previously, we would
+                * always deny the operation at this point.
+                */
+               if ((error = vauth_file_ingroup(vcp, &ismember, ENOENT)) != 0 && error != ENOENT)
                        return(error);
                        return(error);
-               if (ismember)
+               if (error == ENOENT)
+                       eval.ae_options |= KAUTH_AEVAL_IN_GROUP_UNKNOWN;
+               else if (ismember)
                        eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
                eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
                eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
                        eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
                eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
                eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
@@ -5082,14 +6093,20 @@ vnode_authorize_simple(vauth_ctx vcp, kauth_ace_rights_t acl_rights, kauth_ace_r
                        return(error);
                }
                
                        return(error);
                }
                
-               if (eval.ae_result == KAUTH_RESULT_DENY) {
+               switch(eval.ae_result) {
+               case KAUTH_RESULT_DENY:
                        KAUTH_DEBUG("%p    DENIED - by ACL", vcp->vp);
                        KAUTH_DEBUG("%p    DENIED - by ACL", vcp->vp);
-                       return(EACCES);                 /* deny, deny, counter-allege */
-               }
-               if (eval.ae_result == KAUTH_RESULT_ALLOW) {
+                       return(EACCES);         /* deny, deny, counter-allege */
+               case KAUTH_RESULT_ALLOW:
                        KAUTH_DEBUG("%p    ALLOWED - all rights granted by ACL", vcp->vp);
                        return(0);
                        KAUTH_DEBUG("%p    ALLOWED - all rights granted by ACL", vcp->vp);
                        return(0);
+               case KAUTH_RESULT_DEFER:
+               default:
+                       /* Effectively the same as !delete_child_denied */
+                       KAUTH_DEBUG("%p    DEFERRED - directory ACL", vcp->vp);
+                       break;
                }
                }
+
                *found_deny = eval.ae_found_deny;
 
                /* fall through and evaluate residual rights */
                *found_deny = eval.ae_found_deny;
 
                /* fall through and evaluate residual rights */
@@ -5241,13 +6258,16 @@ vnode_authorize_checkimmutable(vnode_t vp, struct vnode_attr *vap, int rights, i
                        }
                }
 
                        }
                }
 
-               /* check for file immutability */
+               /* 
+                * check for file immutability. first, check if the requested rights are 
+                * allowable for a UF_APPEND file.
+                */
                append = 0;
                if (vp->v_type == VDIR) {
                append = 0;
                if (vp->v_type == VDIR) {
-                       if ((rights & (KAUTH_VNODE_ADD_FILE | KAUTH_VNODE_ADD_SUBDIRECTORY)) == rights)
+                       if ((rights & (KAUTH_VNODE_ADD_FILE | KAUTH_VNODE_ADD_SUBDIRECTORY | KAUTH_VNODE_WRITE_EXTATTRIBUTES)) == rights)
                                append = 1;
                } else {
                                append = 1;
                } else {
-                       if ((rights & KAUTH_VNODE_APPEND_DATA) == rights)
+                       if ((rights & (KAUTH_VNODE_APPEND_DATA | KAUTH_VNODE_WRITE_EXTATTRIBUTES)) == rights)
                                append = 1;
                }
                if ((error = vnode_immutable(vap, append, ignore)) != 0) {
                                append = 1;
                }
                if ((error = vnode_immutable(vap, append, ignore)) != 0) {
@@ -5360,7 +6380,9 @@ vnode_authorize_callback(kauth_cred_t cred, void *idata, kauth_action_t action,
        vfs_context_t   ctx;
        vnode_t         cvp = NULLVP;
        vnode_t         vp, dvp;
        vfs_context_t   ctx;
        vnode_t         cvp = NULLVP;
        vnode_t         vp, dvp;
-       int             result;
+       int             result = KAUTH_RESULT_DENY;
+       int             parent_iocount = 0;
+       int             parent_action; /* In case we need to use namedstream's data fork for cached rights*/
 
        ctx = (vfs_context_t)arg0;
        vp = (vnode_t)arg1;
 
        ctx = (vfs_context_t)arg0;
        vp = (vnode_t)arg1;
@@ -5380,18 +6402,66 @@ vnode_authorize_callback(kauth_cred_t cred, void *idata, kauth_action_t action,
         */
         if (dvp && vp)
                goto defer;
         */
         if (dvp && vp)
                goto defer;
-       if (dvp)
+       if (dvp) {
                cvp = dvp;
                cvp = dvp;
-       else
-               cvp = vp;
+       } else {
+               /* 
+                * For named streams on local-authorization volumes, rights are cached on the parent;
+                * authorization is determined by looking at the parent's properties anyway, so storing
+                * on the parent means that we don't recompute for the named stream and that if 
+                * we need to flush rights (e.g. on VNOP_SETATTR()) we don't need to track down the
+                * stream to flush its cache separately.  If we miss in the cache, then we authorize
+                * as if there were no cached rights (passing the named stream vnode and desired rights to 
+                * vnode_authorize_callback_int()).
+                *
+                * On an opaquely authorized volume, we don't know the relationship between the 
+                * data fork's properties and the rights granted on a stream.  Thus, named stream vnodes
+                * on such a volume are authorized directly (rather than using the parent) and have their
+                * own caches.  When a named stream vnode is created, we mark the parent as having a named
+                * stream. On a VNOP_SETATTR() for the parent that may invalidate cached authorization, we 
+                * find the stream and flush its cache.
+                */
+               if (vnode_isnamedstream(vp) && (!vfs_authopaque(vp->v_mount))) {
+                       cvp = vnode_getparent(vp);
+                       if (cvp != NULLVP) {
+                               parent_iocount = 1;
+                       } else {
+                               cvp = NULL;
+                               goto defer; /* If we can't use the parent, take the slow path */
+                       }
+
+                       /* Have to translate some actions */
+                       parent_action = action;
+                       if (parent_action & KAUTH_VNODE_READ_DATA) {
+                               parent_action &= ~KAUTH_VNODE_READ_DATA;
+                               parent_action |= KAUTH_VNODE_READ_EXTATTRIBUTES;
+                       }
+                       if (parent_action & KAUTH_VNODE_WRITE_DATA) {
+                               parent_action &= ~KAUTH_VNODE_WRITE_DATA;
+                               parent_action |= KAUTH_VNODE_WRITE_EXTATTRIBUTES;
+                       }
+
+               } else {
+                       cvp = vp;
+               }
+       }
 
 
-       if (vnode_cache_is_authorized(cvp, ctx, action) == TRUE)
-               return KAUTH_RESULT_ALLOW;
+       if (vnode_cache_is_authorized(cvp, ctx, parent_iocount ? parent_action : action) == TRUE) {
+               result = KAUTH_RESULT_ALLOW;
+               goto out;
+       }
 defer:
         result = vnode_authorize_callback_int(cred, idata, action, arg0, arg1, arg2, arg3);
 
 defer:
         result = vnode_authorize_callback_int(cred, idata, action, arg0, arg1, arg2, arg3);
 
-       if (result == KAUTH_RESULT_ALLOW && cvp != NULLVP)
+       if (result == KAUTH_RESULT_ALLOW && cvp != NULLVP) {
+               KAUTH_DEBUG("%p - caching action = %x", cvp, action);
                vnode_cache_authorized_action(cvp, ctx, action);
                vnode_cache_authorized_action(cvp, ctx, action);
+       }
+
+out:
+       if (parent_iocount) {
+               vnode_put(cvp);
+       }
 
        return result;
 }
 
        return result;
 }
@@ -5411,7 +6481,7 @@ vnode_authorize_callback_int(__unused kauth_cred_t unused_cred, __unused void *i
        int                     result;
        int                     *errorp;
        int                     noimmutable;
        int                     result;
        int                     *errorp;
        int                     noimmutable;
-       boolean_t               parent_authorized_for_delete = FALSE;
+       boolean_t               parent_authorized_for_delete_child = FALSE;
        boolean_t               found_deny = FALSE;
        boolean_t               parent_ref= FALSE;
 
        boolean_t               found_deny = FALSE;
        boolean_t               parent_ref= FALSE;
 
@@ -5476,8 +6546,8 @@ vnode_authorize_callback_int(__unused kauth_cred_t unused_cred, __unused void *i
                 * can skip a whole bunch of work... we will still have to
                 * authorize that this specific child can be removed
                 */
                 * can skip a whole bunch of work... we will still have to
                 * authorize that this specific child can be removed
                 */
-               if (vnode_cache_is_authorized(dvp, ctx, KAUTH_VNODE_DELETE) == TRUE)
-                       parent_authorized_for_delete = TRUE;
+               if (vnode_cache_is_authorized(dvp, ctx, KAUTH_VNODE_DELETE_CHILD) == TRUE)
+                       parent_authorized_for_delete_child = TRUE;
        } else {
                dvp = NULL;
        }
        } else {
                dvp = NULL;
        }
@@ -5524,7 +6594,7 @@ vnode_authorize_callback_int(__unused kauth_cred_t unused_cred, __unused void *i
                KAUTH_DEBUG("%p    ERROR - failed to get vnode attributes - %d", vp, result);
                goto out;
        }
                KAUTH_DEBUG("%p    ERROR - failed to get vnode attributes - %d", vp, result);
                goto out;
        }
-       if (dvp && parent_authorized_for_delete == FALSE) {
+       if (dvp) {
                VATTR_WANTED(&dva, va_mode);
                VATTR_WANTED(&dva, va_uid);
                VATTR_WANTED(&dva, va_gid);
                VATTR_WANTED(&dva, va_mode);
                VATTR_WANTED(&dva, va_uid);
                VATTR_WANTED(&dva, va_gid);
@@ -5540,7 +6610,7 @@ vnode_authorize_callback_int(__unused kauth_cred_t unused_cred, __unused void *i
         * If the vnode is an extended attribute data vnode (eg. a resource fork), *_DATA becomes
         * *_EXTATTRIBUTES.
         */
         * If the vnode is an extended attribute data vnode (eg. a resource fork), *_DATA becomes
         * *_EXTATTRIBUTES.
         */
-       if (S_ISXATTR(va.va_mode) || vnode_isnamedstream(vp)) {
+       if (vnode_isnamedstream(vp)) {
                if (rights & KAUTH_VNODE_READ_DATA) {
                        rights &= ~KAUTH_VNODE_READ_DATA;
                        rights |= KAUTH_VNODE_READ_EXTATTRIBUTES;
                if (rights & KAUTH_VNODE_READ_DATA) {
                        rights &= ~KAUTH_VNODE_READ_DATA;
                        rights |= KAUTH_VNODE_READ_EXTATTRIBUTES;
@@ -5556,7 +6626,7 @@ vnode_authorize_callback_int(__unused kauth_cred_t unused_cred, __unused void *i
         */
        if (vnode_isnamedstream(vp) &&
            (vp->v_parent != NULL) &&
         */
        if (vnode_isnamedstream(vp) &&
            (vp->v_parent != NULL) &&
-           (vget_internal(vp->v_parent, 0, VNODE_NODEAD) == 0)) {
+           (vget_internal(vp->v_parent, 0, VNODE_NODEAD | VNODE_DRAINO) == 0)) {
                parent_ref = TRUE;
                vcp->vp = vp = vp->v_parent;
                if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL))
                parent_ref = TRUE;
                vcp->vp = vp = vp->v_parent;
                if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL))
@@ -5580,7 +6650,7 @@ vnode_authorize_callback_int(__unused kauth_cred_t unused_cred, __unused void *i
        if ((result = vnode_authorize_checkimmutable(vp, &va, rights, noimmutable)) != 0)
                goto out;
        if ((rights & KAUTH_VNODE_DELETE) &&
        if ((result = vnode_authorize_checkimmutable(vp, &va, rights, noimmutable)) != 0)
                goto out;
        if ((rights & KAUTH_VNODE_DELETE) &&
-           parent_authorized_for_delete == FALSE &&
+           parent_authorized_for_delete_child == FALSE &&
            ((result = vnode_authorize_checkimmutable(dvp, &dva, KAUTH_VNODE_DELETE_CHILD, 0)) != 0))
                goto out;
 
            ((result = vnode_authorize_checkimmutable(dvp, &dva, KAUTH_VNODE_DELETE_CHILD, 0)) != 0))
                goto out;
 
@@ -5593,13 +6663,14 @@ vnode_authorize_callback_int(__unused kauth_cred_t unused_cred, __unused void *i
                goto out;
 
        /*
                goto out;
 
        /*
-        * If we're not the superuser, authorize based on file properties.
+        * If we're not the superuser, authorize based on file properties;
+        * note that even if parent_authorized_for_delete_child is TRUE, we
+        * need to check on the node itself.
         */
        if (!vfs_context_issuser(ctx)) {
                /* process delete rights */
                if ((rights & KAUTH_VNODE_DELETE) &&
         */
        if (!vfs_context_issuser(ctx)) {
                /* process delete rights */
                if ((rights & KAUTH_VNODE_DELETE) &&
-                   parent_authorized_for_delete == FALSE &&
-                   ((result = vnode_authorize_delete(vcp)) != 0))
+                   ((result = vnode_authorize_delete(vcp, parent_authorized_for_delete_child)) != 0))
                    goto out;
 
                /* process remaining rights */
                    goto out;
 
                /* process remaining rights */
@@ -5650,12 +6721,21 @@ out:
                        vnode_cache_authorized_action(vp, ctx, KAUTH_VNODE_SEARCHBYANYONE);
                }
        }
                        vnode_cache_authorized_action(vp, ctx, KAUTH_VNODE_SEARCHBYANYONE);
                }
        }
-       if ((rights & KAUTH_VNODE_DELETE) && parent_authorized_for_delete == FALSE) {
+       if ((rights & KAUTH_VNODE_DELETE) && parent_authorized_for_delete_child == FALSE) {
                /*
                /*
-                * parent was successfully and newly authorized for deletions
-                * add it to the cache
+                * parent was successfully and newly authorized for content deletions
+                * add it to the cache, but only if it doesn't have the sticky
+                * bit set on it.  This same  check is done earlier guarding
+                * fetching of dva, and if we jumped to out without having done
+                * this, we will have returned already because of a non-zero
+                * 'result' value.
                 */
                 */
-               vnode_cache_authorized_action(dvp, ctx, KAUTH_VNODE_DELETE);
+               if (VATTR_IS_SUPPORTED(&dva, va_mode) &&
+                   !(dva.va_mode & (S_ISVTX))) {
+                       /* OK to cache delete rights */
+                       KAUTH_DEBUG("%p - caching DELETE_CHILD rights", dvp);
+                       vnode_cache_authorized_action(dvp, ctx, KAUTH_VNODE_DELETE_CHILD);
+               }
        }
        if (parent_ref)
                vnode_put(vp);
        }
        if (parent_ref)
                vnode_put(vp);
@@ -5667,12 +6747,18 @@ out:
        return(KAUTH_RESULT_ALLOW);
 }
 
        return(KAUTH_RESULT_ALLOW);
 }
 
+int 
+vnode_authattr_new(vnode_t dvp, struct vnode_attr *vap, int noauth, vfs_context_t ctx)
+{
+       return vnode_authattr_new_internal(dvp, vap, noauth, NULL, ctx);
+}
+
 /*
  * Check that the attribute information in vattr can be legally applied to
  * a new file by the context.
  */
 /*
  * Check that the attribute information in vattr can be legally applied to
  * a new file by the context.
  */
-int
-vnode_authattr_new(vnode_t dvp, struct vnode_attr *vap, int noauth, vfs_context_t ctx)
+static int
+vnode_authattr_new_internal(vnode_t dvp, struct vnode_attr *vap, int noauth, uint32_t *defaulted_fieldsp, vfs_context_t ctx)
 {
        int             error;
        int             has_priv_suser, ismember, defaulted_owner, defaulted_group, defaulted_mode;
 {
        int             error;
        int             has_priv_suser, ismember, defaulted_owner, defaulted_group, defaulted_mode;
@@ -5681,6 +6767,11 @@ vnode_authattr_new(vnode_t dvp, struct vnode_attr *vap, int noauth, vfs_context_
        mount_t         dmp;
 
        error = 0;
        mount_t         dmp;
 
        error = 0;
+
+       if (defaulted_fieldsp) {
+               *defaulted_fieldsp = 0;
+       }
+
        defaulted_owner = defaulted_group = defaulted_mode = 0;
 
        /*
        defaulted_owner = defaulted_group = defaulted_mode = 0;
 
        /*
@@ -5863,6 +6954,17 @@ vnode_authattr_new(vnode_t dvp, struct vnode_attr *vap, int noauth, vfs_context_
                }
        }
 out:   
                }
        }
 out:   
+       if (defaulted_fieldsp) {
+               if (defaulted_mode) {
+                       *defaulted_fieldsp |= VATTR_PREPARE_DEFAULTED_MODE;
+               }
+               if (defaulted_group) {
+                       *defaulted_fieldsp |= VATTR_PREPARE_DEFAULTED_GID;
+               }
+               if (defaulted_owner) {
+                       *defaulted_fieldsp |= VATTR_PREPARE_DEFAULTED_UID;
+               }
+       }
        return(error);
 }
 
        return(error);
 }
 
@@ -5960,6 +7062,14 @@ vnode_authattr(vnode_t vp, struct vnode_attr *vap, kauth_action_t *actionp, vfs_
                VATTR_WANTED(&ova, va_flags);
        }
 
                VATTR_WANTED(&ova, va_flags);
        }
 
+       /*
+        * If ACLs are being changed, we need the old ACLs.
+        */
+       if (VATTR_IS_ACTIVE(vap, va_acl)) {
+               KAUTH_DEBUG("ATTR - acl changing, fetching old flags");
+               VATTR_WANTED(&ova, va_acl);
+       }
+
        /*
         * If the size is being set, make sure it's not a directory.
         */
        /*
         * If the size is being set, make sure it's not a directory.
         */
@@ -6215,12 +7325,30 @@ vnode_authattr(vnode_t vp, struct vnode_attr *vap, kauth_action_t *actionp, vfs_
         */
        if (VATTR_IS_ACTIVE(vap, va_uuuid)) {
                /* if the owner UUID is not actually changing ... */
         */
        if (VATTR_IS_ACTIVE(vap, va_uuuid)) {
                /* if the owner UUID is not actually changing ... */
-               if (VATTR_IS_SUPPORTED(&ova, va_uuuid) && kauth_guid_equal(&vap->va_uuuid, &ova.va_uuuid))
-                       goto no_uuuid_change;
+               if (VATTR_IS_SUPPORTED(&ova, va_uuuid)) {
+                       if (kauth_guid_equal(&vap->va_uuuid, &ova.va_uuuid))
+                               goto no_uuuid_change;
+                       
+                       /*
+                        * If the current owner UUID is a null GUID, check
+                        * it against the UUID corresponding to the owner UID.
+                        */
+                       if (kauth_guid_equal(&ova.va_uuuid, &kauth_null_guid) &&
+                           VATTR_IS_SUPPORTED(&ova, va_uid)) {
+                               guid_t uid_guid;
+
+                               if (kauth_cred_uid2guid(ova.va_uid, &uid_guid) == 0 &&
+                                   kauth_guid_equal(&vap->va_uuuid, &uid_guid))
+                                       goto no_uuuid_change;
+                       }
+               }
                
                /*
                 * The owner UUID cannot be set by a non-superuser to anything other than
                
                /*
                 * The owner UUID cannot be set by a non-superuser to anything other than
-                * their own.
+                * their own or a null GUID (to "unset" the owner UUID).
+                * Note that file systems must be prepared to handle the
+                * null UUID case in a manner appropriate for that file
+                * system.
                 */
                if (!has_priv_suser) {
                        if ((error = kauth_cred_getguid(cred, &changer)) != 0) {
                 */
                if (!has_priv_suser) {
                        if ((error = kauth_cred_getguid(cred, &changer)) != 0) {
@@ -6228,8 +7356,9 @@ vnode_authattr(vnode_t vp, struct vnode_attr *vap, kauth_action_t *actionp, vfs_
                                /* XXX ENOENT here - no UUID - should perhaps become EPERM */
                                goto out;
                        }
                                /* XXX ENOENT here - no UUID - should perhaps become EPERM */
                                goto out;
                        }
-                       if (!kauth_guid_equal(&vap->va_uuuid, &changer)) {
-                               KAUTH_DEBUG("  ERROR - cannot set supplied owner UUID - not us");
+                       if (!kauth_guid_equal(&vap->va_uuuid, &changer) &&
+                           !kauth_guid_equal(&vap->va_uuuid, &kauth_null_guid)) {
+                               KAUTH_DEBUG("  ERROR - cannot set supplied owner UUID - not us / null");
                                error = EPERM;
                                goto out;
                        }
                                error = EPERM;
                                goto out;
                        }
@@ -6243,20 +7372,41 @@ no_uuuid_change:
         */
        if (VATTR_IS_ACTIVE(vap, va_guuid)) {
                /* if the group UUID is not actually changing ... */
         */
        if (VATTR_IS_ACTIVE(vap, va_guuid)) {
                /* if the group UUID is not actually changing ... */
-               if (VATTR_IS_SUPPORTED(&ova, va_guuid) && kauth_guid_equal(&vap->va_guuid, &ova.va_guuid))
-                       goto no_guuid_change;
+               if (VATTR_IS_SUPPORTED(&ova, va_guuid)) {
+                       if (kauth_guid_equal(&vap->va_guuid, &ova.va_guuid))
+                               goto no_guuid_change;
+
+                       /*
+                        * If the current group UUID is a null UUID, check
+                        * it against the UUID corresponding to the group GID.
+                        */
+                       if (kauth_guid_equal(&ova.va_guuid, &kauth_null_guid) &&
+                           VATTR_IS_SUPPORTED(&ova, va_gid)) {
+                               guid_t gid_guid;
+
+                               if (kauth_cred_gid2guid(ova.va_gid, &gid_guid) == 0 &&
+                                   kauth_guid_equal(&vap->va_guuid, &gid_guid))
+                                       goto no_guuid_change;
+                       }
+               }
 
                /*
                 * The group UUID cannot be set by a non-superuser to anything other than
 
                /*
                 * The group UUID cannot be set by a non-superuser to anything other than
-                * one of which they are a member.
+                * one of which they are a member or a null GUID (to "unset"
+                * the group UUID).
+                * Note that file systems must be prepared to handle the
+                * null UUID case in a manner appropriate for that file
+                * system.
                 */
                if (!has_priv_suser) {
                 */
                if (!has_priv_suser) {
-                       if ((error = kauth_cred_ismember_guid(cred, &vap->va_guuid, &ismember)) != 0) {
+                       if (kauth_guid_equal(&vap->va_guuid, &kauth_null_guid))
+                               ismember = 1;
+                       else if ((error = kauth_cred_ismember_guid(cred, &vap->va_guuid, &ismember)) != 0) {
                                KAUTH_DEBUG("  ERROR - got %d trying to check group membership", error);
                                goto out;
                        }
                        if (!ismember) {
                                KAUTH_DEBUG("  ERROR - got %d trying to check group membership", error);
                                goto out;
                        }
                        if (!ismember) {
-                               KAUTH_DEBUG("  ERROR - cannot create item with supplied group UUID - not a member");
+                               KAUTH_DEBUG("  ERROR - cannot set supplied group UUID - not a member / null");
                                error = EPERM;
                                goto out;
                        }
                                error = EPERM;
                                goto out;
                        }
@@ -6325,7 +7475,7 @@ no_guuid_change:
                                KAUTH_DEBUG("CHMOD - adding/removing ACL entries");
                        } else if (vap->va_acl->acl_entrycount > 0) {
                                /* both ACLs have the same ACE count, said count is 1 or more, bitwise compare ACLs */
                                KAUTH_DEBUG("CHMOD - adding/removing ACL entries");
                        } else if (vap->va_acl->acl_entrycount > 0) {
                                /* both ACLs have the same ACE count, said count is 1 or more, bitwise compare ACLs */
-                               if (!memcmp(&vap->va_acl->acl_ace[0], &ova.va_acl->acl_ace[0],
+                               if (memcmp(&vap->va_acl->acl_ace[0], &ova.va_acl->acl_ace[0],
                                        sizeof(struct kauth_ace) * vap->va_acl->acl_entrycount)) {
                                        required_action |= KAUTH_VNODE_WRITE_SECURITY;
                                        KAUTH_DEBUG("CHMOD - changing ACL entries");
                                        sizeof(struct kauth_ace) * vap->va_acl->acl_entrycount)) {
                                        required_action |= KAUTH_VNODE_WRITE_SECURITY;
                                        KAUTH_DEBUG("CHMOD - changing ACL entries");
@@ -6348,28 +7498,43 @@ out:
        return(error);
 }
 
        return(error);
 }
 
+static int
+setlocklocal_callback(struct vnode *vp, __unused void *cargs)
+{
+       vnode_lock_spin(vp);
+       vp->v_flag |= VLOCKLOCAL;
+       vnode_unlock(vp);
+
+       return (VNODE_RETURNED);
+}
 
 void
 vfs_setlocklocal(mount_t mp)
 {
 
 void
 vfs_setlocklocal(mount_t mp)
 {
-       vnode_t vp;
-       
-       mount_lock(mp);
+       mount_lock_spin(mp);
        mp->mnt_kern_flag |= MNTK_LOCK_LOCAL;
        mp->mnt_kern_flag |= MNTK_LOCK_LOCAL;
+       mount_unlock(mp);
 
        /*
 
        /*
-        * We do not expect anyone to be using any vnodes at the
-        * time this routine is called. So no need for vnode locking 
+        * The number of active vnodes is expected to be
+        * very small when vfs_setlocklocal is invoked.
         */
         */
-       TAILQ_FOREACH(vp, &mp->mnt_vnodelist, v_mntvnodes) {
-                       vp->v_flag |= VLOCKLOCAL;
-       }
-       TAILQ_FOREACH(vp, &mp->mnt_workerqueue, v_mntvnodes) {
-                       vp->v_flag |= VLOCKLOCAL;
-       }
-       TAILQ_FOREACH(vp, &mp->mnt_newvnodes, v_mntvnodes) {
-                       vp->v_flag |= VLOCKLOCAL;
-       }
+       vnode_iterate(mp, 0, setlocklocal_callback, NULL);
+}
+
+void
+vfs_setunmountpreflight(mount_t mp)
+{
+       mount_lock_spin(mp);
+       mp->mnt_kern_flag |= MNTK_UNMOUNT_PREFLIGHT;
+       mount_unlock(mp);
+}
+
+void
+vfs_setcompoundopen(mount_t mp)
+{
+       mount_lock_spin(mp);
+       mp->mnt_compound_ops |= COMPOUND_VNOP_OPEN;
        mount_unlock(mp);
 }
 
        mount_unlock(mp);
 }
 
@@ -6385,7 +7550,7 @@ vn_setunionwait(vnode_t vp)
 void
 vn_checkunionwait(vnode_t vp)
 {
 void
 vn_checkunionwait(vnode_t vp)
 {
-       vnode_lock(vp);
+       vnode_lock_spin(vp);
        while ((vp->v_flag & VISUNION) == VISUNION)
                msleep((caddr_t)&vp->v_flag, &vp->v_lock, 0, 0, 0);
        vnode_unlock(vp);
        while ((vp->v_flag & VISUNION) == VISUNION)
                msleep((caddr_t)&vp->v_flag, &vp->v_lock, 0, 0, 0);
        vnode_unlock(vp);
@@ -6395,7 +7560,7 @@ void
 vn_clearunionwait(vnode_t vp, int locked)
 {
        if (!locked)
 vn_clearunionwait(vnode_t vp, int locked)
 {
        if (!locked)
-               vnode_lock(vp);
+               vnode_lock_spin(vp);
        if((vp->v_flag & VISUNION) == VISUNION) {
                vp->v_flag &= ~VISUNION;
                wakeup((caddr_t)&vp->v_flag);
        if((vp->v_flag & VISUNION) == VISUNION) {
                vp->v_flag &= ~VISUNION;
                wakeup((caddr_t)&vp->v_flag);
@@ -6518,16 +7683,33 @@ errno_t rmdir_remove_orphaned_appleDouble(vnode_t vp , vfs_context_t ctx, int *
                        cpos += dp->d_reclen;
                        dp = (struct dirent*)cpos;
                }
                        cpos += dp->d_reclen;
                        dp = (struct dirent*)cpos;
                }
+               
+               /*
+                * workaround for HFS/NFS setting eofflag before end of file 
+                */
+               if (vp->v_tag == VT_HFS && nentries > 2)
+                       eofflag=0;
+
+               if (vp->v_tag == VT_NFS) {
+                       if (eofflag && !full_erase_flag) {
+                               full_erase_flag = 1;
+                               eofflag = 0;
+                               uio_reset(auio, 0, UIO_SYSSPACE, UIO_READ);
+                       }
+                       else if (!eofflag && full_erase_flag)
+                               full_erase_flag = 0;
+               }
 
        } while (!eofflag);
        /*
 
        } while (!eofflag);
        /*
-        * If we've made it here all the files in the dir are AppleDouble 
+        * If we've made it here all the files in the dir are ._ files.
         * We can delete the files even though the node is suspended
         * because we are the owner of the file.
         */
 
        uio_reset(auio, 0, UIO_SYSSPACE, UIO_READ);
        eofflag = 0;
         * We can delete the files even though the node is suspended
         * because we are the owner of the file.
         */
 
        uio_reset(auio, 0, UIO_SYSSPACE, UIO_READ);
        eofflag = 0;
+       full_erase_flag = 0;
 
        do {
                siz = UIO_BUFF_SIZE;
 
        do {
                siz = UIO_BUFF_SIZE;
@@ -6560,11 +7742,17 @@ errno_t rmdir_remove_orphaned_appleDouble(vnode_t vp , vfs_context_t ctx, int *
                                        !((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
                                            (dp->d_namlen == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.'))
                                          ) {
                                        !((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
                                            (dp->d_namlen == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.'))
                                          ) {
-                               NDINIT(&nd_temp, DELETE, USEDVP, UIO_SYSSPACE, CAST_USER_ADDR_T(dp->d_name), ctx);
+       
+                               NDINIT(&nd_temp, DELETE, OP_UNLINK, USEDVP,
+                                      UIO_SYSSPACE, CAST_USER_ADDR_T(dp->d_name),
+                                      ctx);
                                nd_temp.ni_dvp = vp;
                                error = unlink1(ctx, &nd_temp, 0);
                                nd_temp.ni_dvp = vp;
                                error = unlink1(ctx, &nd_temp, 0);
-                               if(error && error != ENOENT)
+
+                               if (error &&  error != ENOENT) {
                                        goto outsc;
                                        goto outsc;
+                               }
+
                        }
                        cpos += dp->d_reclen;
                        dp = (struct dirent*)cpos;
                        }
                        cpos += dp->d_reclen;
                        dp = (struct dirent*)cpos;
@@ -6606,25 +7794,659 @@ outsc:
 }
 
 
 }
 
 
-#ifdef JOE_DEBUG
+void 
+lock_vnode_and_post(vnode_t vp, int kevent_num) 
+{
+       /* Only take the lock if there's something there! */
+       if (vp->v_knotes.slh_first != NULL) {
+               vnode_lock(vp);
+               KNOTE(&vp->v_knotes, kevent_num);
+               vnode_unlock(vp);
+       }
+}
 
 
-record_vp(vnode_t vp, int count) {
+#ifdef JOE_DEBUG
+static void record_vp(vnode_t vp, int count) {
         struct uthread *ut;
         struct uthread *ut;
-        int  i;
 
 
+#if CONFIG_TRIGGERS
+       if (vp->v_resolve)
+               return;
+#endif
        if ((vp->v_flag & VSYSTEM))
                return;
 
        ut = get_bsdthread_info(current_thread());
         ut->uu_iocount += count;
 
        if ((vp->v_flag & VSYSTEM))
                return;
 
        ut = get_bsdthread_info(current_thread());
         ut->uu_iocount += count;
 
-       if (ut->uu_vpindex < 32) {
-               for (i = 0; i < ut->uu_vpindex; i++) {
-                       if (ut->uu_vps[i] == vp)
-                               return;
+       if (count == 1) {
+               if (ut->uu_vpindex < 32) {
+                       OSBacktrace((void **)&ut->uu_pcs[ut->uu_vpindex][0], 10);
+
+                       ut->uu_vps[ut->uu_vpindex] = vp;
+                       ut->uu_vpindex++;
                }
                }
-               ut->uu_vps[ut->uu_vpindex] = vp;
-               ut->uu_vpindex++;
        }
 }
 #endif
        }
 }
 #endif
+
+
+#if CONFIG_TRIGGERS
+
+#define TRIG_DEBUG 0
+
+#if TRIG_DEBUG
+#define TRIG_LOG(...) do { printf("%s: ", __FUNCTION__); printf(__VA_ARGS__); } while (0)
+#else
+#define TRIG_LOG(...)
+#endif
+
+/*
+ * Resolver result functions
+ */
+
+resolver_result_t
+vfs_resolver_result(uint32_t seq, enum resolver_status stat, int aux)
+{
+       /*
+        * |<---   32   --->|<---  28  --->|<- 4 ->|
+        *      sequence        auxiliary    status
+        */
+       return (((uint64_t)seq) << 32) |                
+              (((uint64_t)(aux & 0x0fffffff)) << 4) |  
+              (uint64_t)(stat & 0x0000000F);   
+}
+
+enum resolver_status
+vfs_resolver_status(resolver_result_t result)
+{
+       /* lower 4 bits is status */
+       return (result & 0x0000000F);
+}
+
+uint32_t
+vfs_resolver_sequence(resolver_result_t result)
+{
+       /* upper 32 bits is sequence */
+       return (uint32_t)(result >> 32);
+}
+
+int
+vfs_resolver_auxiliary(resolver_result_t result)
+{
+       /* 28 bits of auxiliary */
+       return (int)(((uint32_t)(result & 0xFFFFFFF0)) >> 4);
+}
+
+/*
+ * SPI
+ * Call in for resolvers to update vnode trigger state
+ */
+int
+vnode_trigger_update(vnode_t vp, resolver_result_t result)
+{
+       vnode_resolve_t rp;
+       uint32_t seq;
+       enum resolver_status stat;
+
+       if (vp->v_resolve == NULL) {
+               return (EINVAL);
+       }
+
+       stat = vfs_resolver_status(result);
+       seq = vfs_resolver_sequence(result);
+
+       if ((stat != RESOLVER_RESOLVED) && (stat != RESOLVER_UNRESOLVED)) {
+               return (EINVAL);
+       }
+
+       rp = vp->v_resolve;
+       lck_mtx_lock(&rp->vr_lock);
+
+       if (seq > rp->vr_lastseq) {
+               if (stat == RESOLVER_RESOLVED)
+                       rp->vr_flags |= VNT_RESOLVED;
+               else
+                       rp->vr_flags &= ~VNT_RESOLVED;
+
+               rp->vr_lastseq = seq;
+       }
+
+       lck_mtx_unlock(&rp->vr_lock);
+
+       return (0);
+}
+
+static int
+vnode_resolver_attach(vnode_t vp, vnode_resolve_t rp, boolean_t ref)
+{
+       int error;
+
+       vnode_lock_spin(vp);
+       if (vp->v_resolve != NULL) {
+               vnode_unlock(vp);
+               return EINVAL;
+       } else {
+               vp->v_resolve = rp;
+       }
+       vnode_unlock(vp);
+       
+       if (ref) {
+               error = vnode_ref_ext(vp, O_EVTONLY, VNODE_REF_FORCE);
+               if (error != 0) {
+                       panic("VNODE_REF_FORCE didn't help...");
+               }
+       }
+
+       return 0;
+}
+
+/*
+ * VFS internal interfaces for vnode triggers
+ *
+ * vnode must already have an io count on entry
+ * v_resolve is stable when io count is non-zero
+ */
+static int
+vnode_resolver_create(mount_t mp, vnode_t vp, struct vnode_trigger_param *tinfo, boolean_t external)
+{
+       vnode_resolve_t rp;
+       int result;
+       char byte;
+
+#if 1
+       /* minimum pointer test (debugging) */
+       if (tinfo->vnt_data)
+               byte = *((char *)tinfo->vnt_data);
+#endif
+       MALLOC(rp, vnode_resolve_t, sizeof(*rp), M_TEMP, M_WAITOK);
+       if (rp == NULL)
+               return (ENOMEM);
+
+       lck_mtx_init(&rp->vr_lock, trigger_vnode_lck_grp, trigger_vnode_lck_attr);
+
+       rp->vr_resolve_func = tinfo->vnt_resolve_func;
+       rp->vr_unresolve_func = tinfo->vnt_unresolve_func;
+       rp->vr_rearm_func = tinfo->vnt_rearm_func;
+       rp->vr_reclaim_func = tinfo->vnt_reclaim_func;
+       rp->vr_data = tinfo->vnt_data;
+       rp->vr_lastseq = 0;
+       rp->vr_flags = tinfo->vnt_flags & VNT_VALID_MASK;
+       if (external) {
+               rp->vr_flags |= VNT_EXTERNAL;
+       }
+
+       result = vnode_resolver_attach(vp, rp, external);
+       if (result != 0) {
+               goto out;
+       }
+
+       if (mp) {
+               OSAddAtomic(1, &mp->mnt_numtriggers);
+       }
+
+       return (result);
+
+out:
+       FREE(rp, M_TEMP);
+       return result;
+}
+
+static void
+vnode_resolver_release(vnode_resolve_t rp)
+{
+       /*
+        * Give them a chance to free any private data
+        */
+       if (rp->vr_data && rp->vr_reclaim_func) {
+               rp->vr_reclaim_func(NULLVP, rp->vr_data);
+       }
+
+       lck_mtx_destroy(&rp->vr_lock, trigger_vnode_lck_grp);
+       FREE(rp, M_TEMP);
+
+}
+
+/* Called after the vnode has been drained */
+static void
+vnode_resolver_detach(vnode_t vp)
+{
+       vnode_resolve_t rp;
+       mount_t mp;
+
+       mp = vnode_mount(vp);
+
+       vnode_lock(vp);
+       rp = vp->v_resolve;
+       vp->v_resolve = NULL;
+       vnode_unlock(vp);
+
+       if ((rp->vr_flags & VNT_EXTERNAL) != 0) {
+               vnode_rele_ext(vp, O_EVTONLY, 1);
+       } 
+
+       vnode_resolver_release(rp);
+       
+       /* Keep count of active trigger vnodes per mount */
+       OSAddAtomic(-1, &mp->mnt_numtriggers);  
+}
+
+/*
+ * Pathname operations that don't trigger a mount for trigger vnodes
+ */
+static const u_int64_t ignorable_pathops_mask =
+       1LL << OP_MOUNT |
+       1LL << OP_UNMOUNT |
+       1LL << OP_STATFS |
+       1LL << OP_ACCESS |
+       1LL << OP_GETATTR |
+       1LL << OP_LISTXATTR;
+
+int
+vfs_istraditionaltrigger(enum path_operation op, const struct componentname *cnp)
+{
+       if (cnp->cn_flags & ISLASTCN)
+               return ((1LL << op) & ignorable_pathops_mask) == 0;
+       else
+               return (1);
+}
+
+__private_extern__
+void
+vnode_trigger_rearm(vnode_t vp, vfs_context_t ctx)
+{
+       vnode_resolve_t rp;
+       resolver_result_t result;
+       enum resolver_status status;
+       uint32_t seq;
+
+       if ((vp->v_resolve == NULL) ||
+           (vp->v_resolve->vr_rearm_func == NULL) ||
+           (vp->v_resolve->vr_flags & VNT_AUTO_REARM) == 0) {
+               return;
+       }
+
+       rp = vp->v_resolve;
+       lck_mtx_lock(&rp->vr_lock);
+
+       /*
+        * Check if VFS initiated this unmount. If so, we'll catch it after the unresolve completes.
+        */
+       if (rp->vr_flags & VNT_VFS_UNMOUNTED) {
+               lck_mtx_unlock(&rp->vr_lock);
+               return;
+       }
+
+       /* Check if this vnode is already armed */
+       if ((rp->vr_flags & VNT_RESOLVED) == 0) {
+               lck_mtx_unlock(&rp->vr_lock);
+               return;
+       }
+
+       lck_mtx_unlock(&rp->vr_lock);
+
+       result = rp->vr_rearm_func(vp, 0, rp->vr_data, ctx);
+       status = vfs_resolver_status(result);
+       seq = vfs_resolver_sequence(result);
+
+       lck_mtx_lock(&rp->vr_lock);
+       if (seq > rp->vr_lastseq) {
+               if (status == RESOLVER_UNRESOLVED)
+                       rp->vr_flags &= ~VNT_RESOLVED;
+               rp->vr_lastseq = seq;
+       }
+       lck_mtx_unlock(&rp->vr_lock);
+}
+
+__private_extern__
+int
+vnode_trigger_resolve(vnode_t vp, struct nameidata *ndp, vfs_context_t ctx)
+{
+       vnode_resolve_t rp;
+       enum path_operation op;
+       resolver_result_t result;
+       enum resolver_status status;
+       uint32_t seq;
+
+       /* Only trigger on topmost vnodes */
+       if ((vp->v_resolve == NULL) ||
+           (vp->v_resolve->vr_resolve_func == NULL) ||
+           (vp->v_mountedhere != NULL)) {
+               return (0);
+       }
+
+       rp = vp->v_resolve;
+       lck_mtx_lock(&rp->vr_lock);
+
+       /* Check if this vnode is already resolved */
+       if (rp->vr_flags & VNT_RESOLVED) {
+               lck_mtx_unlock(&rp->vr_lock);
+               return (0);
+       }
+
+       lck_mtx_unlock(&rp->vr_lock);
+
+       /*
+        * XXX
+        * assumes that resolver will not access this trigger vnode (otherwise the kernel will deadlock)
+        * is there anyway to know this???
+        * there can also be other legitimate lookups in parallel
+        *
+        * XXX - should we call this on a separate thread with a timeout?
+        * 
+        * XXX - should we use ISLASTCN to pick the op value???  Perhaps only leafs should
+        * get the richer set and non-leafs should get generic OP_LOOKUP?  TBD
+        */
+       op = (ndp->ni_op < OP_MAXOP) ? ndp->ni_op: OP_LOOKUP;
+
+       result = rp->vr_resolve_func(vp, &ndp->ni_cnd, op, 0, rp->vr_data, ctx);
+       status = vfs_resolver_status(result);
+       seq = vfs_resolver_sequence(result);
+
+       lck_mtx_lock(&rp->vr_lock);
+       if (seq > rp->vr_lastseq) {
+               if (status == RESOLVER_RESOLVED)
+                       rp->vr_flags |= VNT_RESOLVED;
+               rp->vr_lastseq = seq;
+       }
+       lck_mtx_unlock(&rp->vr_lock);
+
+       /* On resolver errors, propagate the error back up */
+       return (status == RESOLVER_ERROR ? vfs_resolver_auxiliary(result) : 0);
+}
+
+static int
+vnode_trigger_unresolve(vnode_t vp, int flags, vfs_context_t ctx)
+{
+       vnode_resolve_t rp;
+       resolver_result_t result;
+       enum resolver_status status;
+       uint32_t seq;
+
+       if ((vp->v_resolve == NULL) || (vp->v_resolve->vr_unresolve_func == NULL)) {
+               return (0);
+       }
+
+       rp = vp->v_resolve;
+       lck_mtx_lock(&rp->vr_lock);
+
+       /* Check if this vnode is already resolved */
+       if ((rp->vr_flags & VNT_RESOLVED) == 0) {
+               printf("vnode_trigger_unresolve: not currently resolved\n");
+               lck_mtx_unlock(&rp->vr_lock);
+               return (0);
+       }
+
+       rp->vr_flags |= VNT_VFS_UNMOUNTED;
+
+       lck_mtx_unlock(&rp->vr_lock);
+
+       /*
+        * XXX
+        * assumes that resolver will not access this trigger vnode (otherwise the kernel will deadlock)
+        * there can also be other legitimate lookups in parallel
+        *
+        * XXX - should we call this on a separate thread with a timeout?
+        */
+
+       result = rp->vr_unresolve_func(vp, flags, rp->vr_data, ctx);
+       status = vfs_resolver_status(result);
+       seq = vfs_resolver_sequence(result);
+
+       lck_mtx_lock(&rp->vr_lock);
+       if (seq > rp->vr_lastseq) {
+               if (status == RESOLVER_UNRESOLVED)
+                       rp->vr_flags &= ~VNT_RESOLVED;
+               rp->vr_lastseq = seq;
+       }
+       rp->vr_flags &= ~VNT_VFS_UNMOUNTED;
+       lck_mtx_unlock(&rp->vr_lock);
+
+       /* On resolver errors, propagate the error back up */
+       return (status == RESOLVER_ERROR ? vfs_resolver_auxiliary(result) : 0);
+}
+
+static int
+triggerisdescendant(mount_t mp, mount_t rmp)
+{
+       int match = FALSE;
+
+       /*
+        * walk up vnode covered chain looking for a match
+        */
+       name_cache_lock_shared();
+
+       while (1) {
+               vnode_t vp;
+
+               /* did we encounter "/" ? */
+               if (mp->mnt_flag & MNT_ROOTFS)
+                       break;
+
+               vp = mp->mnt_vnodecovered;
+               if (vp == NULLVP)
+                       break;
+
+               mp = vp->v_mount;
+               if (mp == rmp) {
+                       match = TRUE;
+                       break;
+               }
+       }
+
+       name_cache_unlock();
+
+       return (match);
+}
+
+struct trigger_unmount_info {
+       vfs_context_t   ctx;
+       mount_t         top_mp;
+       vnode_t         trigger_vp;
+       mount_t         trigger_mp;
+       uint32_t        trigger_vid;
+       int             flags;
+};
+
+static int
+trigger_unmount_callback(mount_t mp, void * arg)
+{
+       struct trigger_unmount_info * infop = (struct trigger_unmount_info *)arg;
+       boolean_t mountedtrigger = FALSE;
+
+       /*
+        * When we encounter the top level mount we're done
+        */
+       if (mp == infop->top_mp)
+               return (VFS_RETURNED_DONE);
+
+       if ((mp->mnt_vnodecovered == NULL) ||
+           (vnode_getwithref(mp->mnt_vnodecovered) != 0)) {
+               return (VFS_RETURNED);
+       }
+
+       if ((mp->mnt_vnodecovered->v_mountedhere == mp) &&
+           (mp->mnt_vnodecovered->v_resolve != NULL) &&
+           (mp->mnt_vnodecovered->v_resolve->vr_flags & VNT_RESOLVED)) {
+               mountedtrigger = TRUE;
+       }
+       vnode_put(mp->mnt_vnodecovered);
+
+       /*
+        * When we encounter a mounted trigger, check if its under the top level mount
+        */
+       if ( !mountedtrigger || !triggerisdescendant(mp, infop->top_mp) )
+               return (VFS_RETURNED);
+
+       /*
+        * Process any pending nested mount (now that its not referenced)
+        */
+       if ((infop->trigger_vp != NULLVP) &&
+           (vnode_getwithvid(infop->trigger_vp, infop->trigger_vid) == 0)) {
+               vnode_t vp = infop->trigger_vp;
+               int error;
+
+               infop->trigger_vp = NULLVP;
+               
+               if (mp == vp->v_mountedhere) {
+                       vnode_put(vp);
+                       printf("trigger_unmount_callback: unexpected match '%s'\n",
+                               mp->mnt_vfsstat.f_mntonname);
+                       return (VFS_RETURNED);
+               }
+               if (infop->trigger_mp != vp->v_mountedhere) {
+                       vnode_put(vp);
+                       printf("trigger_unmount_callback: trigger mnt changed! (%p != %p)\n",
+                               infop->trigger_mp, vp->v_mountedhere);
+                       goto savenext;
+               }
+
+               error = vnode_trigger_unresolve(vp, infop->flags, infop->ctx);
+               vnode_put(vp);
+               if (error) {
+                       printf("unresolving: '%s', err %d\n",
+                               vp->v_mountedhere ? vp->v_mountedhere->mnt_vfsstat.f_mntonname :
+                               "???", error);
+                       return (VFS_RETURNED_DONE); /* stop iteration on errors */
+               }
+       }
+savenext:
+       /*
+        * We can't call resolver here since we hold a mount iter
+        * ref on mp so save its covered vp for later processing
+        */
+       infop->trigger_vp = mp->mnt_vnodecovered;
+       if ((infop->trigger_vp != NULLVP) &&
+           (vnode_getwithref(infop->trigger_vp) == 0)) {
+               if (infop->trigger_vp->v_mountedhere == mp) {
+                       infop->trigger_vid = infop->trigger_vp->v_id;
+                       infop->trigger_mp = mp;
+               }
+               vnode_put(infop->trigger_vp);
+       }
+
+       return (VFS_RETURNED);
+}
+
+/*
+ * Attempt to unmount any trigger mounts nested underneath a mount.
+ * This is a best effort attempt and no retries are performed here.
+ *
+ * Note: mp->mnt_rwlock is held exclusively on entry (so be carefull)
+ */
+__private_extern__
+void
+vfs_nested_trigger_unmounts(mount_t mp, int flags, vfs_context_t ctx)
+{
+       struct trigger_unmount_info info;
+
+       /* Must have trigger vnodes */
+       if (mp->mnt_numtriggers == 0) {
+               return;
+       }
+       /* Avoid recursive requests (by checking covered vnode) */
+       if ((mp->mnt_vnodecovered != NULL) &&
+           (vnode_getwithref(mp->mnt_vnodecovered) == 0)) {
+               boolean_t recursive = FALSE;
+
+               if ((mp->mnt_vnodecovered->v_mountedhere == mp) &&
+                   (mp->mnt_vnodecovered->v_resolve != NULL) &&
+                   (mp->mnt_vnodecovered->v_resolve->vr_flags & VNT_VFS_UNMOUNTED)) {
+                       recursive = TRUE;
+               }
+               vnode_put(mp->mnt_vnodecovered);
+               if (recursive)
+                       return;
+       }
+
+       /*
+        * Attempt to unmount any nested trigger mounts (best effort)
+        */
+       info.ctx = ctx;
+       info.top_mp = mp;
+       info.trigger_vp = NULLVP;
+       info.trigger_vid = 0;
+       info.trigger_mp = NULL;
+       info.flags = flags;
+
+       (void) vfs_iterate(VFS_ITERATE_TAIL_FIRST, trigger_unmount_callback, &info);
+
+       /*
+        * Process remaining nested mount (now that its not referenced)
+        */
+       if ((info.trigger_vp != NULLVP) &&
+           (vnode_getwithvid(info.trigger_vp, info.trigger_vid) == 0)) {
+               vnode_t vp = info.trigger_vp;
+
+               if (info.trigger_mp == vp->v_mountedhere) {
+                       (void) vnode_trigger_unresolve(vp, flags, ctx);
+               }
+               vnode_put(vp);
+       }
+}
+
+int
+vfs_addtrigger(mount_t mp, const char *relpath, struct vnode_trigger_info *vtip, vfs_context_t ctx)
+{
+       struct nameidata nd;
+       int res;
+       vnode_t rvp, vp;
+       struct vnode_trigger_param vtp;
+       
+       /* 
+        * Must be called for trigger callback, wherein rwlock is held 
+        */
+       lck_rw_assert(&mp->mnt_rwlock, LCK_RW_ASSERT_HELD);
+
+       TRIG_LOG("Adding trigger at %s\n", relpath);
+       TRIG_LOG("Trying VFS_ROOT\n");
+
+       /* 
+        * We do a lookup starting at the root of the mountpoint, unwilling
+        * to cross into other mountpoints.
+        */
+       res = VFS_ROOT(mp, &rvp, ctx);
+       if (res != 0) {
+               goto out;
+       }
+
+       TRIG_LOG("Trying namei\n");
+
+       NDINIT(&nd, LOOKUP, OP_LOOKUP, USEDVP | NOCROSSMOUNT | FOLLOW, UIO_SYSSPACE,
+               CAST_USER_ADDR_T(relpath), ctx);
+       nd.ni_dvp = rvp;
+       res = namei(&nd);
+       if (res != 0) {
+               vnode_put(rvp);
+               goto out;
+       }
+       
+       vp = nd.ni_vp;
+       nameidone(&nd);
+       vnode_put(rvp);
+
+       TRIG_LOG("Trying vnode_resolver_create()\n");
+
+       /* 
+        * Set up blob.  vnode_create() takes a larger structure
+        * with creation info, and we needed something different
+        * for this case.  One needs to win, or we need to munge both;
+        * vnode_create() wins.
+        */
+       bzero(&vtp, sizeof(vtp));
+       vtp.vnt_resolve_func = vtip->vti_resolve_func;
+       vtp.vnt_unresolve_func = vtip->vti_unresolve_func;
+       vtp.vnt_rearm_func = vtip->vti_rearm_func;
+       vtp.vnt_reclaim_func = vtip->vti_reclaim_func;
+       vtp.vnt_reclaim_func = vtip->vti_reclaim_func;
+       vtp.vnt_data = vtip->vti_data;
+       vtp.vnt_flags = vtip->vti_flags;
+
+       res = vnode_resolver_create(mp, vp, &vtp, TRUE);
+       vnode_put(vp);
+out:
+       TRIG_LOG("Returning %d\n", res);
+       return res;
+}
+
+#endif /* CONFIG_TRIGGERS */