1 /*
   2  * CDDL HEADER START
   3  *
   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 /*
  22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  23  * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
  24  * Copyright 2014 Nexenta Systems, Inc.  All rights reserved.
  25  */
  26 
  27 /* Portions Copyright 2007 Jeremy Teo */
  28 /* Portions Copyright 2010 Robert Milkowski */
  29 
  30 #include <sys/types.h>
  31 #include <sys/param.h>
  32 #include <sys/time.h>
  33 #include <sys/systm.h>
  34 #include <sys/sysmacros.h>
  35 #include <sys/resource.h>
  36 #include <sys/vfs.h>
  37 #include <sys/vfs_opreg.h>
  38 #include <sys/vnode.h>
  39 #include <sys/file.h>
  40 #include <sys/stat.h>
  41 #include <sys/kmem.h>
  42 #include <sys/taskq.h>
  43 #include <sys/uio.h>
  44 #include <sys/vmsystm.h>
  45 #include <sys/atomic.h>
  46 #include <sys/vm.h>
  47 #include <vm/seg_vn.h>
  48 #include <vm/pvn.h>
  49 #include <vm/as.h>
  50 #include <vm/kpm.h>
  51 #include <vm/seg_kpm.h>
  52 #include <sys/mman.h>
  53 #include <sys/pathname.h>
  54 #include <sys/cmn_err.h>
  55 #include <sys/errno.h>
  56 #include <sys/unistd.h>
  57 #include <sys/zfs_dir.h>
  58 #include <sys/zfs_acl.h>
  59 #include <sys/zfs_ioctl.h>
  60 #include <sys/fs/zfs.h>
  61 #include <sys/dmu.h>
  62 #include <sys/dmu_objset.h>
  63 #include <sys/spa.h>
  64 #include <sys/txg.h>
  65 #include <sys/dbuf.h>
  66 #include <sys/zap.h>
  67 #include <sys/sa.h>
  68 #include <sys/dirent.h>
  69 #include <sys/policy.h>
  70 #include <sys/sunddi.h>
  71 #include <sys/filio.h>
  72 #include <sys/sid.h>
  73 #include "fs/fs_subr.h"
  74 #include <sys/zfs_ctldir.h>
  75 #include <sys/zfs_fuid.h>
  76 #include <sys/zfs_sa.h>
  77 #include <sys/zfeature.h>
  78 #include <sys/dnlc.h>
  79 #include <sys/zfs_rlock.h>
  80 #include <sys/extdirent.h>
  81 #include <sys/kidmap.h>
  82 #include <sys/cred.h>
  83 #include <sys/attr.h>
  84 
  85 /*
  86  * Programming rules.
  87  *
  88  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
  89  * properly lock its in-core state, create a DMU transaction, do the work,
  90  * record this work in the intent log (ZIL), commit the DMU transaction,
  91  * and wait for the intent log to commit if it is a synchronous operation.
  92  * Moreover, the vnode ops must work in both normal and log replay context.
  93  * The ordering of events is important to avoid deadlocks and references
  94  * to freed memory.  The example below illustrates the following Big Rules:
  95  *
  96  *  (1) A check must be made in each zfs thread for a mounted file system.
  97  *      This is done avoiding races using ZFS_ENTER(zfsvfs).
  98  *      A ZFS_EXIT(zfsvfs) is needed before all returns.  Any znodes
  99  *      must be checked with ZFS_VERIFY_ZP(zp).  Both of these macros
 100  *      can return EIO from the calling function.
 101  *
 102  *  (2) VN_RELE() should always be the last thing except for zil_commit()
 103  *      (if necessary) and ZFS_EXIT(). This is for 3 reasons:
 104  *      First, if it's the last reference, the vnode/znode
 105  *      can be freed, so the zp may point to freed memory.  Second, the last
 106  *      reference will call zfs_zinactive(), which may induce a lot of work --
 107  *      pushing cached pages (which acquires range locks) and syncing out
 108  *      cached atime changes.  Third, zfs_zinactive() may require a new tx,
 109  *      which could deadlock the system if you were already holding one.
 110  *      If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
 111  *
 112  *  (3) All range locks must be grabbed before calling dmu_tx_assign(),
 113  *      as they can span dmu_tx_assign() calls.
 114  *
 115  *  (4) If ZPL locks are held, pass TXG_NOWAIT as the second argument to
 116  *      dmu_tx_assign().  This is critical because we don't want to block
 117  *      while holding locks.
 118  *
 119  *      If no ZPL locks are held (aside from ZFS_ENTER()), use TXG_WAIT.  This
 120  *      reduces lock contention and CPU usage when we must wait (note that if
 121  *      throughput is constrained by the storage, nearly every transaction
 122  *      must wait).
 123  *
 124  *      Note, in particular, that if a lock is sometimes acquired before
 125  *      the tx assigns, and sometimes after (e.g. z_lock), then failing
 126  *      to use a non-blocking assign can deadlock the system.  The scenario:
 127  *
 128  *      Thread A has grabbed a lock before calling dmu_tx_assign().
 129  *      Thread B is in an already-assigned tx, and blocks for this lock.
 130  *      Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
 131  *      forever, because the previous txg can't quiesce until B's tx commits.
 132  *
 133  *      If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
 134  *      then drop all locks, call dmu_tx_wait(), and try again.  On subsequent
 135  *      calls to dmu_tx_assign(), pass TXG_WAITED rather than TXG_NOWAIT,
 136  *      to indicate that this operation has already called dmu_tx_wait().
 137  *      This will ensure that we don't retry forever, waiting a short bit
 138  *      each time.
 139  *
 140  *  (5) If the operation succeeded, generate the intent log entry for it
 141  *      before dropping locks.  This ensures that the ordering of events
 142  *      in the intent log matches the order in which they actually occurred.
 143  *      During ZIL replay the zfs_log_* functions will update the sequence
 144  *      number to indicate the zil transaction has replayed.
 145  *
 146  *  (6) At the end of each vnode op, the DMU tx must always commit,
 147  *      regardless of whether there were any errors.
 148  *
 149  *  (7) After dropping all locks, invoke zil_commit(zilog, foid)
 150  *      to ensure that synchronous semantics are provided when necessary.
 151  *
 152  * In general, this is how things should be ordered in each vnode op:
 153  *
 154  *      ZFS_ENTER(zfsvfs);              // exit if unmounted
 155  * top:
 156  *      zfs_dirent_lock(&dl, ...)   // lock directory entry (may VN_HOLD())
 157  *      rw_enter(...);                  // grab any other locks you need
 158  *      tx = dmu_tx_create(...);        // get DMU tx
 159  *      dmu_tx_hold_*();                // hold each object you might modify
 160  *      error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
 161  *      if (error) {
 162  *              rw_exit(...);           // drop locks
 163  *              zfs_dirent_unlock(dl);  // unlock directory entry
 164  *              VN_RELE(...);           // release held vnodes
 165  *              if (error == ERESTART) {
 166  *                      waited = B_TRUE;
 167  *                      dmu_tx_wait(tx);
 168  *                      dmu_tx_abort(tx);
 169  *                      goto top;
 170  *              }
 171  *              dmu_tx_abort(tx);       // abort DMU tx
 172  *              ZFS_EXIT(zfsvfs);       // finished in zfs
 173  *              return (error);         // really out of space
 174  *      }
 175  *      error = do_real_work();         // do whatever this VOP does
 176  *      if (error == 0)
 177  *              zfs_log_*(...);         // on success, make ZIL entry
 178  *      dmu_tx_commit(tx);              // commit DMU tx -- error or not
 179  *      rw_exit(...);                   // drop locks
 180  *      zfs_dirent_unlock(dl);          // unlock directory entry
 181  *      VN_RELE(...);                   // release held vnodes
 182  *      zil_commit(zilog, foid);        // synchronous when necessary
 183  *      ZFS_EXIT(zfsvfs);               // finished in zfs
 184  *      return (error);                 // done, report error
 185  */
 186 
 187 /* ARGSUSED */
 188 static int
 189 zfs_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
 190 {
 191         znode_t *zp = VTOZ(*vpp);
 192         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
 193 
 194         ZFS_ENTER(zfsvfs);
 195         ZFS_VERIFY_ZP(zp);
 196 
 197         if ((flag & FWRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
 198             ((flag & FAPPEND) == 0)) {
 199                 ZFS_EXIT(zfsvfs);
 200                 return (SET_ERROR(EPERM));
 201         }
 202 
 203         if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
 204             ZTOV(zp)->v_type == VREG &&
 205             !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0) {
 206                 if (fs_vscan(*vpp, cr, 0) != 0) {
 207                         ZFS_EXIT(zfsvfs);
 208                         return (SET_ERROR(EACCES));
 209                 }
 210         }
 211 
 212         /* Keep a count of the synchronous opens in the znode */
 213         if (flag & (FSYNC | FDSYNC))
 214                 atomic_inc_32(&zp->z_sync_cnt);
 215 
 216         ZFS_EXIT(zfsvfs);
 217         return (0);
 218 }
 219 
 220 /* ARGSUSED */
 221 static int
 222 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
 223     caller_context_t *ct)
 224 {
 225         znode_t *zp = VTOZ(vp);
 226         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
 227 
 228         /*
 229          * Clean up any locks held by this process on the vp.
 230          */
 231         cleanlocks(vp, ddi_get_pid(), 0);
 232         cleanshares(vp, ddi_get_pid());
 233 
 234         ZFS_ENTER(zfsvfs);
 235         ZFS_VERIFY_ZP(zp);
 236 
 237         /* Decrement the synchronous opens in the znode */
 238         if ((flag & (FSYNC | FDSYNC)) && (count == 1))
 239                 atomic_dec_32(&zp->z_sync_cnt);
 240 
 241         if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
 242             ZTOV(zp)->v_type == VREG &&
 243             !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0)
 244                 VERIFY(fs_vscan(vp, cr, 1) == 0);
 245 
 246         ZFS_EXIT(zfsvfs);
 247         return (0);
 248 }
 249 
 250 /*
 251  * Lseek support for finding holes (cmd == _FIO_SEEK_HOLE) and
 252  * data (cmd == _FIO_SEEK_DATA). "off" is an in/out parameter.
 253  */
 254 static int
 255 zfs_holey(vnode_t *vp, int cmd, offset_t *off)
 256 {
 257         znode_t *zp = VTOZ(vp);
 258         uint64_t noff = (uint64_t)*off; /* new offset */
 259         uint64_t file_sz;
 260         int error;
 261         boolean_t hole;
 262 
 263         file_sz = zp->z_size;
 264         if (noff >= file_sz)  {
 265                 return (SET_ERROR(ENXIO));
 266         }
 267 
 268         if (cmd == _FIO_SEEK_HOLE)
 269                 hole = B_TRUE;
 270         else
 271                 hole = B_FALSE;
 272 
 273         error = dmu_offset_next(zp->z_zfsvfs->z_os, zp->z_id, hole, &noff);
 274 
 275         if (error == ESRCH)
 276                 return (SET_ERROR(ENXIO));
 277 
 278         /*
 279          * We could find a hole that begins after the logical end-of-file,
 280          * because dmu_offset_next() only works on whole blocks.  If the
 281          * EOF falls mid-block, then indicate that the "virtual hole"
 282          * at the end of the file begins at the logical EOF, rather than
 283          * at the end of the last block.
 284          */
 285         if (noff > file_sz) {
 286                 ASSERT(hole);
 287                 noff = file_sz;
 288         }
 289 
 290         if (noff < *off)
 291                 return (error);
 292         *off = noff;
 293         return (error);
 294 }
 295 
 296 
 297 static int zfs_zero_write(vnode_t *vp, uint64_t size, cred_t *cr,
 298     caller_context_t *ct);
 299 
 300 /* ARGSUSED */
 301 static int
 302 zfs_ioctl(vnode_t *vp, int com, intptr_t data, int flag, cred_t *cred,
 303     int *rvalp, caller_context_t *ct)
 304 {
 305         offset_t off;
 306         int error;
 307         zfsvfs_t *zfsvfs;
 308         znode_t *zp;
 309         uint64_t size;
 310 
 311         switch (com) {
 312         case _FIOFFS:
 313                 return (zfs_sync(vp->v_vfsp, 0, cred));
 314 
 315                 /*
 316                  * The following two ioctls are used by bfu.  Faking out,
 317                  * necessary to avoid bfu errors.
 318                  */
 319         case _FIOGDIO:
 320         case _FIOSDIO:
 321                 return (0);
 322 
 323         case _FIO_SEEK_DATA:
 324         case _FIO_SEEK_HOLE:
 325                 if (ddi_copyin((void *)data, &off, sizeof (off), flag))
 326                         return (SET_ERROR(EFAULT));
 327 
 328                 zp = VTOZ(vp);
 329                 zfsvfs = zp->z_zfsvfs;
 330                 ZFS_ENTER(zfsvfs);
 331                 ZFS_VERIFY_ZP(zp);
 332 
 333                 /* offset parameter is in/out */
 334                 error = zfs_holey(vp, com, &off);
 335                 ZFS_EXIT(zfsvfs);
 336                 if (error)
 337                         return (error);
 338                 if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
 339                         return (SET_ERROR(EFAULT));
 340                 return (0);
 341         case _FIO_RESERVE_SPACE:
 342                 if (ddi_copyin((void *)data, &size, sizeof (size), flag))
 343                         return (EFAULT);
 344                 error = zfs_zero_write(vp, size, cred, ct);
 345                 return (error);
 346         }
 347         return (SET_ERROR(ENOTTY));
 348 }
 349 
 350 /*
 351  * Utility functions to map and unmap a single physical page.  These
 352  * are used to manage the mappable copies of ZFS file data, and therefore
 353  * do not update ref/mod bits.
 354  */
 355 caddr_t
 356 zfs_map_page(page_t *pp, enum seg_rw rw)
 357 {
 358         if (kpm_enable)
 359                 return (hat_kpm_mapin(pp, 0));
 360         ASSERT(rw == S_READ || rw == S_WRITE);
 361         return (ppmapin(pp, PROT_READ | ((rw == S_WRITE) ? PROT_WRITE : 0),
 362             (caddr_t)-1));
 363 }
 364 
 365 void
 366 zfs_unmap_page(page_t *pp, caddr_t addr)
 367 {
 368         if (kpm_enable) {
 369                 hat_kpm_mapout(pp, 0, addr);
 370         } else {
 371                 ppmapout(addr);
 372         }
 373 }
 374 
 375 /*
 376  * When a file is memory mapped, we must keep the IO data synchronized
 377  * between the DMU cache and the memory mapped pages.  What this means:
 378  *
 379  * On Write:    If we find a memory mapped page, we write to *both*
 380  *              the page and the dmu buffer.
 381  */
 382 static void
 383 update_pages(vnode_t *vp, int64_t start, int len, objset_t *os, uint64_t oid)
 384 {
 385         int64_t off;
 386 
 387         off = start & PAGEOFFSET;
 388         for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
 389                 page_t *pp;
 390                 uint64_t nbytes = MIN(PAGESIZE - off, len);
 391 
 392                 if (pp = page_lookup(vp, start, SE_SHARED)) {
 393                         caddr_t va;
 394 
 395                         va = zfs_map_page(pp, S_WRITE);
 396                         (void) dmu_read(os, oid, start+off, nbytes, va+off,
 397                             DMU_READ_PREFETCH);
 398                         zfs_unmap_page(pp, va);
 399                         page_unlock(pp);
 400                 }
 401                 len -= nbytes;
 402                 off = 0;
 403         }
 404 }
 405 
 406 /*
 407  * When a file is memory mapped, we must keep the IO data synchronized
 408  * between the DMU cache and the memory mapped pages.  What this means:
 409  *
 410  * On Read:     We "read" preferentially from memory mapped pages,
 411  *              else we default from the dmu buffer.
 412  *
 413  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
 414  *       the file is memory mapped.
 415  */
 416 static int
 417 mappedread(vnode_t *vp, int nbytes, uio_t *uio)
 418 {
 419         znode_t *zp = VTOZ(vp);
 420         int64_t start, off;
 421         int len = nbytes;
 422         int error = 0;
 423 
 424         start = uio->uio_loffset;
 425         off = start & PAGEOFFSET;
 426         for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
 427                 page_t *pp;
 428                 uint64_t bytes = MIN(PAGESIZE - off, len);
 429 
 430                 if (pp = page_lookup(vp, start, SE_SHARED)) {
 431                         caddr_t va;
 432 
 433                         va = zfs_map_page(pp, S_READ);
 434                         error = uiomove(va + off, bytes, UIO_READ, uio);
 435                         zfs_unmap_page(pp, va);
 436                         page_unlock(pp);
 437                 } else {
 438                         error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
 439                             uio, bytes);
 440                 }
 441                 len -= bytes;
 442                 off = 0;
 443                 if (error)
 444                         break;
 445         }
 446         return (error);
 447 }
 448 
 449 offset_t zfs_read_chunk_size = 1024 * 1024; /* Tunable */
 450 
 451 /*
 452  * Read bytes from specified file into supplied buffer.
 453  *
 454  *      IN:     vp      - vnode of file to be read from.
 455  *              uio     - structure supplying read location, range info,
 456  *                        and return buffer.
 457  *              ioflag  - SYNC flags; used to provide FRSYNC semantics.
 458  *              cr      - credentials of caller.
 459  *              ct      - caller context
 460  *
 461  *      OUT:    uio     - updated offset and range, buffer filled.
 462  *
 463  *      RETURN: 0 on success, error code on failure.
 464  *
 465  * Side Effects:
 466  *      vp - atime updated if byte count > 0
 467  */
 468 /* ARGSUSED */
 469 static int
 470 zfs_read(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
 471 {
 472         znode_t         *zp = VTOZ(vp);
 473         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
 474         ssize_t         n, nbytes;
 475         int             error = 0;
 476         rl_t            *rl;
 477         xuio_t          *xuio = NULL;
 478 
 479         ZFS_ENTER(zfsvfs);
 480         ZFS_VERIFY_ZP(zp);
 481 
 482         if (zp->z_pflags & ZFS_AV_QUARANTINED) {
 483                 ZFS_EXIT(zfsvfs);
 484                 return (SET_ERROR(EACCES));
 485         }
 486 
 487         /*
 488          * Validate file offset
 489          */
 490         if (uio->uio_loffset < (offset_t)0) {
 491                 ZFS_EXIT(zfsvfs);
 492                 return (SET_ERROR(EINVAL));
 493         }
 494 
 495         /*
 496          * Fasttrack empty reads
 497          */
 498         if (uio->uio_resid == 0) {
 499                 ZFS_EXIT(zfsvfs);
 500                 return (0);
 501         }
 502 
 503         /*
 504          * Check for mandatory locks
 505          */
 506         if (MANDMODE(zp->z_mode)) {
 507                 if (error = chklock(vp, FREAD,
 508                     uio->uio_loffset, uio->uio_resid, uio->uio_fmode, ct)) {
 509                         ZFS_EXIT(zfsvfs);
 510                         return (error);
 511                 }
 512         }
 513 
 514         /*
 515          * If we're in FRSYNC mode, sync out this znode before reading it.
 516          */
 517         if (ioflag & FRSYNC || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
 518                 zil_commit(zfsvfs->z_log, zp->z_id);
 519 
 520         /*
 521          * Lock the range against changes.
 522          */
 523         rl = zfs_range_lock(zp, uio->uio_loffset, uio->uio_resid, RL_READER);
 524 
 525         /*
 526          * If we are reading past end-of-file we can skip
 527          * to the end; but we might still need to set atime.
 528          */
 529         if (uio->uio_loffset >= zp->z_size) {
 530                 error = 0;
 531                 goto out;
 532         }
 533 
 534         ASSERT(uio->uio_loffset < zp->z_size);
 535         n = MIN(uio->uio_resid, zp->z_size - uio->uio_loffset);
 536 
 537         if ((uio->uio_extflg == UIO_XUIO) &&
 538             (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY)) {
 539                 int nblk;
 540                 int blksz = zp->z_blksz;
 541                 uint64_t offset = uio->uio_loffset;
 542 
 543                 xuio = (xuio_t *)uio;
 544                 if ((ISP2(blksz))) {
 545                         nblk = (P2ROUNDUP(offset + n, blksz) - P2ALIGN(offset,
 546                             blksz)) / blksz;
 547                 } else {
 548                         ASSERT(offset + n <= blksz);
 549                         nblk = 1;
 550                 }
 551                 (void) dmu_xuio_init(xuio, nblk);
 552 
 553                 if (vn_has_cached_data(vp)) {
 554                         /*
 555                          * For simplicity, we always allocate a full buffer
 556                          * even if we only expect to read a portion of a block.
 557                          */
 558                         while (--nblk >= 0) {
 559                                 (void) dmu_xuio_add(xuio,
 560                                     dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
 561                                     blksz), 0, blksz);
 562                         }
 563                 }
 564         }
 565 
 566         while (n > 0) {
 567                 nbytes = MIN(n, zfs_read_chunk_size -
 568                     P2PHASE(uio->uio_loffset, zfs_read_chunk_size));
 569 
 570                 if (vn_has_cached_data(vp)) {
 571                         error = mappedread(vp, nbytes, uio);
 572                 } else {
 573                         error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
 574                             uio, nbytes);
 575                 }
 576                 if (error) {
 577                         /* convert checksum errors into IO errors */
 578                         if (error == ECKSUM)
 579                                 error = SET_ERROR(EIO);
 580                         break;
 581                 }
 582 
 583                 n -= nbytes;
 584         }
 585 out:
 586         zfs_range_unlock(rl);
 587 
 588         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
 589         ZFS_EXIT(zfsvfs);
 590         return (error);
 591 }
 592 
 593 /*
 594  * Write the bytes to a file.
 595  *
 596  *      IN:     vp      - vnode of file to be written to.
 597  *              uio     - structure supplying write location, range info,
 598  *                        and data buffer.
 599  *              ioflag  - FAPPEND, FSYNC, and/or FDSYNC.  FAPPEND is
 600  *                        set if in append mode.
 601  *              cr      - credentials of caller.
 602  *              ct      - caller context (NFS/CIFS fem monitor only)
 603  *
 604  *      OUT:    uio     - updated offset and range.
 605  *
 606  *      RETURN: 0 on success, error code on failure.
 607  *
 608  * Timestamps:
 609  *      vp - ctime|mtime updated if byte count > 0
 610  */
 611 
 612 /* ARGSUSED */
 613 static int
 614 zfs_write(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
 615 {
 616         znode_t         *zp = VTOZ(vp);
 617         rlim64_t        limit = uio->uio_llimit;
 618         ssize_t         start_resid = uio->uio_resid;
 619         ssize_t         tx_bytes;
 620         uint64_t        end_size;
 621         dmu_tx_t        *tx;
 622         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
 623         zilog_t         *zilog;
 624         offset_t        woff;
 625         ssize_t         n, nbytes;
 626         rl_t            *rl;
 627         int             max_blksz = zfsvfs->z_max_blksz;
 628         int             error = 0;
 629         arc_buf_t       *abuf;
 630         iovec_t         *aiov = NULL;
 631         xuio_t          *xuio = NULL;
 632         int             i_iov = 0;
 633         int             iovcnt = uio->uio_iovcnt;
 634         iovec_t         *iovp = uio->uio_iov;
 635         int             write_eof;
 636         int             count = 0;
 637         sa_bulk_attr_t  bulk[4];
 638         uint64_t        mtime[2], ctime[2];
 639 
 640         /*
 641          * Fasttrack empty write
 642          */
 643         n = start_resid;
 644         if (n == 0)
 645                 return (0);
 646 
 647         if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
 648                 limit = MAXOFFSET_T;
 649 
 650         ZFS_ENTER(zfsvfs);
 651         ZFS_VERIFY_ZP(zp);
 652 
 653         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
 654         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
 655         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
 656             &zp->z_size, 8);
 657         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
 658             &zp->z_pflags, 8);
 659 
 660         /*
 661          * In a case vp->v_vfsp != zp->z_zfsvfs->z_vfs (e.g. snapshots) our
 662          * callers might not be able to detect properly that we are read-only,
 663          * so check it explicitly here.
 664          */
 665         if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
 666                 ZFS_EXIT(zfsvfs);
 667                 return (SET_ERROR(EROFS));
 668         }
 669 
 670         /*
 671          * If immutable or not appending then return EPERM
 672          */
 673         if ((zp->z_pflags & (ZFS_IMMUTABLE | ZFS_READONLY)) ||
 674             ((zp->z_pflags & ZFS_APPENDONLY) && !(ioflag & FAPPEND) &&
 675             (uio->uio_loffset < zp->z_size))) {
 676                 ZFS_EXIT(zfsvfs);
 677                 return (SET_ERROR(EPERM));
 678         }
 679 
 680         zilog = zfsvfs->z_log;
 681 
 682         /*
 683          * Validate file offset
 684          */
 685         woff = ioflag & FAPPEND ? zp->z_size : uio->uio_loffset;
 686         if (woff < 0) {
 687                 ZFS_EXIT(zfsvfs);
 688                 return (SET_ERROR(EINVAL));
 689         }
 690 
 691         /*
 692          * Check for mandatory locks before calling zfs_range_lock()
 693          * in order to prevent a deadlock with locks set via fcntl().
 694          */
 695         if (MANDMODE((mode_t)zp->z_mode) &&
 696             (error = chklock(vp, FWRITE, woff, n, uio->uio_fmode, ct)) != 0) {
 697                 ZFS_EXIT(zfsvfs);
 698                 return (error);
 699         }
 700 
 701         /*
 702          * Pre-fault the pages to ensure slow (eg NFS) pages
 703          * don't hold up txg.
 704          * Skip this if uio contains loaned arc_buf.
 705          */
 706         if ((uio->uio_extflg == UIO_XUIO) &&
 707             (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY))
 708                 xuio = (xuio_t *)uio;
 709         else
 710                 uio_prefaultpages(MIN(n, max_blksz), uio);
 711 
 712         /*
 713          * If in append mode, set the io offset pointer to eof.
 714          */
 715         if (ioflag & FAPPEND) {
 716                 /*
 717                  * Obtain an appending range lock to guarantee file append
 718                  * semantics.  We reset the write offset once we have the lock.
 719                  */
 720                 rl = zfs_range_lock(zp, 0, n, RL_APPEND);
 721                 woff = rl->r_off;
 722                 if (rl->r_len == UINT64_MAX) {
 723                         /*
 724                          * We overlocked the file because this write will cause
 725                          * the file block size to increase.
 726                          * Note that zp_size cannot change with this lock held.
 727                          */
 728                         woff = zp->z_size;
 729                 }
 730                 uio->uio_loffset = woff;
 731         } else {
 732                 /*
 733                  * Note that if the file block size will change as a result of
 734                  * this write, then this range lock will lock the entire file
 735                  * so that we can re-write the block safely.
 736                  */
 737                 rl = zfs_range_lock(zp, woff, n, RL_WRITER);
 738         }
 739 
 740         if (woff >= limit) {
 741                 zfs_range_unlock(rl);
 742                 ZFS_EXIT(zfsvfs);
 743                 return (SET_ERROR(EFBIG));
 744         }
 745 
 746         if ((woff + n) > limit || woff > (limit - n))
 747                 n = limit - woff;
 748 
 749         /* Will this write extend the file length? */
 750         write_eof = (woff + n > zp->z_size);
 751 
 752         end_size = MAX(zp->z_size, woff + n);
 753 
 754         /*
 755          * Write the file in reasonable size chunks.  Each chunk is written
 756          * in a separate transaction; this keeps the intent log records small
 757          * and allows us to do more fine-grained space accounting.
 758          */
 759         while (n > 0) {
 760                 abuf = NULL;
 761                 woff = uio->uio_loffset;
 762                 if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
 763                     zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
 764                         if (abuf != NULL)
 765                                 dmu_return_arcbuf(abuf);
 766                         error = SET_ERROR(EDQUOT);
 767                         break;
 768                 }
 769 
 770                 if (xuio && abuf == NULL) {
 771                         ASSERT(i_iov < iovcnt);
 772                         aiov = &iovp[i_iov];
 773                         abuf = dmu_xuio_arcbuf(xuio, i_iov);
 774                         dmu_xuio_clear(xuio, i_iov);
 775                         DTRACE_PROBE3(zfs_cp_write, int, i_iov,
 776                             iovec_t *, aiov, arc_buf_t *, abuf);
 777                         ASSERT((aiov->iov_base == abuf->b_data) ||
 778                             ((char *)aiov->iov_base - (char *)abuf->b_data +
 779                             aiov->iov_len == arc_buf_size(abuf)));
 780                         i_iov++;
 781                 } else if (abuf == NULL && n >= max_blksz &&
 782                     woff >= zp->z_size &&
 783                     P2PHASE(woff, max_blksz) == 0 &&
 784                     zp->z_blksz == max_blksz) {
 785                         /*
 786                          * This write covers a full block.  "Borrow" a buffer
 787                          * from the dmu so that we can fill it before we enter
 788                          * a transaction.  This avoids the possibility of
 789                          * holding up the transaction if the data copy hangs
 790                          * up on a pagefault (e.g., from an NFS server mapping).
 791                          */
 792                         size_t cbytes;
 793 
 794                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
 795                             max_blksz);
 796                         ASSERT(abuf != NULL);
 797                         ASSERT(arc_buf_size(abuf) == max_blksz);
 798                         if (error = uiocopy(abuf->b_data, max_blksz,
 799                             UIO_WRITE, uio, &cbytes)) {
 800                                 dmu_return_arcbuf(abuf);
 801                                 break;
 802                         }
 803                         ASSERT(cbytes == max_blksz);
 804                 }
 805 
 806                 /*
 807                  * Start a transaction.
 808                  */
 809                 tx = dmu_tx_create(zfsvfs->z_os);
 810                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
 811                 dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
 812                 zfs_sa_upgrade_txholds(tx, zp);
 813                 error = dmu_tx_assign(tx, TXG_WAIT);
 814                 if (error) {
 815                         dmu_tx_abort(tx);
 816                         if (abuf != NULL)
 817                                 dmu_return_arcbuf(abuf);
 818                         break;
 819                 }
 820 
 821                 /*
 822                  * If zfs_range_lock() over-locked we grow the blocksize
 823                  * and then reduce the lock range.  This will only happen
 824                  * on the first iteration since zfs_range_reduce() will
 825                  * shrink down r_len to the appropriate size.
 826                  */
 827                 if (rl->r_len == UINT64_MAX) {
 828                         uint64_t new_blksz;
 829 
 830                         if (zp->z_blksz > max_blksz) {
 831                                 ASSERT(!ISP2(zp->z_blksz));
 832                                 new_blksz = MIN(end_size, SPA_MAXBLOCKSIZE);
 833                         } else {
 834                                 new_blksz = MIN(end_size, max_blksz);
 835                         }
 836                         zfs_grow_blocksize(zp, new_blksz, tx);
 837                         zfs_range_reduce(rl, woff, n);
 838                 }
 839 
 840                 /*
 841                  * XXX - should we really limit each write to z_max_blksz?
 842                  * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
 843                  */
 844                 nbytes = MIN(n, max_blksz - P2PHASE(woff, max_blksz));
 845 
 846                 if (abuf == NULL) {
 847                         tx_bytes = uio->uio_resid;
 848                         error = dmu_write_uio_dbuf(sa_get_db(zp->z_sa_hdl),
 849                             uio, nbytes, tx);
 850                         tx_bytes -= uio->uio_resid;
 851                 } else {
 852                         tx_bytes = nbytes;
 853                         ASSERT(xuio == NULL || tx_bytes == aiov->iov_len);
 854                         /*
 855                          * If this is not a full block write, but we are
 856                          * extending the file past EOF and this data starts
 857                          * block-aligned, use assign_arcbuf().  Otherwise,
 858                          * write via dmu_write().
 859                          */
 860                         if (tx_bytes < max_blksz && (!write_eof ||
 861                             aiov->iov_base != abuf->b_data)) {
 862                                 ASSERT(xuio);
 863                                 dmu_write(zfsvfs->z_os, zp->z_id, woff,
 864                                     aiov->iov_len, aiov->iov_base, tx);
 865                                 dmu_return_arcbuf(abuf);
 866                                 xuio_stat_wbuf_copied();
 867                         } else {
 868                                 ASSERT(xuio || tx_bytes == max_blksz);
 869                                 dmu_assign_arcbuf(sa_get_db(zp->z_sa_hdl),
 870                                     woff, abuf, tx);
 871                         }
 872                         ASSERT(tx_bytes <= uio->uio_resid);
 873                         uioskip(uio, tx_bytes);
 874                 }
 875                 if (tx_bytes && vn_has_cached_data(vp)) {
 876                         update_pages(vp, woff,
 877                             tx_bytes, zfsvfs->z_os, zp->z_id);
 878                 }
 879 
 880                 /*
 881                  * If we made no progress, we're done.  If we made even
 882                  * partial progress, update the znode and ZIL accordingly.
 883                  */
 884                 if (tx_bytes == 0) {
 885                         (void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
 886                             (void *)&zp->z_size, sizeof (uint64_t), tx);
 887                         dmu_tx_commit(tx);
 888                         ASSERT(error != 0);
 889                         break;
 890                 }
 891 
 892                 /*
 893                  * Clear Set-UID/Set-GID bits on successful write if not
 894                  * privileged and at least one of the excute bits is set.
 895                  *
 896                  * It would be nice to to this after all writes have
 897                  * been done, but that would still expose the ISUID/ISGID
 898                  * to another app after the partial write is committed.
 899                  *
 900                  * Note: we don't call zfs_fuid_map_id() here because
 901                  * user 0 is not an ephemeral uid.
 902                  */
 903                 mutex_enter(&zp->z_acl_lock);
 904                 if ((zp->z_mode & (S_IXUSR | (S_IXUSR >> 3) |
 905                     (S_IXUSR >> 6))) != 0 &&
 906                     (zp->z_mode & (S_ISUID | S_ISGID)) != 0 &&
 907                     secpolicy_vnode_setid_retain(cr,
 908                     (zp->z_mode & S_ISUID) != 0 && zp->z_uid == 0) != 0) {
 909                         uint64_t newmode;
 910                         zp->z_mode &= ~(S_ISUID | S_ISGID);
 911                         newmode = zp->z_mode;
 912                         (void) sa_update(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs),
 913                             (void *)&newmode, sizeof (uint64_t), tx);
 914                 }
 915                 mutex_exit(&zp->z_acl_lock);
 916 
 917                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
 918                     B_TRUE);
 919 
 920                 /*
 921                  * Update the file size (zp_size) if it has changed;
 922                  * account for possible concurrent updates.
 923                  */
 924                 while ((end_size = zp->z_size) < uio->uio_loffset) {
 925                         (void) atomic_cas_64(&zp->z_size, end_size,
 926                             uio->uio_loffset);
 927                         ASSERT(error == 0);
 928                 }
 929                 /*
 930                  * If we are replaying and eof is non zero then force
 931                  * the file size to the specified eof. Note, there's no
 932                  * concurrency during replay.
 933                  */
 934                 if (zfsvfs->z_replay && zfsvfs->z_replay_eof != 0)
 935                         zp->z_size = zfsvfs->z_replay_eof;
 936 
 937                 error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
 938 
 939                 zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, ioflag);
 940                 dmu_tx_commit(tx);
 941 
 942                 if (error != 0)
 943                         break;
 944                 ASSERT(tx_bytes == nbytes);
 945                 n -= nbytes;
 946 
 947                 if (!xuio && n > 0)
 948                         uio_prefaultpages(MIN(n, max_blksz), uio);
 949         }
 950 
 951         zfs_range_unlock(rl);
 952 
 953         /*
 954          * If we're in replay mode, or we made no progress, return error.
 955          * Otherwise, it's at least a partial write, so it's successful.
 956          */
 957         if (zfsvfs->z_replay || uio->uio_resid == start_resid) {
 958                 ZFS_EXIT(zfsvfs);
 959                 return (error);
 960         }
 961 
 962         if (ioflag & (FSYNC | FDSYNC) ||
 963             zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
 964                 zil_commit(zilog, zp->z_id);
 965 
 966         ZFS_EXIT(zfsvfs);
 967         return (0);
 968 }
 969 
 970 #define ZFS_RESERVE_CHUNK (2 * 1024 * 1024)
 971 /* ARGSUSED */
 972 static int
 973 zfs_zero_write(vnode_t *vp, uint64_t size, cred_t *cr, caller_context_t *ct)
 974 {
 975         znode_t         *zp = VTOZ(vp);
 976         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
 977         int             count = 0;
 978         sa_bulk_attr_t  bulk[4];
 979         uint64_t        mtime[2], ctime[2];
 980         rl_t            *rl;
 981         int             error = 0;
 982         dmu_tx_t        *tx = NULL;
 983         uint64_t        end_size;
 984         uint64_t        pos = 0;
 985 
 986         if (zp->z_size > 0)
 987                 return (EFBIG);
 988         if (size == 0)
 989                 return (0);
 990 
 991         ZFS_ENTER(zfsvfs);
 992         ZFS_VERIFY_ZP(zp);
 993 
 994         if (!spa_feature_is_enabled(zfsvfs->z_os->os_spa,
 995             SPA_FEATURE_SPACE_RESERVATION))
 996         {
 997                 ZFS_EXIT(zfsvfs);
 998                 return (ENOTSUP);
 999         }
1000 
1001         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
1002         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
1003         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
1004             &zp->z_size, 8);
1005         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
1006             &zp->z_pflags, 8);
1007 
1008         /*
1009          * If immutable or not appending then return EPERM
1010          */
1011         if ((zp->z_pflags & (ZFS_IMMUTABLE | ZFS_READONLY))) {
1012                 ZFS_EXIT(zfsvfs);
1013                 return (EPERM);
1014         }
1015 
1016         rl = zfs_range_lock(zp, 0, size, RL_WRITER);
1017 
1018         if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
1019             zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
1020                 error = EDQUOT;
1021                 goto out;
1022         }
1023 
1024         while (pos < size) {
1025                 uint64_t length = size - pos;
1026                 length = MIN(length, ZFS_RESERVE_CHUNK);
1027 again:
1028                 tx = dmu_tx_create(zfsvfs->z_os);
1029                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1030                 dmu_tx_hold_write(tx, zp->z_id, pos, length);
1031                 zfs_sa_upgrade_txholds(tx, zp);
1032                 error = dmu_tx_assign(tx, TXG_NOWAIT);
1033                 if (error) {
1034                         if (error == ERESTART) {
1035                                 dmu_tx_wait(tx);
1036                                 dmu_tx_abort(tx);
1037                                 goto again;
1038                         }
1039                         dmu_tx_abort(tx);
1040                         goto out;
1041                 }
1042 
1043                 if (pos == 0)
1044                         zfs_grow_blocksize(zp, MIN(size, zfsvfs->z_max_blksz), tx);
1045                 dmu_write_zero(zfsvfs->z_os, zp->z_id, pos, length, tx);
1046 
1047                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime, B_TRUE);
1048 
1049                 pos += length;
1050                 while ((end_size = zp->z_size) < pos)
1051                         (void) atomic_cas_64(&zp->z_size, end_size, pos);
1052 
1053                 error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1054 
1055                 dmu_tx_commit(tx);
1056                 if (error)
1057                         goto out;
1058         }
1059 out:
1060         zfs_range_unlock(rl);
1061         ZFS_EXIT(zfsvfs);
1062 
1063         return (error);
1064 }
1065 
1066 void
1067 zfs_get_done(zgd_t *zgd, int error)
1068 {
1069         znode_t *zp = zgd->zgd_private;
1070         objset_t *os = zp->z_zfsvfs->z_os;
1071 
1072         if (zgd->zgd_db)
1073                 dmu_buf_rele(zgd->zgd_db, zgd);
1074 
1075         zfs_range_unlock(zgd->zgd_rl);
1076 
1077         /*
1078          * Release the vnode asynchronously as we currently have the
1079          * txg stopped from syncing.
1080          */
1081         VN_RELE_ASYNC(ZTOV(zp), dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1082 
1083         if (error == 0 && zgd->zgd_bp)
1084                 zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
1085 
1086         kmem_free(zgd, sizeof (zgd_t));
1087 }
1088 
1089 #ifdef DEBUG
1090 static int zil_fault_io = 0;
1091 #endif
1092 
1093 /*
1094  * Get data to generate a TX_WRITE intent log record.
1095  */
1096 int
1097 zfs_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
1098 {
1099         zfsvfs_t *zfsvfs = arg;
1100         objset_t *os = zfsvfs->z_os;
1101         znode_t *zp;
1102         uint64_t object = lr->lr_foid;
1103         uint64_t offset = lr->lr_offset;
1104         uint64_t size = lr->lr_length;
1105         blkptr_t *bp = &lr->lr_blkptr;
1106         dmu_buf_t *db;
1107         zgd_t *zgd;
1108         int error = 0;
1109 
1110         ASSERT(zio != NULL);
1111         ASSERT(size != 0);
1112 
1113         /*
1114          * Nothing to do if the file has been removed
1115          */
1116         if (zfs_zget(zfsvfs, object, &zp) != 0)
1117                 return (SET_ERROR(ENOENT));
1118         if (zp->z_unlinked) {
1119                 /*
1120                  * Release the vnode asynchronously as we currently have the
1121                  * txg stopped from syncing.
1122                  */
1123                 VN_RELE_ASYNC(ZTOV(zp),
1124                     dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1125                 return (SET_ERROR(ENOENT));
1126         }
1127 
1128         zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1129         zgd->zgd_zilog = zfsvfs->z_log;
1130         zgd->zgd_private = zp;
1131 
1132         /*
1133          * Write records come in two flavors: immediate and indirect.
1134          * For small writes it's cheaper to store the data with the
1135          * log record (immediate); for large writes it's cheaper to
1136          * sync the data and get a pointer to it (indirect) so that
1137          * we don't have to write the data twice.
1138          */
1139         if (buf != NULL) { /* immediate write */
1140                 zgd->zgd_rl = zfs_range_lock(zp, offset, size, RL_READER);
1141                 /* test for truncation needs to be done while range locked */
1142                 if (offset >= zp->z_size) {
1143                         error = SET_ERROR(ENOENT);
1144                 } else {
1145                         error = dmu_read(os, object, offset, size, buf,
1146                             DMU_READ_NO_PREFETCH);
1147                 }
1148                 ASSERT(error == 0 || error == ENOENT);
1149         } else { /* indirect write */
1150                 /*
1151                  * Have to lock the whole block to ensure when it's
1152                  * written out and it's checksum is being calculated
1153                  * that no one can change the data. We need to re-check
1154                  * blocksize after we get the lock in case it's changed!
1155                  */
1156                 for (;;) {
1157                         uint64_t blkoff;
1158                         size = zp->z_blksz;
1159                         blkoff = ISP2(size) ? P2PHASE(offset, size) : offset;
1160                         offset -= blkoff;
1161                         zgd->zgd_rl = zfs_range_lock(zp, offset, size,
1162                             RL_READER);
1163                         if (zp->z_blksz == size)
1164                                 break;
1165                         offset += blkoff;
1166                         zfs_range_unlock(zgd->zgd_rl);
1167                 }
1168                 /* test for truncation needs to be done while range locked */
1169                 if (lr->lr_offset >= zp->z_size)
1170                         error = SET_ERROR(ENOENT);
1171 #ifdef DEBUG
1172                 if (zil_fault_io) {
1173                         error = SET_ERROR(EIO);
1174                         zil_fault_io = 0;
1175                 }
1176 #endif
1177                 if (error == 0)
1178                         error = dmu_buf_hold(os, object, offset, zgd, &db,
1179                             DMU_READ_NO_PREFETCH);
1180 
1181                 if (error == 0) {
1182                         blkptr_t *obp = dmu_buf_get_blkptr(db);
1183                         if (obp) {
1184                                 ASSERT(BP_IS_HOLE(bp));
1185                                 *bp = *obp;
1186                         }
1187 
1188                         zgd->zgd_db = db;
1189                         zgd->zgd_bp = bp;
1190 
1191                         ASSERT(db->db_offset == offset);
1192                         ASSERT(db->db_size == size);
1193 
1194                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
1195                             zfs_get_done, zgd);
1196                         ASSERT(error || lr->lr_length <= zp->z_blksz);
1197 
1198                         /*
1199                          * On success, we need to wait for the write I/O
1200                          * initiated by dmu_sync() to complete before we can
1201                          * release this dbuf.  We will finish everything up
1202                          * in the zfs_get_done() callback.
1203                          */
1204                         if (error == 0)
1205                                 return (0);
1206 
1207                         if (error == EALREADY) {
1208                                 lr->lr_common.lrc_txtype = TX_WRITE2;
1209                                 error = 0;
1210                         }
1211                 }
1212         }
1213 
1214         zfs_get_done(zgd, error);
1215 
1216         return (error);
1217 }
1218 
1219 /*ARGSUSED*/
1220 static int
1221 zfs_access(vnode_t *vp, int mode, int flag, cred_t *cr,
1222     caller_context_t *ct)
1223 {
1224         znode_t *zp = VTOZ(vp);
1225         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1226         int error;
1227 
1228         ZFS_ENTER(zfsvfs);
1229         ZFS_VERIFY_ZP(zp);
1230 
1231         if (flag & V_ACE_MASK)
1232                 error = zfs_zaccess(zp, mode, flag, B_FALSE, cr);
1233         else
1234                 error = zfs_zaccess_rwx(zp, mode, flag, cr);
1235 
1236         ZFS_EXIT(zfsvfs);
1237         return (error);
1238 }
1239 
1240 /*
1241  * If vnode is for a device return a specfs vnode instead.
1242  */
1243 static int
1244 specvp_check(vnode_t **vpp, cred_t *cr)
1245 {
1246         int error = 0;
1247 
1248         if (IS_DEVVP(*vpp)) {
1249                 struct vnode *svp;
1250 
1251                 svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1252                 VN_RELE(*vpp);
1253                 if (svp == NULL)
1254                         error = SET_ERROR(ENOSYS);
1255                 *vpp = svp;
1256         }
1257         return (error);
1258 }
1259 
1260 
1261 /*
1262  * Lookup an entry in a directory, or an extended attribute directory.
1263  * If it exists, return a held vnode reference for it.
1264  *
1265  *      IN:     dvp     - vnode of directory to search.
1266  *              nm      - name of entry to lookup.
1267  *              pnp     - full pathname to lookup [UNUSED].
1268  *              flags   - LOOKUP_XATTR set if looking for an attribute.
1269  *              rdir    - root directory vnode [UNUSED].
1270  *              cr      - credentials of caller.
1271  *              ct      - caller context
1272  *              direntflags - directory lookup flags
1273  *              realpnp - returned pathname.
1274  *
1275  *      OUT:    vpp     - vnode of located entry, NULL if not found.
1276  *
1277  *      RETURN: 0 on success, error code on failure.
1278  *
1279  * Timestamps:
1280  *      NA
1281  */
1282 /* ARGSUSED */
1283 static int
1284 zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
1285     int flags, vnode_t *rdir, cred_t *cr,  caller_context_t *ct,
1286     int *direntflags, pathname_t *realpnp)
1287 {
1288         znode_t *zdp = VTOZ(dvp);
1289         zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
1290         int     error = 0;
1291 
1292         /* fast path */
1293         if (!(flags & (LOOKUP_XATTR | FIGNORECASE))) {
1294 
1295                 if (dvp->v_type != VDIR) {
1296                         return (SET_ERROR(ENOTDIR));
1297                 } else if (zdp->z_sa_hdl == NULL) {
1298                         return (SET_ERROR(EIO));
1299                 }
1300 
1301                 if (nm[0] == 0 || (nm[0] == '.' && nm[1] == '\0')) {
1302                         error = zfs_fastaccesschk_execute(zdp, cr);
1303                         if (!error) {
1304                                 *vpp = dvp;
1305                                 VN_HOLD(*vpp);
1306                                 return (0);
1307                         }
1308                         return (error);
1309                 } else {
1310                         vnode_t *tvp = dnlc_lookup(dvp, nm);
1311 
1312                         if (tvp) {
1313                                 error = zfs_fastaccesschk_execute(zdp, cr);
1314                                 if (error) {
1315                                         VN_RELE(tvp);
1316                                         return (error);
1317                                 }
1318                                 if (tvp == DNLC_NO_VNODE) {
1319                                         VN_RELE(tvp);
1320                                         return (SET_ERROR(ENOENT));
1321                                 } else {
1322                                         *vpp = tvp;
1323                                         return (specvp_check(vpp, cr));
1324                                 }
1325                         }
1326                 }
1327         }
1328 
1329         DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp, char *, nm);
1330 
1331         ZFS_ENTER(zfsvfs);
1332         ZFS_VERIFY_ZP(zdp);
1333 
1334         *vpp = NULL;
1335 
1336         if (flags & LOOKUP_XATTR) {
1337                 /*
1338                  * If the xattr property is off, refuse the lookup request.
1339                  */
1340                 if (!(zfsvfs->z_vfs->vfs_flag & VFS_XATTR)) {
1341                         ZFS_EXIT(zfsvfs);
1342                         return (SET_ERROR(EINVAL));
1343                 }
1344 
1345                 /*
1346                  * We don't allow recursive attributes..
1347                  * Maybe someday we will.
1348                  */
1349                 if (zdp->z_pflags & ZFS_XATTR) {
1350                         ZFS_EXIT(zfsvfs);
1351                         return (SET_ERROR(EINVAL));
1352                 }
1353 
1354                 if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr, flags)) {
1355                         ZFS_EXIT(zfsvfs);
1356                         return (error);
1357                 }
1358 
1359                 /*
1360                  * Do we have permission to get into attribute directory?
1361                  */
1362 
1363                 if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, 0,
1364                     B_FALSE, cr)) {
1365                         VN_RELE(*vpp);
1366                         *vpp = NULL;
1367                 }
1368 
1369                 ZFS_EXIT(zfsvfs);
1370                 return (error);
1371         }
1372 
1373         if (dvp->v_type != VDIR) {
1374                 ZFS_EXIT(zfsvfs);
1375                 return (SET_ERROR(ENOTDIR));
1376         }
1377 
1378         /*
1379          * Check accessibility of directory.
1380          */
1381 
1382         if (error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr)) {
1383                 ZFS_EXIT(zfsvfs);
1384                 return (error);
1385         }
1386 
1387         if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
1388             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1389                 ZFS_EXIT(zfsvfs);
1390                 return (SET_ERROR(EILSEQ));
1391         }
1392 
1393         error = zfs_dirlook(zdp, nm, vpp, flags, direntflags, realpnp);
1394         if (error == 0)
1395                 error = specvp_check(vpp, cr);
1396 
1397         ZFS_EXIT(zfsvfs);
1398         return (error);
1399 }
1400 
1401 /*
1402  * Attempt to create a new entry in a directory.  If the entry
1403  * already exists, truncate the file if permissible, else return
1404  * an error.  Return the vp of the created or trunc'd file.
1405  *
1406  *      IN:     dvp     - vnode of directory to put new file entry in.
1407  *              name    - name of new file entry.
1408  *              vap     - attributes of new file.
1409  *              excl    - flag indicating exclusive or non-exclusive mode.
1410  *              mode    - mode to open file with.
1411  *              cr      - credentials of caller.
1412  *              flag    - large file flag [UNUSED].
1413  *              ct      - caller context
1414  *              vsecp   - ACL to be set
1415  *
1416  *      OUT:    vpp     - vnode of created or trunc'd entry.
1417  *
1418  *      RETURN: 0 on success, error code on failure.
1419  *
1420  * Timestamps:
1421  *      dvp - ctime|mtime updated if new entry created
1422  *       vp - ctime|mtime always, atime if new
1423  */
1424 
1425 /* ARGSUSED */
1426 static int
1427 zfs_create(vnode_t *dvp, char *name, vattr_t *vap, vcexcl_t excl,
1428     int mode, vnode_t **vpp, cred_t *cr, int flag, caller_context_t *ct,
1429     vsecattr_t *vsecp)
1430 {
1431         znode_t         *zp, *dzp = VTOZ(dvp);
1432         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1433         zilog_t         *zilog;
1434         objset_t        *os;
1435         zfs_dirlock_t   *dl;
1436         dmu_tx_t        *tx;
1437         int             error;
1438         ksid_t          *ksid;
1439         uid_t           uid;
1440         gid_t           gid = crgetgid(cr);
1441         zfs_acl_ids_t   acl_ids;
1442         boolean_t       fuid_dirtied;
1443         boolean_t       have_acl = B_FALSE;
1444         boolean_t       waited = B_FALSE;
1445 
1446         /*
1447          * If we have an ephemeral id, ACL, or XVATTR then
1448          * make sure file system is at proper version
1449          */
1450 
1451         ksid = crgetsid(cr, KSID_OWNER);
1452         if (ksid)
1453                 uid = ksid_getid(ksid);
1454         else
1455                 uid = crgetuid(cr);
1456 
1457         if (zfsvfs->z_use_fuids == B_FALSE &&
1458             (vsecp || (vap->va_mask & AT_XVATTR) ||
1459             IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1460                 return (SET_ERROR(EINVAL));
1461 
1462         ZFS_ENTER(zfsvfs);
1463         ZFS_VERIFY_ZP(dzp);
1464         os = zfsvfs->z_os;
1465         zilog = zfsvfs->z_log;
1466 
1467         if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1468             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1469                 ZFS_EXIT(zfsvfs);
1470                 return (SET_ERROR(EILSEQ));
1471         }
1472 
1473         if (vap->va_mask & AT_XVATTR) {
1474                 if ((error = secpolicy_xvattr((xvattr_t *)vap,
1475                     crgetuid(cr), cr, vap->va_type)) != 0) {
1476                         ZFS_EXIT(zfsvfs);
1477                         return (error);
1478                 }
1479         }
1480 top:
1481         *vpp = NULL;
1482 
1483         if ((vap->va_mode & VSVTX) && secpolicy_vnode_stky_modify(cr))
1484                 vap->va_mode &= ~VSVTX;
1485 
1486         if (*name == '\0') {
1487                 /*
1488                  * Null component name refers to the directory itself.
1489                  */
1490                 VN_HOLD(dvp);
1491                 zp = dzp;
1492                 dl = NULL;
1493                 error = 0;
1494         } else {
1495                 /* possible VN_HOLD(zp) */
1496                 int zflg = 0;
1497 
1498                 if (flag & FIGNORECASE)
1499                         zflg |= ZCILOOK;
1500 
1501                 error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1502                     NULL, NULL);
1503                 if (error) {
1504                         if (have_acl)
1505                                 zfs_acl_ids_free(&acl_ids);
1506                         if (strcmp(name, "..") == 0)
1507                                 error = SET_ERROR(EISDIR);
1508                         ZFS_EXIT(zfsvfs);
1509                         return (error);
1510                 }
1511         }
1512 
1513         if (zp == NULL) {
1514                 uint64_t txtype;
1515 
1516                 /*
1517                  * Create a new file object and update the directory
1518                  * to reference it.
1519                  */
1520                 if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
1521                         if (have_acl)
1522                                 zfs_acl_ids_free(&acl_ids);
1523                         goto out;
1524                 }
1525 
1526                 /*
1527                  * We only support the creation of regular files in
1528                  * extended attribute directories.
1529                  */
1530 
1531                 if ((dzp->z_pflags & ZFS_XATTR) &&
1532                     (vap->va_type != VREG)) {
1533                         if (have_acl)
1534                                 zfs_acl_ids_free(&acl_ids);
1535                         error = SET_ERROR(EINVAL);
1536                         goto out;
1537                 }
1538 
1539                 if (!have_acl && (error = zfs_acl_ids_create(dzp, 0, vap,
1540                     cr, vsecp, &acl_ids)) != 0)
1541                         goto out;
1542                 have_acl = B_TRUE;
1543 
1544                 if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1545                         zfs_acl_ids_free(&acl_ids);
1546                         error = SET_ERROR(EDQUOT);
1547                         goto out;
1548                 }
1549 
1550                 tx = dmu_tx_create(os);
1551 
1552                 dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1553                     ZFS_SA_BASE_ATTR_SIZE);
1554 
1555                 fuid_dirtied = zfsvfs->z_fuid_dirty;
1556                 if (fuid_dirtied)
1557                         zfs_fuid_txhold(zfsvfs, tx);
1558                 dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1559                 dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
1560                 if (!zfsvfs->z_use_sa &&
1561                     acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1562                         dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1563                             0, acl_ids.z_aclp->z_acl_bytes);
1564                 }
1565                 error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
1566                 if (error) {
1567                         zfs_dirent_unlock(dl);
1568                         if (error == ERESTART) {
1569                                 waited = B_TRUE;
1570                                 dmu_tx_wait(tx);
1571                                 dmu_tx_abort(tx);
1572                                 goto top;
1573                         }
1574                         zfs_acl_ids_free(&acl_ids);
1575                         dmu_tx_abort(tx);
1576                         ZFS_EXIT(zfsvfs);
1577                         return (error);
1578                 }
1579                 zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1580 
1581                 if (fuid_dirtied)
1582                         zfs_fuid_sync(zfsvfs, tx);
1583 
1584                 (void) zfs_link_create(dl, zp, tx, ZNEW);
1585                 txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1586                 if (flag & FIGNORECASE)
1587                         txtype |= TX_CI;
1588                 zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1589                     vsecp, acl_ids.z_fuidp, vap);
1590                 zfs_acl_ids_free(&acl_ids);
1591                 dmu_tx_commit(tx);
1592         } else {
1593                 int aflags = (flag & FAPPEND) ? V_APPEND : 0;
1594 
1595                 if (have_acl)
1596                         zfs_acl_ids_free(&acl_ids);
1597                 have_acl = B_FALSE;
1598 
1599                 /*
1600                  * A directory entry already exists for this name.
1601                  */
1602                 /*
1603                  * Can't truncate an existing file if in exclusive mode.
1604                  */
1605                 if (excl == EXCL) {
1606                         error = SET_ERROR(EEXIST);
1607                         goto out;
1608                 }
1609                 /*
1610                  * Can't open a directory for writing.
1611                  */
1612                 if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1613                         error = SET_ERROR(EISDIR);
1614                         goto out;
1615                 }
1616                 /*
1617                  * Verify requested access to file.
1618                  */
1619                 if (mode && (error = zfs_zaccess_rwx(zp, mode, aflags, cr))) {
1620                         goto out;
1621                 }
1622 
1623                 mutex_enter(&dzp->z_lock);
1624                 dzp->z_seq++;
1625                 mutex_exit(&dzp->z_lock);
1626 
1627                 /*
1628                  * Truncate regular files if requested.
1629                  */
1630                 if ((ZTOV(zp)->v_type == VREG) &&
1631                     (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1632                         /* we can't hold any locks when calling zfs_freesp() */
1633                         zfs_dirent_unlock(dl);
1634                         dl = NULL;
1635                         error = zfs_freesp(zp, 0, 0, mode, TRUE);
1636                         if (error == 0) {
1637                                 vnevent_create(ZTOV(zp), ct);
1638                         }
1639                 }
1640         }
1641 out:
1642 
1643         if (dl)
1644                 zfs_dirent_unlock(dl);
1645 
1646         if (error) {
1647                 if (zp)
1648                         VN_RELE(ZTOV(zp));
1649         } else {
1650                 *vpp = ZTOV(zp);
1651                 error = specvp_check(vpp, cr);
1652         }
1653 
1654         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1655                 zil_commit(zilog, 0);
1656 
1657         ZFS_EXIT(zfsvfs);
1658         return (error);
1659 }
1660 
1661 /*
1662  * Remove an entry from a directory.
1663  *
1664  *      IN:     dvp     - vnode of directory to remove entry from.
1665  *              name    - name of entry to remove.
1666  *              cr      - credentials of caller.
1667  *              ct      - caller context
1668  *              flags   - case flags
1669  *
1670  *      RETURN: 0 on success, error code on failure.
1671  *
1672  * Timestamps:
1673  *      dvp - ctime|mtime
1674  *       vp - ctime (if nlink > 0)
1675  */
1676 
1677 uint64_t null_xattr = 0;
1678 
1679 /*ARGSUSED*/
1680 static int
1681 zfs_remove(vnode_t *dvp, char *name, cred_t *cr, caller_context_t *ct,
1682     int flags)
1683 {
1684         znode_t         *zp, *dzp = VTOZ(dvp);
1685         znode_t         *xzp;
1686         vnode_t         *vp;
1687         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1688         zilog_t         *zilog;
1689         uint64_t        acl_obj, xattr_obj;
1690         uint64_t        xattr_obj_unlinked = 0;
1691         uint64_t        obj = 0;
1692         zfs_dirlock_t   *dl;
1693         dmu_tx_t        *tx;
1694         boolean_t       may_delete_now, delete_now = FALSE;
1695         boolean_t       unlinked, toobig = FALSE;
1696         uint64_t        txtype;
1697         pathname_t      *realnmp = NULL;
1698         pathname_t      realnm;
1699         int             error;
1700         int             zflg = ZEXISTS;
1701         boolean_t       waited = B_FALSE;
1702 
1703         ZFS_ENTER(zfsvfs);
1704         ZFS_VERIFY_ZP(dzp);
1705         zilog = zfsvfs->z_log;
1706 
1707         if (flags & FIGNORECASE) {
1708                 zflg |= ZCILOOK;
1709                 pn_alloc(&realnm);
1710                 realnmp = &realnm;
1711         }
1712 
1713 top:
1714         xattr_obj = 0;
1715         xzp = NULL;
1716         /*
1717          * Attempt to lock directory; fail if entry doesn't exist.
1718          */
1719         if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1720             NULL, realnmp)) {
1721                 if (realnmp)
1722                         pn_free(realnmp);
1723                 ZFS_EXIT(zfsvfs);
1724                 return (error);
1725         }
1726 
1727         vp = ZTOV(zp);
1728 
1729         if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1730                 goto out;
1731         }
1732 
1733         /*
1734          * Need to use rmdir for removing directories.
1735          */
1736         if (vp->v_type == VDIR) {
1737                 error = SET_ERROR(EPERM);
1738                 goto out;
1739         }
1740 
1741         vnevent_remove(vp, dvp, name, ct);
1742 
1743         if (realnmp)
1744                 dnlc_remove(dvp, realnmp->pn_buf);
1745         else
1746                 dnlc_remove(dvp, name);
1747 
1748         mutex_enter(&vp->v_lock);
1749         may_delete_now = vp->v_count == 1 && !vn_has_cached_data(vp);
1750         mutex_exit(&vp->v_lock);
1751 
1752         /*
1753          * We may delete the znode now, or we may put it in the unlinked set;
1754          * it depends on whether we're the last link, and on whether there are
1755          * other holds on the vnode.  So we dmu_tx_hold() the right things to
1756          * allow for either case.
1757          */
1758         obj = zp->z_id;
1759         tx = dmu_tx_create(zfsvfs->z_os);
1760         dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1761         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1762         zfs_sa_upgrade_txholds(tx, zp);
1763         zfs_sa_upgrade_txholds(tx, dzp);
1764         if (may_delete_now) {
1765                 toobig =
1766                     zp->z_size > zp->z_blksz * DMU_MAX_DELETEBLKCNT;
1767                 /* if the file is too big, only hold_free a token amount */
1768                 dmu_tx_hold_free(tx, zp->z_id, 0,
1769                     (toobig ? DMU_MAX_ACCESS : DMU_OBJECT_END));
1770         }
1771 
1772         /* are there any extended attributes? */
1773         error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1774             &xattr_obj, sizeof (xattr_obj));
1775         if (error == 0 && xattr_obj) {
1776                 error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1777                 ASSERT0(error);
1778                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1779                 dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1780         }
1781 
1782         mutex_enter(&zp->z_lock);
1783         if ((acl_obj = zfs_external_acl(zp)) != 0 && may_delete_now)
1784                 dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1785         mutex_exit(&zp->z_lock);
1786 
1787         /* charge as an update -- would be nice not to charge at all */
1788         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1789 
1790         /*
1791          * Mark this transaction as typically resulting in a net free of
1792          * space, unless object removal will be delayed indefinitely
1793          * (due to active holds on the vnode due to the file being open).
1794          */
1795         if (may_delete_now)
1796                 dmu_tx_mark_netfree(tx);
1797 
1798         error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
1799         if (error) {
1800                 zfs_dirent_unlock(dl);
1801                 VN_RELE(vp);
1802                 if (xzp)
1803                         VN_RELE(ZTOV(xzp));
1804                 if (error == ERESTART) {
1805                         waited = B_TRUE;
1806                         dmu_tx_wait(tx);
1807                         dmu_tx_abort(tx);
1808                         goto top;
1809                 }
1810                 if (realnmp)
1811                         pn_free(realnmp);
1812                 dmu_tx_abort(tx);
1813                 ZFS_EXIT(zfsvfs);
1814                 return (error);
1815         }
1816 
1817         /*
1818          * Remove the directory entry.
1819          */
1820         error = zfs_link_destroy(dl, zp, tx, zflg, &unlinked);
1821 
1822         if (error) {
1823                 dmu_tx_commit(tx);
1824                 goto out;
1825         }
1826 
1827         if (unlinked) {
1828                 /*
1829                  * Hold z_lock so that we can make sure that the ACL obj
1830                  * hasn't changed.  Could have been deleted due to
1831                  * zfs_sa_upgrade().
1832                  */
1833                 mutex_enter(&zp->z_lock);
1834                 mutex_enter(&vp->v_lock);
1835                 (void) sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1836                     &xattr_obj_unlinked, sizeof (xattr_obj_unlinked));
1837                 delete_now = may_delete_now && !toobig &&
1838                     vp->v_count == 1 && !vn_has_cached_data(vp) &&
1839                     xattr_obj == xattr_obj_unlinked && zfs_external_acl(zp) ==
1840                     acl_obj;
1841                 mutex_exit(&vp->v_lock);
1842         }
1843 
1844         if (delete_now) {
1845                 if (xattr_obj_unlinked) {
1846                         ASSERT3U(xzp->z_links, ==, 2);
1847                         mutex_enter(&xzp->z_lock);
1848                         xzp->z_unlinked = 1;
1849                         xzp->z_links = 0;
1850                         error = sa_update(xzp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
1851                             &xzp->z_links, sizeof (xzp->z_links), tx);
1852                         ASSERT3U(error,  ==,  0);
1853                         mutex_exit(&xzp->z_lock);
1854                         zfs_unlinked_add(xzp, tx);
1855 
1856                         if (zp->z_is_sa)
1857                                 error = sa_remove(zp->z_sa_hdl,
1858                                     SA_ZPL_XATTR(zfsvfs), tx);
1859                         else
1860                                 error = sa_update(zp->z_sa_hdl,
1861                                     SA_ZPL_XATTR(zfsvfs), &null_xattr,
1862                                     sizeof (uint64_t), tx);
1863                         ASSERT0(error);
1864                 }
1865                 mutex_enter(&vp->v_lock);
1866                 vp->v_count--;
1867                 ASSERT0(vp->v_count);
1868                 mutex_exit(&vp->v_lock);
1869                 mutex_exit(&zp->z_lock);
1870                 zfs_znode_delete(zp, tx);
1871         } else if (unlinked) {
1872                 mutex_exit(&zp->z_lock);
1873                 zfs_unlinked_add(zp, tx);
1874         }
1875 
1876         txtype = TX_REMOVE;
1877         if (flags & FIGNORECASE)
1878                 txtype |= TX_CI;
1879         zfs_log_remove(zilog, tx, txtype, dzp, name, obj);
1880 
1881         dmu_tx_commit(tx);
1882 out:
1883         if (realnmp)
1884                 pn_free(realnmp);
1885 
1886         zfs_dirent_unlock(dl);
1887 
1888         if (!delete_now)
1889                 VN_RELE(vp);
1890         if (xzp)
1891                 VN_RELE(ZTOV(xzp));
1892 
1893         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1894                 zil_commit(zilog, 0);
1895 
1896         ZFS_EXIT(zfsvfs);
1897         return (error);
1898 }
1899 
1900 /*
1901  * Create a new directory and insert it into dvp using the name
1902  * provided.  Return a pointer to the inserted directory.
1903  *
1904  *      IN:     dvp     - vnode of directory to add subdir to.
1905  *              dirname - name of new directory.
1906  *              vap     - attributes of new directory.
1907  *              cr      - credentials of caller.
1908  *              ct      - caller context
1909  *              flags   - case flags
1910  *              vsecp   - ACL to be set
1911  *
1912  *      OUT:    vpp     - vnode of created directory.
1913  *
1914  *      RETURN: 0 on success, error code on failure.
1915  *
1916  * Timestamps:
1917  *      dvp - ctime|mtime updated
1918  *       vp - ctime|mtime|atime updated
1919  */
1920 /*ARGSUSED*/
1921 static int
1922 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr,
1923     caller_context_t *ct, int flags, vsecattr_t *vsecp)
1924 {
1925         znode_t         *zp, *dzp = VTOZ(dvp);
1926         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1927         zilog_t         *zilog;
1928         zfs_dirlock_t   *dl;
1929         uint64_t        txtype;
1930         dmu_tx_t        *tx;
1931         int             error;
1932         int             zf = ZNEW;
1933         ksid_t          *ksid;
1934         uid_t           uid;
1935         gid_t           gid = crgetgid(cr);
1936         zfs_acl_ids_t   acl_ids;
1937         boolean_t       fuid_dirtied;
1938         boolean_t       waited = B_FALSE;
1939 
1940         ASSERT(vap->va_type == VDIR);
1941 
1942         /*
1943          * If we have an ephemeral id, ACL, or XVATTR then
1944          * make sure file system is at proper version
1945          */
1946 
1947         ksid = crgetsid(cr, KSID_OWNER);
1948         if (ksid)
1949                 uid = ksid_getid(ksid);
1950         else
1951                 uid = crgetuid(cr);
1952         if (zfsvfs->z_use_fuids == B_FALSE &&
1953             (vsecp || (vap->va_mask & AT_XVATTR) ||
1954             IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1955                 return (SET_ERROR(EINVAL));
1956 
1957         ZFS_ENTER(zfsvfs);
1958         ZFS_VERIFY_ZP(dzp);
1959         zilog = zfsvfs->z_log;
1960 
1961         if (dzp->z_pflags & ZFS_XATTR) {
1962                 ZFS_EXIT(zfsvfs);
1963                 return (SET_ERROR(EINVAL));
1964         }
1965 
1966         if (zfsvfs->z_utf8 && u8_validate(dirname,
1967             strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1968                 ZFS_EXIT(zfsvfs);
1969                 return (SET_ERROR(EILSEQ));
1970         }
1971         if (flags & FIGNORECASE)
1972                 zf |= ZCILOOK;
1973 
1974         if (vap->va_mask & AT_XVATTR) {
1975                 if ((error = secpolicy_xvattr((xvattr_t *)vap,
1976                     crgetuid(cr), cr, vap->va_type)) != 0) {
1977                         ZFS_EXIT(zfsvfs);
1978                         return (error);
1979                 }
1980         }
1981 
1982         if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
1983             vsecp, &acl_ids)) != 0) {
1984                 ZFS_EXIT(zfsvfs);
1985                 return (error);
1986         }
1987         /*
1988          * First make sure the new directory doesn't exist.
1989          *
1990          * Existence is checked first to make sure we don't return
1991          * EACCES instead of EEXIST which can cause some applications
1992          * to fail.
1993          */
1994 top:
1995         *vpp = NULL;
1996 
1997         if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, zf,
1998             NULL, NULL)) {
1999                 zfs_acl_ids_free(&acl_ids);
2000                 ZFS_EXIT(zfsvfs);
2001                 return (error);
2002         }
2003 
2004         if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr)) {
2005                 zfs_acl_ids_free(&acl_ids);
2006                 zfs_dirent_unlock(dl);
2007                 ZFS_EXIT(zfsvfs);
2008                 return (error);
2009         }
2010 
2011         if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
2012                 zfs_acl_ids_free(&acl_ids);
2013                 zfs_dirent_unlock(dl);
2014                 ZFS_EXIT(zfsvfs);
2015                 return (SET_ERROR(EDQUOT));
2016         }
2017 
2018         /*
2019          * Add a new entry to the directory.
2020          */
2021         tx = dmu_tx_create(zfsvfs->z_os);
2022         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
2023         dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
2024         fuid_dirtied = zfsvfs->z_fuid_dirty;
2025         if (fuid_dirtied)
2026                 zfs_fuid_txhold(zfsvfs, tx);
2027         if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
2028                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
2029                     acl_ids.z_aclp->z_acl_bytes);
2030         }
2031 
2032         dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
2033             ZFS_SA_BASE_ATTR_SIZE);
2034 
2035         error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
2036         if (error) {
2037                 zfs_dirent_unlock(dl);
2038                 if (error == ERESTART) {
2039                         waited = B_TRUE;
2040                         dmu_tx_wait(tx);
2041                         dmu_tx_abort(tx);
2042                         goto top;
2043                 }
2044                 zfs_acl_ids_free(&acl_ids);
2045                 dmu_tx_abort(tx);
2046                 ZFS_EXIT(zfsvfs);
2047                 return (error);
2048         }
2049 
2050         /*
2051          * Create new node.
2052          */
2053         zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
2054 
2055         if (fuid_dirtied)
2056                 zfs_fuid_sync(zfsvfs, tx);
2057 
2058         /*
2059          * Now put new name in parent dir.
2060          */
2061         (void) zfs_link_create(dl, zp, tx, ZNEW);
2062 
2063         *vpp = ZTOV(zp);
2064 
2065         txtype = zfs_log_create_txtype(Z_DIR, vsecp, vap);
2066         if (flags & FIGNORECASE)
2067                 txtype |= TX_CI;
2068         zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, vsecp,
2069             acl_ids.z_fuidp, vap);
2070 
2071         zfs_acl_ids_free(&acl_ids);
2072 
2073         dmu_tx_commit(tx);
2074 
2075         zfs_dirent_unlock(dl);
2076 
2077         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2078                 zil_commit(zilog, 0);
2079 
2080         ZFS_EXIT(zfsvfs);
2081         return (0);
2082 }
2083 
2084 /*
2085  * Remove a directory subdir entry.  If the current working
2086  * directory is the same as the subdir to be removed, the
2087  * remove will fail.
2088  *
2089  *      IN:     dvp     - vnode of directory to remove from.
2090  *              name    - name of directory to be removed.
2091  *              cwd     - vnode of current working directory.
2092  *              cr      - credentials of caller.
2093  *              ct      - caller context
2094  *              flags   - case flags
2095  *
2096  *      RETURN: 0 on success, error code on failure.
2097  *
2098  * Timestamps:
2099  *      dvp - ctime|mtime updated
2100  */
2101 /*ARGSUSED*/
2102 static int
2103 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr,
2104     caller_context_t *ct, int flags)
2105 {
2106         znode_t         *dzp = VTOZ(dvp);
2107         znode_t         *zp;
2108         vnode_t         *vp;
2109         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
2110         zilog_t         *zilog;
2111         zfs_dirlock_t   *dl;
2112         dmu_tx_t        *tx;
2113         int             error;
2114         int             zflg = ZEXISTS;
2115         boolean_t       waited = B_FALSE;
2116 
2117         ZFS_ENTER(zfsvfs);
2118         ZFS_VERIFY_ZP(dzp);
2119         zilog = zfsvfs->z_log;
2120 
2121         if (flags & FIGNORECASE)
2122                 zflg |= ZCILOOK;
2123 top:
2124         zp = NULL;
2125 
2126         /*
2127          * Attempt to lock directory; fail if entry doesn't exist.
2128          */
2129         if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
2130             NULL, NULL)) {
2131                 ZFS_EXIT(zfsvfs);
2132                 return (error);
2133         }
2134 
2135         vp = ZTOV(zp);
2136 
2137         if (error = zfs_zaccess_delete(dzp, zp, cr)) {
2138                 goto out;
2139         }
2140 
2141         if (vp->v_type != VDIR) {
2142                 error = SET_ERROR(ENOTDIR);
2143                 goto out;
2144         }
2145 
2146         if (vp == cwd) {
2147                 error = SET_ERROR(EINVAL);
2148                 goto out;
2149         }
2150 
2151         vnevent_rmdir(vp, dvp, name, ct);
2152 
2153         /*
2154          * Grab a lock on the directory to make sure that noone is
2155          * trying to add (or lookup) entries while we are removing it.
2156          */
2157         rw_enter(&zp->z_name_lock, RW_WRITER);
2158 
2159         /*
2160          * Grab a lock on the parent pointer to make sure we play well
2161          * with the treewalk and directory rename code.
2162          */
2163         rw_enter(&zp->z_parent_lock, RW_WRITER);
2164 
2165         tx = dmu_tx_create(zfsvfs->z_os);
2166         dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
2167         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2168         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
2169         zfs_sa_upgrade_txholds(tx, zp);
2170         zfs_sa_upgrade_txholds(tx, dzp);
2171         error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
2172         if (error) {
2173                 rw_exit(&zp->z_parent_lock);
2174                 rw_exit(&zp->z_name_lock);
2175                 zfs_dirent_unlock(dl);
2176                 VN_RELE(vp);
2177                 if (error == ERESTART) {
2178                         waited = B_TRUE;
2179                         dmu_tx_wait(tx);
2180                         dmu_tx_abort(tx);
2181                         goto top;
2182                 }
2183                 dmu_tx_abort(tx);
2184                 ZFS_EXIT(zfsvfs);
2185                 return (error);
2186         }
2187 
2188         error = zfs_link_destroy(dl, zp, tx, zflg, NULL);
2189 
2190         if (error == 0) {
2191                 uint64_t txtype = TX_RMDIR;
2192                 if (flags & FIGNORECASE)
2193                         txtype |= TX_CI;
2194                 zfs_log_remove(zilog, tx, txtype, dzp, name, ZFS_NO_OBJECT);
2195         }
2196 
2197         dmu_tx_commit(tx);
2198 
2199         rw_exit(&zp->z_parent_lock);
2200         rw_exit(&zp->z_name_lock);
2201 out:
2202         zfs_dirent_unlock(dl);
2203 
2204         VN_RELE(vp);
2205 
2206         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2207                 zil_commit(zilog, 0);
2208 
2209         ZFS_EXIT(zfsvfs);
2210         return (error);
2211 }
2212 
2213 /*
2214  * Read as many directory entries as will fit into the provided
2215  * buffer from the given directory cursor position (specified in
2216  * the uio structure).
2217  *
2218  *      IN:     vp      - vnode of directory to read.
2219  *              uio     - structure supplying read location, range info,
2220  *                        and return buffer.
2221  *              cr      - credentials of caller.
2222  *              ct      - caller context
2223  *              flags   - case flags
2224  *
2225  *      OUT:    uio     - updated offset and range, buffer filled.
2226  *              eofp    - set to true if end-of-file detected.
2227  *
2228  *      RETURN: 0 on success, error code on failure.
2229  *
2230  * Timestamps:
2231  *      vp - atime updated
2232  *
2233  * Note that the low 4 bits of the cookie returned by zap is always zero.
2234  * This allows us to use the low range for "special" directory entries:
2235  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
2236  * we use the offset 2 for the '.zfs' directory.
2237  */
2238 /* ARGSUSED */
2239 static int
2240 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp,
2241     caller_context_t *ct, int flags)
2242 {
2243         znode_t         *zp = VTOZ(vp);
2244         iovec_t         *iovp;
2245         edirent_t       *eodp;
2246         dirent64_t      *odp;
2247         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
2248         objset_t        *os;
2249         caddr_t         outbuf;
2250         size_t          bufsize;
2251         zap_cursor_t    zc;
2252         zap_attribute_t zap;
2253         uint_t          bytes_wanted;
2254         uint64_t        offset; /* must be unsigned; checks for < 1 */
2255         uint64_t        parent;
2256         int             local_eof;
2257         int             outcount;
2258         int             error;
2259         uint8_t         prefetch;
2260         boolean_t       check_sysattrs;
2261 
2262         ZFS_ENTER(zfsvfs);
2263         ZFS_VERIFY_ZP(zp);
2264 
2265         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
2266             &parent, sizeof (parent))) != 0) {
2267                 ZFS_EXIT(zfsvfs);
2268                 return (error);
2269         }
2270 
2271         /*
2272          * If we are not given an eof variable,
2273          * use a local one.
2274          */
2275         if (eofp == NULL)
2276                 eofp = &local_eof;
2277 
2278         /*
2279          * Check for valid iov_len.
2280          */
2281         if (uio->uio_iov->iov_len <= 0) {
2282                 ZFS_EXIT(zfsvfs);
2283                 return (SET_ERROR(EINVAL));
2284         }
2285 
2286         /*
2287          * Quit if directory has been removed (posix)
2288          */
2289         if ((*eofp = zp->z_unlinked) != 0) {
2290                 ZFS_EXIT(zfsvfs);
2291                 return (0);
2292         }
2293 
2294         error = 0;
2295         os = zfsvfs->z_os;
2296         offset = uio->uio_loffset;
2297         prefetch = zp->z_zn_prefetch;
2298 
2299         /*
2300          * Initialize the iterator cursor.
2301          */
2302         if (offset <= 3) {
2303                 /*
2304                  * Start iteration from the beginning of the directory.
2305                  */
2306                 zap_cursor_init(&zc, os, zp->z_id);
2307         } else {
2308                 /*
2309                  * The offset is a serialized cursor.
2310                  */
2311                 zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
2312         }
2313 
2314         /*
2315          * Get space to change directory entries into fs independent format.
2316          */
2317         iovp = uio->uio_iov;
2318         bytes_wanted = iovp->iov_len;
2319         if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
2320                 bufsize = bytes_wanted;
2321                 outbuf = kmem_alloc(bufsize, KM_SLEEP);
2322                 odp = (struct dirent64 *)outbuf;
2323         } else {
2324                 bufsize = bytes_wanted;
2325                 outbuf = NULL;
2326                 odp = (struct dirent64 *)iovp->iov_base;
2327         }
2328         eodp = (struct edirent *)odp;
2329 
2330         /*
2331          * If this VFS supports the system attribute view interface; and
2332          * we're looking at an extended attribute directory; and we care
2333          * about normalization conflicts on this vfs; then we must check
2334          * for normalization conflicts with the sysattr name space.
2335          */
2336         check_sysattrs = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
2337             (vp->v_flag & V_XATTRDIR) && zfsvfs->z_norm &&
2338             (flags & V_RDDIR_ENTFLAGS);
2339 
2340         /*
2341          * Transform to file-system independent format
2342          */
2343         outcount = 0;
2344         while (outcount < bytes_wanted) {
2345                 ino64_t objnum;
2346                 ushort_t reclen;
2347                 off64_t *next = NULL;
2348 
2349                 /*
2350                  * Special case `.', `..', and `.zfs'.
2351                  */
2352                 if (offset == 0) {
2353                         (void) strcpy(zap.za_name, ".");
2354                         zap.za_normalization_conflict = 0;
2355                         objnum = zp->z_id;
2356                 } else if (offset == 1) {
2357                         (void) strcpy(zap.za_name, "..");
2358                         zap.za_normalization_conflict = 0;
2359                         objnum = parent;
2360                 } else if (offset == 2 && zfs_show_ctldir(zp)) {
2361                         (void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
2362                         zap.za_normalization_conflict = 0;
2363                         objnum = ZFSCTL_INO_ROOT;
2364                 } else {
2365                         /*
2366                          * Grab next entry.
2367                          */
2368                         if (error = zap_cursor_retrieve(&zc, &zap)) {
2369                                 if ((*eofp = (error == ENOENT)) != 0)
2370                                         break;
2371                                 else
2372                                         goto update;
2373                         }
2374 
2375                         if (zap.za_integer_length != 8 ||
2376                             zap.za_num_integers != 1) {
2377                                 cmn_err(CE_WARN, "zap_readdir: bad directory "
2378                                     "entry, obj = %lld, offset = %lld\n",
2379                                     (u_longlong_t)zp->z_id,
2380                                     (u_longlong_t)offset);
2381                                 error = SET_ERROR(ENXIO);
2382                                 goto update;
2383                         }
2384 
2385                         objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
2386                         /*
2387                          * MacOS X can extract the object type here such as:
2388                          * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2389                          */
2390 
2391                         if (check_sysattrs && !zap.za_normalization_conflict) {
2392                                 zap.za_normalization_conflict =
2393                                     xattr_sysattr_casechk(zap.za_name);
2394                         }
2395                 }
2396 
2397                 if (flags & V_RDDIR_ACCFILTER) {
2398                         /*
2399                          * If we have no access at all, don't include
2400                          * this entry in the returned information
2401                          */
2402                         znode_t *ezp;
2403                         if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
2404                                 goto skip_entry;
2405                         if (!zfs_has_access(ezp, cr)) {
2406                                 VN_RELE(ZTOV(ezp));
2407                                 goto skip_entry;
2408                         }
2409                         VN_RELE(ZTOV(ezp));
2410                 }
2411 
2412                 if (flags & V_RDDIR_ENTFLAGS)
2413                         reclen = EDIRENT_RECLEN(strlen(zap.za_name));
2414                 else
2415                         reclen = DIRENT64_RECLEN(strlen(zap.za_name));
2416 
2417                 /*
2418                  * Will this entry fit in the buffer?
2419                  */
2420                 if (outcount + reclen > bufsize) {
2421                         /*
2422                          * Did we manage to fit anything in the buffer?
2423                          */
2424                         if (!outcount) {
2425                                 error = SET_ERROR(EINVAL);
2426                                 goto update;
2427                         }
2428                         break;
2429                 }
2430                 if (flags & V_RDDIR_ENTFLAGS) {
2431                         /*
2432                          * Add extended flag entry:
2433                          */
2434                         eodp->ed_ino = objnum;
2435                         eodp->ed_reclen = reclen;
2436                         /* NOTE: ed_off is the offset for the *next* entry */
2437                         next = &(eodp->ed_off);
2438                         eodp->ed_eflags = zap.za_normalization_conflict ?
2439                             ED_CASE_CONFLICT : 0;
2440                         (void) strncpy(eodp->ed_name, zap.za_name,
2441                             EDIRENT_NAMELEN(reclen));
2442                         eodp = (edirent_t *)((intptr_t)eodp + reclen);
2443                 } else {
2444                         /*
2445                          * Add normal entry:
2446                          */
2447                         odp->d_ino = objnum;
2448                         odp->d_reclen = reclen;
2449                         /* NOTE: d_off is the offset for the *next* entry */
2450                         next = &(odp->d_off);
2451                         (void) strncpy(odp->d_name, zap.za_name,
2452                             DIRENT64_NAMELEN(reclen));
2453                         odp = (dirent64_t *)((intptr_t)odp + reclen);
2454                 }
2455                 outcount += reclen;
2456 
2457                 ASSERT(outcount <= bufsize);
2458 
2459                 /* Prefetch znode */
2460                 if (prefetch)
2461                         dmu_prefetch(os, objnum, 0, 0);
2462 
2463         skip_entry:
2464                 /*
2465                  * Move to the next entry, fill in the previous offset.
2466                  */
2467                 if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
2468                         zap_cursor_advance(&zc);
2469                         offset = zap_cursor_serialize(&zc);
2470                 } else {
2471                         offset += 1;
2472                 }
2473                 if (next)
2474                         *next = offset;
2475         }
2476         zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
2477 
2478         if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
2479                 iovp->iov_base += outcount;
2480                 iovp->iov_len -= outcount;
2481                 uio->uio_resid -= outcount;
2482         } else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
2483                 /*
2484                  * Reset the pointer.
2485                  */
2486                 offset = uio->uio_loffset;
2487         }
2488 
2489 update:
2490         zap_cursor_fini(&zc);
2491         if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
2492                 kmem_free(outbuf, bufsize);
2493 
2494         if (error == ENOENT)
2495                 error = 0;
2496 
2497         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2498 
2499         uio->uio_loffset = offset;
2500         ZFS_EXIT(zfsvfs);
2501         return (error);
2502 }
2503 
2504 ulong_t zfs_fsync_sync_cnt = 4;
2505 
2506 static int
2507 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
2508 {
2509         znode_t *zp = VTOZ(vp);
2510         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2511 
2512         /*
2513          * Regardless of whether this is required for standards conformance,
2514          * this is the logical behavior when fsync() is called on a file with
2515          * dirty pages.  We use B_ASYNC since the ZIL transactions are already
2516          * going to be pushed out as part of the zil_commit().
2517          */
2518         if (vn_has_cached_data(vp) && !(syncflag & FNODSYNC) &&
2519             (vp->v_type == VREG) && !(IS_SWAPVP(vp)))
2520                 (void) VOP_PUTPAGE(vp, (offset_t)0, (size_t)0, B_ASYNC, cr, ct);
2521 
2522         (void) tsd_set(zfs_fsyncer_key, (void *)zfs_fsync_sync_cnt);
2523 
2524         if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) {
2525                 ZFS_ENTER(zfsvfs);
2526                 ZFS_VERIFY_ZP(zp);
2527                 zil_commit(zfsvfs->z_log, zp->z_id);
2528                 ZFS_EXIT(zfsvfs);
2529         }
2530         return (0);
2531 }
2532 
2533 
2534 /*
2535  * Get the requested file attributes and place them in the provided
2536  * vattr structure.
2537  *
2538  *      IN:     vp      - vnode of file.
2539  *              vap     - va_mask identifies requested attributes.
2540  *                        If AT_XVATTR set, then optional attrs are requested
2541  *              flags   - ATTR_NOACLCHECK (CIFS server context)
2542  *              cr      - credentials of caller.
2543  *              ct      - caller context
2544  *
2545  *      OUT:    vap     - attribute values.
2546  *
2547  *      RETURN: 0 (always succeeds).
2548  */
2549 /* ARGSUSED */
2550 static int
2551 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2552     caller_context_t *ct)
2553 {
2554         znode_t *zp = VTOZ(vp);
2555         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2556         int     error = 0;
2557         uint64_t links;
2558         uint64_t mtime[2], ctime[2];
2559         xvattr_t *xvap = (xvattr_t *)vap;       /* vap may be an xvattr_t * */
2560         xoptattr_t *xoap = NULL;
2561         boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2562         sa_bulk_attr_t bulk[2];
2563         int count = 0;
2564 
2565         ZFS_ENTER(zfsvfs);
2566         ZFS_VERIFY_ZP(zp);
2567 
2568         zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
2569 
2570         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
2571         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
2572 
2573         if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
2574                 ZFS_EXIT(zfsvfs);
2575                 return (error);
2576         }
2577 
2578         /*
2579          * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2580          * Also, if we are the owner don't bother, since owner should
2581          * always be allowed to read basic attributes of file.
2582          */
2583         if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
2584             (vap->va_uid != crgetuid(cr))) {
2585                 if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2586                     skipaclchk, cr)) {
2587                         ZFS_EXIT(zfsvfs);
2588                         return (error);
2589                 }
2590         }
2591 
2592         /*
2593          * Return all attributes.  It's cheaper to provide the answer
2594          * than to determine whether we were asked the question.
2595          */
2596 
2597         mutex_enter(&zp->z_lock);
2598         vap->va_type = vp->v_type;
2599         vap->va_mode = zp->z_mode & MODEMASK;
2600         vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
2601         vap->va_nodeid = zp->z_id;
2602         if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp))
2603                 links = zp->z_links + 1;
2604         else
2605                 links = zp->z_links;
2606         vap->va_nlink = MIN(links, UINT32_MAX);      /* nlink_t limit! */
2607         vap->va_size = zp->z_size;
2608         vap->va_rdev = vp->v_rdev;
2609         vap->va_seq = zp->z_seq;
2610 
2611         /*
2612          * Add in any requested optional attributes and the create time.
2613          * Also set the corresponding bits in the returned attribute bitmap.
2614          */
2615         if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2616                 if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2617                         xoap->xoa_archive =
2618                             ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2619                         XVA_SET_RTN(xvap, XAT_ARCHIVE);
2620                 }
2621 
2622                 if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2623                         xoap->xoa_readonly =
2624                             ((zp->z_pflags & ZFS_READONLY) != 0);
2625                         XVA_SET_RTN(xvap, XAT_READONLY);
2626                 }
2627 
2628                 if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2629                         xoap->xoa_system =
2630                             ((zp->z_pflags & ZFS_SYSTEM) != 0);
2631                         XVA_SET_RTN(xvap, XAT_SYSTEM);
2632                 }
2633 
2634                 if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2635                         xoap->xoa_hidden =
2636                             ((zp->z_pflags & ZFS_HIDDEN) != 0);
2637                         XVA_SET_RTN(xvap, XAT_HIDDEN);
2638                 }
2639 
2640                 if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2641                         xoap->xoa_nounlink =
2642                             ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2643                         XVA_SET_RTN(xvap, XAT_NOUNLINK);
2644                 }
2645 
2646                 if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2647                         xoap->xoa_immutable =
2648                             ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2649                         XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2650                 }
2651 
2652                 if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2653                         xoap->xoa_appendonly =
2654                             ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2655                         XVA_SET_RTN(xvap, XAT_APPENDONLY);
2656                 }
2657 
2658                 if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2659                         xoap->xoa_nodump =
2660                             ((zp->z_pflags & ZFS_NODUMP) != 0);
2661                         XVA_SET_RTN(xvap, XAT_NODUMP);
2662                 }
2663 
2664                 if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2665                         xoap->xoa_opaque =
2666                             ((zp->z_pflags & ZFS_OPAQUE) != 0);
2667                         XVA_SET_RTN(xvap, XAT_OPAQUE);
2668                 }
2669 
2670                 if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2671                         xoap->xoa_av_quarantined =
2672                             ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2673                         XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2674                 }
2675 
2676                 if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2677                         xoap->xoa_av_modified =
2678                             ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2679                         XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2680                 }
2681 
2682                 if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2683                     vp->v_type == VREG) {
2684                         zfs_sa_get_scanstamp(zp, xvap);
2685                 }
2686 
2687                 if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
2688                         uint64_t times[2];
2689 
2690                         (void) sa_lookup(zp->z_sa_hdl, SA_ZPL_CRTIME(zfsvfs),
2691                             times, sizeof (times));
2692                         ZFS_TIME_DECODE(&xoap->xoa_createtime, times);
2693                         XVA_SET_RTN(xvap, XAT_CREATETIME);
2694                 }
2695 
2696                 if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2697                         xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2698                         XVA_SET_RTN(xvap, XAT_REPARSE);
2699                 }
2700                 if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2701                         xoap->xoa_generation = zp->z_gen;
2702                         XVA_SET_RTN(xvap, XAT_GEN);
2703                 }
2704 
2705                 if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2706                         xoap->xoa_offline =
2707                             ((zp->z_pflags & ZFS_OFFLINE) != 0);
2708                         XVA_SET_RTN(xvap, XAT_OFFLINE);
2709                 }
2710 
2711                 if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2712                         xoap->xoa_sparse =
2713                             ((zp->z_pflags & ZFS_SPARSE) != 0);
2714                         XVA_SET_RTN(xvap, XAT_SPARSE);
2715                 }
2716         }
2717 
2718         ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2719         ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2720         ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2721 
2722         mutex_exit(&zp->z_lock);
2723 
2724         sa_object_size(zp->z_sa_hdl, &vap->va_blksize, &vap->va_nblocks);
2725 
2726         if (zp->z_blksz == 0) {
2727                 /*
2728                  * Block size hasn't been set; suggest maximal I/O transfers.
2729                  */
2730                 vap->va_blksize = zfsvfs->z_max_blksz;
2731         }
2732 
2733         ZFS_EXIT(zfsvfs);
2734         return (0);
2735 }
2736 
2737 /*
2738  * Set the file attributes to the values contained in the
2739  * vattr structure.
2740  *
2741  *      IN:     vp      - vnode of file to be modified.
2742  *              vap     - new attribute values.
2743  *                        If AT_XVATTR set, then optional attrs are being set
2744  *              flags   - ATTR_UTIME set if non-default time values provided.
2745  *                      - ATTR_NOACLCHECK (CIFS context only).
2746  *              cr      - credentials of caller.
2747  *              ct      - caller context
2748  *
2749  *      RETURN: 0 on success, error code on failure.
2750  *
2751  * Timestamps:
2752  *      vp - ctime updated, mtime updated if size changed.
2753  */
2754 /* ARGSUSED */
2755 static int
2756 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2757     caller_context_t *ct)
2758 {
2759         znode_t         *zp = VTOZ(vp);
2760         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
2761         zilog_t         *zilog;
2762         dmu_tx_t        *tx;
2763         vattr_t         oldva;
2764         xvattr_t        tmpxvattr;
2765         uint_t          mask = vap->va_mask;
2766         uint_t          saved_mask = 0;
2767         int             trim_mask = 0;
2768         uint64_t        new_mode;
2769         uint64_t        new_uid, new_gid;
2770         uint64_t        xattr_obj;
2771         uint64_t        mtime[2], ctime[2];
2772         znode_t         *attrzp;
2773         int             need_policy = FALSE;
2774         int             err, err2;
2775         zfs_fuid_info_t *fuidp = NULL;
2776         xvattr_t *xvap = (xvattr_t *)vap;       /* vap may be an xvattr_t * */
2777         xoptattr_t      *xoap;
2778         zfs_acl_t       *aclp;
2779         boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2780         boolean_t       fuid_dirtied = B_FALSE;
2781         sa_bulk_attr_t  bulk[7], xattr_bulk[7];
2782         int             count = 0, xattr_count = 0;
2783 
2784         if (mask == 0)
2785                 return (0);
2786 
2787         if (mask & AT_NOSET)
2788                 return (SET_ERROR(EINVAL));
2789 
2790         ZFS_ENTER(zfsvfs);
2791         ZFS_VERIFY_ZP(zp);
2792 
2793         zilog = zfsvfs->z_log;
2794 
2795         /*
2796          * Make sure that if we have ephemeral uid/gid or xvattr specified
2797          * that file system is at proper version level
2798          */
2799 
2800         if (zfsvfs->z_use_fuids == B_FALSE &&
2801             (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2802             ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2803             (mask & AT_XVATTR))) {
2804                 ZFS_EXIT(zfsvfs);
2805                 return (SET_ERROR(EINVAL));
2806         }
2807 
2808         if (mask & AT_SIZE && vp->v_type == VDIR) {
2809                 ZFS_EXIT(zfsvfs);
2810                 return (SET_ERROR(EISDIR));
2811         }
2812 
2813         if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2814                 ZFS_EXIT(zfsvfs);
2815                 return (SET_ERROR(EINVAL));
2816         }
2817 
2818         /*
2819          * If this is an xvattr_t, then get a pointer to the structure of
2820          * optional attributes.  If this is NULL, then we have a vattr_t.
2821          */
2822         xoap = xva_getxoptattr(xvap);
2823 
2824         xva_init(&tmpxvattr);
2825 
2826         /*
2827          * Immutable files can only alter immutable bit and atime
2828          */
2829         if ((zp->z_pflags & ZFS_IMMUTABLE) &&
2830             ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2831             ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2832                 ZFS_EXIT(zfsvfs);
2833                 return (SET_ERROR(EPERM));
2834         }
2835 
2836         if ((mask & AT_SIZE) && (zp->z_pflags & ZFS_READONLY)) {
2837                 ZFS_EXIT(zfsvfs);
2838                 return (SET_ERROR(EPERM));
2839         }
2840 
2841         /*
2842          * Verify timestamps doesn't overflow 32 bits.
2843          * ZFS can handle large timestamps, but 32bit syscalls can't
2844          * handle times greater than 2039.  This check should be removed
2845          * once large timestamps are fully supported.
2846          */
2847         if (mask & (AT_ATIME | AT_MTIME)) {
2848                 if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2849                     ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2850                         ZFS_EXIT(zfsvfs);
2851                         return (SET_ERROR(EOVERFLOW));
2852                 }
2853         }
2854 
2855 top:
2856         attrzp = NULL;
2857         aclp = NULL;
2858 
2859         /* Can this be moved to before the top label? */
2860         if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2861                 ZFS_EXIT(zfsvfs);
2862                 return (SET_ERROR(EROFS));
2863         }
2864 
2865         /*
2866          * First validate permissions
2867          */
2868 
2869         if (mask & AT_SIZE) {
2870                 err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, skipaclchk, cr);
2871                 if (err) {
2872                         ZFS_EXIT(zfsvfs);
2873                         return (err);
2874                 }
2875                 /*
2876                  * XXX - Note, we are not providing any open
2877                  * mode flags here (like FNDELAY), so we may
2878                  * block if there are locks present... this
2879                  * should be addressed in openat().
2880                  */
2881                 /* XXX - would it be OK to generate a log record here? */
2882                 err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2883                 if (err) {
2884                         ZFS_EXIT(zfsvfs);
2885                         return (err);
2886                 }
2887 
2888                 if (vap->va_size == 0)
2889                         vnevent_truncate(ZTOV(zp), ct);
2890         }
2891 
2892         if (mask & (AT_ATIME|AT_MTIME) ||
2893             ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2894             XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2895             XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2896             XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
2897             XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
2898             XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2899             XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
2900                 need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2901                     skipaclchk, cr);
2902         }
2903 
2904         if (mask & (AT_UID|AT_GID)) {
2905                 int     idmask = (mask & (AT_UID|AT_GID));
2906                 int     take_owner;
2907                 int     take_group;
2908 
2909                 /*
2910                  * NOTE: even if a new mode is being set,
2911                  * we may clear S_ISUID/S_ISGID bits.
2912                  */
2913 
2914                 if (!(mask & AT_MODE))
2915                         vap->va_mode = zp->z_mode;
2916 
2917                 /*
2918                  * Take ownership or chgrp to group we are a member of
2919                  */
2920 
2921                 take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2922                 take_group = (mask & AT_GID) &&
2923                     zfs_groupmember(zfsvfs, vap->va_gid, cr);
2924 
2925                 /*
2926                  * If both AT_UID and AT_GID are set then take_owner and
2927                  * take_group must both be set in order to allow taking
2928                  * ownership.
2929                  *
2930                  * Otherwise, send the check through secpolicy_vnode_setattr()
2931                  *
2932                  */
2933 
2934                 if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2935                     ((idmask == AT_UID) && take_owner) ||
2936                     ((idmask == AT_GID) && take_group)) {
2937                         if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2938                             skipaclchk, cr) == 0) {
2939                                 /*
2940                                  * Remove setuid/setgid for non-privileged users
2941                                  */
2942                                 secpolicy_setid_clear(vap, cr);
2943                                 trim_mask = (mask & (AT_UID|AT_GID));
2944                         } else {
2945                                 need_policy =  TRUE;
2946                         }
2947                 } else {
2948                         need_policy =  TRUE;
2949                 }
2950         }
2951 
2952         mutex_enter(&zp->z_lock);
2953         oldva.va_mode = zp->z_mode;
2954         zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
2955         if (mask & AT_XVATTR) {
2956                 /*
2957                  * Update xvattr mask to include only those attributes
2958                  * that are actually changing.
2959                  *
2960                  * the bits will be restored prior to actually setting
2961                  * the attributes so the caller thinks they were set.
2962                  */
2963                 if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2964                         if (xoap->xoa_appendonly !=
2965                             ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
2966                                 need_policy = TRUE;
2967                         } else {
2968                                 XVA_CLR_REQ(xvap, XAT_APPENDONLY);
2969                                 XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
2970                         }
2971                 }
2972 
2973                 if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2974                         if (xoap->xoa_nounlink !=
2975                             ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
2976                                 need_policy = TRUE;
2977                         } else {
2978                                 XVA_CLR_REQ(xvap, XAT_NOUNLINK);
2979                                 XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
2980                         }
2981                 }
2982 
2983                 if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2984                         if (xoap->xoa_immutable !=
2985                             ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
2986                                 need_policy = TRUE;
2987                         } else {
2988                                 XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
2989                                 XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
2990                         }
2991                 }
2992 
2993                 if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2994                         if (xoap->xoa_nodump !=
2995                             ((zp->z_pflags & ZFS_NODUMP) != 0)) {
2996                                 need_policy = TRUE;
2997                         } else {
2998                                 XVA_CLR_REQ(xvap, XAT_NODUMP);
2999                                 XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
3000                         }
3001                 }
3002 
3003                 if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
3004                         if (xoap->xoa_av_modified !=
3005                             ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
3006                                 need_policy = TRUE;
3007                         } else {
3008                                 XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
3009                                 XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
3010                         }
3011                 }
3012 
3013                 if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
3014                         if ((vp->v_type != VREG &&
3015                             xoap->xoa_av_quarantined) ||
3016                             xoap->xoa_av_quarantined !=
3017                             ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
3018                                 need_policy = TRUE;
3019                         } else {
3020                                 XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
3021                                 XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
3022                         }
3023                 }
3024 
3025                 if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
3026                         mutex_exit(&zp->z_lock);
3027                         ZFS_EXIT(zfsvfs);
3028                         return (SET_ERROR(EPERM));
3029                 }
3030 
3031                 if (need_policy == FALSE &&
3032                     (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
3033                     XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
3034                         need_policy = TRUE;
3035                 }
3036         }
3037 
3038         mutex_exit(&zp->z_lock);
3039 
3040         if (mask & AT_MODE) {
3041                 if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
3042                         err = secpolicy_setid_setsticky_clear(vp, vap,
3043                             &oldva, cr);
3044                         if (err) {
3045                                 ZFS_EXIT(zfsvfs);
3046                                 return (err);
3047                         }
3048                         trim_mask |= AT_MODE;
3049                 } else {
3050                         need_policy = TRUE;
3051                 }
3052         }
3053 
3054         if (need_policy) {
3055                 /*
3056                  * If trim_mask is set then take ownership
3057                  * has been granted or write_acl is present and user
3058                  * has the ability to modify mode.  In that case remove
3059                  * UID|GID and or MODE from mask so that
3060                  * secpolicy_vnode_setattr() doesn't revoke it.
3061                  */
3062 
3063                 if (trim_mask) {
3064                         saved_mask = vap->va_mask;
3065                         vap->va_mask &= ~trim_mask;
3066                 }
3067                 err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
3068                     (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
3069                 if (err) {
3070                         ZFS_EXIT(zfsvfs);
3071                         return (err);
3072                 }
3073 
3074                 if (trim_mask)
3075                         vap->va_mask |= saved_mask;
3076         }
3077 
3078         /*
3079          * secpolicy_vnode_setattr, or take ownership may have
3080          * changed va_mask
3081          */
3082         mask = vap->va_mask;
3083 
3084         if ((mask & (AT_UID | AT_GID))) {
3085                 err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
3086                     &xattr_obj, sizeof (xattr_obj));
3087 
3088                 if (err == 0 && xattr_obj) {
3089                         err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp);
3090                         if (err)
3091                                 goto out2;
3092                 }
3093                 if (mask & AT_UID) {
3094                         new_uid = zfs_fuid_create(zfsvfs,
3095                             (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
3096                         if (new_uid != zp->z_uid &&
3097                             zfs_fuid_overquota(zfsvfs, B_FALSE, new_uid)) {
3098                                 if (attrzp)
3099                                         VN_RELE(ZTOV(attrzp));
3100                                 err = SET_ERROR(EDQUOT);
3101                                 goto out2;
3102                         }
3103                 }
3104 
3105                 if (mask & AT_GID) {
3106                         new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
3107                             cr, ZFS_GROUP, &fuidp);
3108                         if (new_gid != zp->z_gid &&
3109                             zfs_fuid_overquota(zfsvfs, B_TRUE, new_gid)) {
3110                                 if (attrzp)
3111                                         VN_RELE(ZTOV(attrzp));
3112                                 err = SET_ERROR(EDQUOT);
3113                                 goto out2;
3114                         }
3115                 }
3116         }
3117         tx = dmu_tx_create(zfsvfs->z_os);
3118 
3119         if (mask & AT_MODE) {
3120                 uint64_t pmode = zp->z_mode;
3121                 uint64_t acl_obj;
3122                 new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
3123 
3124                 if (zp->z_zfsvfs->z_acl_mode == ZFS_ACL_RESTRICTED &&
3125                     !(zp->z_pflags & ZFS_ACL_TRIVIAL)) {
3126                         err = SET_ERROR(EPERM);
3127                         goto out;
3128                 }
3129 
3130                 if (err = zfs_acl_chmod_setattr(zp, &aclp, new_mode))
3131                         goto out;
3132 
3133                 mutex_enter(&zp->z_lock);
3134                 if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
3135                         /*
3136                          * Are we upgrading ACL from old V0 format
3137                          * to V1 format?
3138                          */
3139                         if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
3140                             zfs_znode_acl_version(zp) ==
3141                             ZFS_ACL_VERSION_INITIAL) {
3142                                 dmu_tx_hold_free(tx, acl_obj, 0,
3143                                     DMU_OBJECT_END);
3144                                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3145                                     0, aclp->z_acl_bytes);
3146                         } else {
3147                                 dmu_tx_hold_write(tx, acl_obj, 0,
3148                                     aclp->z_acl_bytes);
3149                         }
3150                 } else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3151                         dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3152                             0, aclp->z_acl_bytes);
3153                 }
3154                 mutex_exit(&zp->z_lock);
3155                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3156         } else {
3157                 if ((mask & AT_XVATTR) &&
3158                     XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3159                         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3160                 else
3161                         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3162         }
3163 
3164         if (attrzp) {
3165                 dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, B_FALSE);
3166         }
3167 
3168         fuid_dirtied = zfsvfs->z_fuid_dirty;
3169         if (fuid_dirtied)
3170                 zfs_fuid_txhold(zfsvfs, tx);
3171 
3172         zfs_sa_upgrade_txholds(tx, zp);
3173 
3174         err = dmu_tx_assign(tx, TXG_WAIT);
3175         if (err)
3176                 goto out;
3177 
3178         count = 0;
3179         /*
3180          * Set each attribute requested.
3181          * We group settings according to the locks they need to acquire.
3182          *
3183          * Note: you cannot set ctime directly, although it will be
3184          * updated as a side-effect of calling this function.
3185          */
3186 
3187 
3188         if (mask & (AT_UID|AT_GID|AT_MODE))
3189                 mutex_enter(&zp->z_acl_lock);
3190         mutex_enter(&zp->z_lock);
3191 
3192         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
3193             &zp->z_pflags, sizeof (zp->z_pflags));
3194 
3195         if (attrzp) {
3196                 if (mask & (AT_UID|AT_GID|AT_MODE))
3197                         mutex_enter(&attrzp->z_acl_lock);
3198                 mutex_enter(&attrzp->z_lock);
3199                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3200                     SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
3201                     sizeof (attrzp->z_pflags));
3202         }
3203 
3204         if (mask & (AT_UID|AT_GID)) {
3205 
3206                 if (mask & AT_UID) {
3207                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
3208                             &new_uid, sizeof (new_uid));
3209                         zp->z_uid = new_uid;
3210                         if (attrzp) {
3211                                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3212                                     SA_ZPL_UID(zfsvfs), NULL, &new_uid,
3213                                     sizeof (new_uid));
3214                                 attrzp->z_uid = new_uid;
3215                         }
3216                 }
3217 
3218                 if (mask & AT_GID) {
3219                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
3220                             NULL, &new_gid, sizeof (new_gid));
3221                         zp->z_gid = new_gid;
3222                         if (attrzp) {
3223                                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3224                                     SA_ZPL_GID(zfsvfs), NULL, &new_gid,
3225                                     sizeof (new_gid));
3226                                 attrzp->z_gid = new_gid;
3227                         }
3228                 }
3229                 if (!(mask & AT_MODE)) {
3230                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
3231                             NULL, &new_mode, sizeof (new_mode));
3232                         new_mode = zp->z_mode;
3233                 }
3234                 err = zfs_acl_chown_setattr(zp);
3235                 ASSERT(err == 0);
3236                 if (attrzp) {
3237                         err = zfs_acl_chown_setattr(attrzp);
3238                         ASSERT(err == 0);
3239                 }
3240         }
3241 
3242         if (mask & AT_MODE) {
3243                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
3244                     &new_mode, sizeof (new_mode));
3245                 zp->z_mode = new_mode;
3246                 ASSERT3U((uintptr_t)aclp, !=, NULL);
3247                 err = zfs_aclset_common(zp, aclp, cr, tx);
3248                 ASSERT0(err);
3249                 if (zp->z_acl_cached)
3250                         zfs_acl_free(zp->z_acl_cached);
3251                 zp->z_acl_cached = aclp;
3252                 aclp = NULL;
3253         }
3254 
3255 
3256         if (mask & AT_ATIME) {
3257                 ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
3258                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
3259                     &zp->z_atime, sizeof (zp->z_atime));
3260         }
3261 
3262         if (mask & AT_MTIME) {
3263                 ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
3264                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
3265                     mtime, sizeof (mtime));
3266         }
3267 
3268         /* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
3269         if (mask & AT_SIZE && !(mask & AT_MTIME)) {
3270                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
3271                     NULL, mtime, sizeof (mtime));
3272                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3273                     &ctime, sizeof (ctime));
3274                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
3275                     B_TRUE);
3276         } else if (mask != 0) {
3277                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3278                     &ctime, sizeof (ctime));
3279                 zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime,
3280                     B_TRUE);
3281                 if (attrzp) {
3282                         SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3283                             SA_ZPL_CTIME(zfsvfs), NULL,
3284                             &ctime, sizeof (ctime));
3285                         zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
3286                             mtime, ctime, B_TRUE);
3287                 }
3288         }
3289         /*
3290          * Do this after setting timestamps to prevent timestamp
3291          * update from toggling bit
3292          */
3293 
3294         if (xoap && (mask & AT_XVATTR)) {
3295 
3296                 /*
3297                  * restore trimmed off masks
3298                  * so that return masks can be set for caller.
3299                  */
3300 
3301                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
3302                         XVA_SET_REQ(xvap, XAT_APPENDONLY);
3303                 }
3304                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
3305                         XVA_SET_REQ(xvap, XAT_NOUNLINK);
3306                 }
3307                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
3308                         XVA_SET_REQ(xvap, XAT_IMMUTABLE);
3309                 }
3310                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
3311                         XVA_SET_REQ(xvap, XAT_NODUMP);
3312                 }
3313                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
3314                         XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
3315                 }
3316                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
3317                         XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
3318                 }
3319 
3320                 if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3321                         ASSERT(vp->v_type == VREG);
3322 
3323                 zfs_xvattr_set(zp, xvap, tx);
3324         }
3325 
3326         if (fuid_dirtied)
3327                 zfs_fuid_sync(zfsvfs, tx);
3328 
3329         if (mask != 0)
3330                 zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
3331 
3332         mutex_exit(&zp->z_lock);
3333         if (mask & (AT_UID|AT_GID|AT_MODE))
3334                 mutex_exit(&zp->z_acl_lock);
3335 
3336         if (attrzp) {
3337                 if (mask & (AT_UID|AT_GID|AT_MODE))
3338                         mutex_exit(&attrzp->z_acl_lock);
3339                 mutex_exit(&attrzp->z_lock);
3340         }
3341 out:
3342         if (err == 0 && attrzp) {
3343                 err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
3344                     xattr_count, tx);
3345                 ASSERT(err2 == 0);
3346         }
3347 
3348         if (attrzp)
3349                 VN_RELE(ZTOV(attrzp));
3350 
3351         if (aclp)
3352                 zfs_acl_free(aclp);
3353 
3354         if (fuidp) {
3355                 zfs_fuid_info_free(fuidp);
3356                 fuidp = NULL;
3357         }
3358 
3359         if (err) {
3360                 dmu_tx_abort(tx);
3361                 if (err == ERESTART)
3362                         goto top;
3363         } else {
3364                 err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
3365                 dmu_tx_commit(tx);
3366         }
3367 
3368 out2:
3369         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3370                 zil_commit(zilog, 0);
3371 
3372         ZFS_EXIT(zfsvfs);
3373         return (err);
3374 }
3375 
3376 typedef struct zfs_zlock {
3377         krwlock_t       *zl_rwlock;     /* lock we acquired */
3378         znode_t         *zl_znode;      /* znode we held */
3379         struct zfs_zlock *zl_next;      /* next in list */
3380 } zfs_zlock_t;
3381 
3382 /*
3383  * Drop locks and release vnodes that were held by zfs_rename_lock().
3384  */
3385 static void
3386 zfs_rename_unlock(zfs_zlock_t **zlpp)
3387 {
3388         zfs_zlock_t *zl;
3389 
3390         while ((zl = *zlpp) != NULL) {
3391                 if (zl->zl_znode != NULL)
3392                         VN_RELE(ZTOV(zl->zl_znode));
3393                 rw_exit(zl->zl_rwlock);
3394                 *zlpp = zl->zl_next;
3395                 kmem_free(zl, sizeof (*zl));
3396         }
3397 }
3398 
3399 /*
3400  * Search back through the directory tree, using the ".." entries.
3401  * Lock each directory in the chain to prevent concurrent renames.
3402  * Fail any attempt to move a directory into one of its own descendants.
3403  * XXX - z_parent_lock can overlap with map or grow locks
3404  */
3405 static int
3406 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
3407 {
3408         zfs_zlock_t     *zl;
3409         znode_t         *zp = tdzp;
3410         uint64_t        rootid = zp->z_zfsvfs->z_root;
3411         uint64_t        oidp = zp->z_id;
3412         krwlock_t       *rwlp = &szp->z_parent_lock;
3413         krw_t           rw = RW_WRITER;
3414 
3415         /*
3416          * First pass write-locks szp and compares to zp->z_id.
3417          * Later passes read-lock zp and compare to zp->z_parent.
3418          */
3419         do {
3420                 if (!rw_tryenter(rwlp, rw)) {
3421                         /*
3422                          * Another thread is renaming in this path.
3423                          * Note that if we are a WRITER, we don't have any
3424                          * parent_locks held yet.
3425                          */
3426                         if (rw == RW_READER && zp->z_id > szp->z_id) {
3427                                 /*
3428                                  * Drop our locks and restart
3429                                  */
3430                                 zfs_rename_unlock(&zl);
3431                                 *zlpp = NULL;
3432                                 zp = tdzp;
3433                                 oidp = zp->z_id;
3434                                 rwlp = &szp->z_parent_lock;
3435                                 rw = RW_WRITER;
3436                                 continue;
3437                         } else {
3438                                 /*
3439                                  * Wait for other thread to drop its locks
3440                                  */
3441                                 rw_enter(rwlp, rw);
3442                         }
3443                 }
3444 
3445                 zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
3446                 zl->zl_rwlock = rwlp;
3447                 zl->zl_znode = NULL;
3448                 zl->zl_next = *zlpp;
3449                 *zlpp = zl;
3450 
3451                 if (oidp == szp->z_id)               /* We're a descendant of szp */
3452                         return (SET_ERROR(EINVAL));
3453 
3454                 if (oidp == rootid)             /* We've hit the top */
3455                         return (0);
3456 
3457                 if (rw == RW_READER) {          /* i.e. not the first pass */
3458                         int error = zfs_zget(zp->z_zfsvfs, oidp, &zp);
3459                         if (error)
3460                                 return (error);
3461                         zl->zl_znode = zp;
3462                 }
3463                 (void) sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zp->z_zfsvfs),
3464                     &oidp, sizeof (oidp));
3465                 rwlp = &zp->z_parent_lock;
3466                 rw = RW_READER;
3467 
3468         } while (zp->z_id != sdzp->z_id);
3469 
3470         return (0);
3471 }
3472 
3473 /*
3474  * Move an entry from the provided source directory to the target
3475  * directory.  Change the entry name as indicated.
3476  *
3477  *      IN:     sdvp    - Source directory containing the "old entry".
3478  *              snm     - Old entry name.
3479  *              tdvp    - Target directory to contain the "new entry".
3480  *              tnm     - New entry name.
3481  *              cr      - credentials of caller.
3482  *              ct      - caller context
3483  *              flags   - case flags
3484  *
3485  *      RETURN: 0 on success, error code on failure.
3486  *
3487  * Timestamps:
3488  *      sdvp,tdvp - ctime|mtime updated
3489  */
3490 /*ARGSUSED*/
3491 static int
3492 zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr,
3493     caller_context_t *ct, int flags)
3494 {
3495         znode_t         *tdzp, *szp, *tzp;
3496         znode_t         *sdzp = VTOZ(sdvp);
3497         zfsvfs_t        *zfsvfs = sdzp->z_zfsvfs;
3498         zilog_t         *zilog;
3499         vnode_t         *realvp;
3500         zfs_dirlock_t   *sdl, *tdl;
3501         dmu_tx_t        *tx;
3502         zfs_zlock_t     *zl;
3503         int             cmp, serr, terr;
3504         int             error = 0;
3505         int             zflg = 0;
3506         boolean_t       waited = B_FALSE;
3507 
3508         ZFS_ENTER(zfsvfs);
3509         ZFS_VERIFY_ZP(sdzp);
3510         zilog = zfsvfs->z_log;
3511 
3512         /*
3513          * Make sure we have the real vp for the target directory.
3514          */
3515         if (VOP_REALVP(tdvp, &realvp, ct) == 0)
3516                 tdvp = realvp;
3517 
3518         tdzp = VTOZ(tdvp);
3519         ZFS_VERIFY_ZP(tdzp);
3520 
3521         /*
3522          * We check z_zfsvfs rather than v_vfsp here, because snapshots and the
3523          * ctldir appear to have the same v_vfsp.
3524          */
3525         if (tdzp->z_zfsvfs != zfsvfs || zfsctl_is_node(tdvp)) {
3526                 ZFS_EXIT(zfsvfs);
3527                 return (SET_ERROR(EXDEV));
3528         }
3529 
3530         if (zfsvfs->z_utf8 && u8_validate(tnm,
3531             strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3532                 ZFS_EXIT(zfsvfs);
3533                 return (SET_ERROR(EILSEQ));
3534         }
3535 
3536         if (flags & FIGNORECASE)
3537                 zflg |= ZCILOOK;
3538 
3539 top:
3540         szp = NULL;
3541         tzp = NULL;
3542         zl = NULL;
3543 
3544         /*
3545          * This is to prevent the creation of links into attribute space
3546          * by renaming a linked file into/outof an attribute directory.
3547          * See the comment in zfs_link() for why this is considered bad.
3548          */
3549         if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3550                 ZFS_EXIT(zfsvfs);
3551                 return (SET_ERROR(EINVAL));
3552         }
3553 
3554         /*
3555          * Lock source and target directory entries.  To prevent deadlock,
3556          * a lock ordering must be defined.  We lock the directory with
3557          * the smallest object id first, or if it's a tie, the one with
3558          * the lexically first name.
3559          */
3560         if (sdzp->z_id < tdzp->z_id) {
3561                 cmp = -1;
3562         } else if (sdzp->z_id > tdzp->z_id) {
3563                 cmp = 1;
3564         } else {
3565                 /*
3566                  * First compare the two name arguments without
3567                  * considering any case folding.
3568                  */
3569                 int nofold = (zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER);
3570 
3571                 cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
3572                 ASSERT(error == 0 || !zfsvfs->z_utf8);
3573                 if (cmp == 0) {
3574                         /*
3575                          * POSIX: "If the old argument and the new argument
3576                          * both refer to links to the same existing file,
3577                          * the rename() function shall return successfully
3578                          * and perform no other action."
3579                          */
3580                         ZFS_EXIT(zfsvfs);
3581                         return (0);
3582                 }
3583                 /*
3584                  * If the file system is case-folding, then we may
3585                  * have some more checking to do.  A case-folding file
3586                  * system is either supporting mixed case sensitivity
3587                  * access or is completely case-insensitive.  Note
3588                  * that the file system is always case preserving.
3589                  *
3590                  * In mixed sensitivity mode case sensitive behavior
3591                  * is the default.  FIGNORECASE must be used to
3592                  * explicitly request case insensitive behavior.
3593                  *
3594                  * If the source and target names provided differ only
3595                  * by case (e.g., a request to rename 'tim' to 'Tim'),
3596                  * we will treat this as a special case in the
3597                  * case-insensitive mode: as long as the source name
3598                  * is an exact match, we will allow this to proceed as
3599                  * a name-change request.
3600                  */
3601                 if ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
3602                     (zfsvfs->z_case == ZFS_CASE_MIXED &&
3603                     flags & FIGNORECASE)) &&
3604                     u8_strcmp(snm, tnm, 0, zfsvfs->z_norm, U8_UNICODE_LATEST,
3605                     &error) == 0) {
3606                         /*
3607                          * case preserving rename request, require exact
3608                          * name matches
3609                          */
3610                         zflg |= ZCIEXACT;
3611                         zflg &= ~ZCILOOK;
3612                 }
3613         }
3614 
3615         /*
3616          * If the source and destination directories are the same, we should
3617          * grab the z_name_lock of that directory only once.
3618          */
3619         if (sdzp == tdzp) {
3620                 zflg |= ZHAVELOCK;
3621                 rw_enter(&sdzp->z_name_lock, RW_READER);
3622         }
3623 
3624         if (cmp < 0) {
3625                 serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
3626                     ZEXISTS | zflg, NULL, NULL);
3627                 terr = zfs_dirent_lock(&tdl,
3628                     tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
3629         } else {
3630                 terr = zfs_dirent_lock(&tdl,
3631                     tdzp, tnm, &tzp, zflg, NULL, NULL);
3632                 serr = zfs_dirent_lock(&sdl,
3633                     sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
3634                     NULL, NULL);
3635         }
3636 
3637         if (serr) {
3638                 /*
3639                  * Source entry invalid or not there.
3640                  */
3641                 if (!terr) {
3642                         zfs_dirent_unlock(tdl);
3643                         if (tzp)
3644                                 VN_RELE(ZTOV(tzp));
3645                 }
3646 
3647                 if (sdzp == tdzp)
3648                         rw_exit(&sdzp->z_name_lock);
3649 
3650                 if (strcmp(snm, "..") == 0)
3651                         serr = SET_ERROR(EINVAL);
3652                 ZFS_EXIT(zfsvfs);
3653                 return (serr);
3654         }
3655         if (terr) {
3656                 zfs_dirent_unlock(sdl);
3657                 VN_RELE(ZTOV(szp));
3658 
3659                 if (sdzp == tdzp)
3660                         rw_exit(&sdzp->z_name_lock);
3661 
3662                 if (strcmp(tnm, "..") == 0)
3663                         terr = SET_ERROR(EINVAL);
3664                 ZFS_EXIT(zfsvfs);
3665                 return (terr);
3666         }
3667 
3668         /*
3669          * Must have write access at the source to remove the old entry
3670          * and write access at the target to create the new entry.
3671          * Note that if target and source are the same, this can be
3672          * done in a single check.
3673          */
3674 
3675         if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
3676                 goto out;
3677 
3678         if (ZTOV(szp)->v_type == VDIR) {
3679                 /*
3680                  * Check to make sure rename is valid.
3681                  * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3682                  */
3683                 if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
3684                         goto out;
3685         }
3686 
3687         /*
3688          * Does target exist?
3689          */
3690         if (tzp) {
3691                 /*
3692                  * Source and target must be the same type.
3693                  */
3694                 if (ZTOV(szp)->v_type == VDIR) {
3695                         if (ZTOV(tzp)->v_type != VDIR) {
3696                                 error = SET_ERROR(ENOTDIR);
3697                                 goto out;
3698                         }
3699                 } else {
3700                         if (ZTOV(tzp)->v_type == VDIR) {
3701                                 error = SET_ERROR(EISDIR);
3702                                 goto out;
3703                         }
3704                 }
3705                 /*
3706                  * POSIX dictates that when the source and target
3707                  * entries refer to the same file object, rename
3708                  * must do nothing and exit without error.
3709                  */
3710                 if (szp->z_id == tzp->z_id) {
3711                         error = 0;
3712                         goto out;
3713                 }
3714         }
3715 
3716         vnevent_rename_src(ZTOV(szp), sdvp, snm, ct);
3717         if (tzp)
3718                 vnevent_rename_dest(ZTOV(tzp), tdvp, tnm, ct);
3719 
3720         /*
3721          * notify the target directory if it is not the same
3722          * as source directory.
3723          */
3724         if (tdvp != sdvp) {
3725                 vnevent_rename_dest_dir(tdvp, ct);
3726         }
3727 
3728         tx = dmu_tx_create(zfsvfs->z_os);
3729         dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3730         dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
3731         dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3732         dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3733         if (sdzp != tdzp) {
3734                 dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, B_FALSE);
3735                 zfs_sa_upgrade_txholds(tx, tdzp);
3736         }
3737         if (tzp) {
3738                 dmu_tx_hold_sa(tx, tzp->z_sa_hdl, B_FALSE);
3739                 zfs_sa_upgrade_txholds(tx, tzp);
3740         }
3741 
3742         zfs_sa_upgrade_txholds(tx, szp);
3743         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3744         error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
3745         if (error) {
3746                 if (zl != NULL)
3747                         zfs_rename_unlock(&zl);
3748                 zfs_dirent_unlock(sdl);
3749                 zfs_dirent_unlock(tdl);
3750 
3751                 if (sdzp == tdzp)
3752                         rw_exit(&sdzp->z_name_lock);
3753 
3754                 VN_RELE(ZTOV(szp));
3755                 if (tzp)
3756                         VN_RELE(ZTOV(tzp));
3757                 if (error == ERESTART) {
3758                         waited = B_TRUE;
3759                         dmu_tx_wait(tx);
3760                         dmu_tx_abort(tx);
3761                         goto top;
3762                 }
3763                 dmu_tx_abort(tx);
3764                 ZFS_EXIT(zfsvfs);
3765                 return (error);
3766         }
3767 
3768         if (tzp)        /* Attempt to remove the existing target */
3769                 error = zfs_link_destroy(tdl, tzp, tx, zflg, NULL);
3770 
3771         if (error == 0) {
3772                 error = zfs_link_create(tdl, szp, tx, ZRENAMING);
3773                 if (error == 0) {
3774                         szp->z_pflags |= ZFS_AV_MODIFIED;
3775 
3776                         error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
3777                             (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3778                         ASSERT0(error);
3779 
3780                         error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
3781                         if (error == 0) {
3782                                 zfs_log_rename(zilog, tx, TX_RENAME |
3783                                     (flags & FIGNORECASE ? TX_CI : 0), sdzp,
3784                                     sdl->dl_name, tdzp, tdl->dl_name, szp);
3785 
3786                                 /*
3787                                  * Update path information for the target vnode
3788                                  */
3789                                 vn_renamepath(tdvp, ZTOV(szp), tnm,
3790                                     strlen(tnm));
3791                         } else {
3792                                 /*
3793                                  * At this point, we have successfully created
3794                                  * the target name, but have failed to remove
3795                                  * the source name.  Since the create was done
3796                                  * with the ZRENAMING flag, there are
3797                                  * complications; for one, the link count is
3798                                  * wrong.  The easiest way to deal with this
3799                                  * is to remove the newly created target, and
3800                                  * return the original error.  This must
3801                                  * succeed; fortunately, it is very unlikely to
3802                                  * fail, since we just created it.
3803                                  */
3804                                 VERIFY3U(zfs_link_destroy(tdl, szp, tx,
3805                                     ZRENAMING, NULL), ==, 0);
3806                         }
3807                 }
3808         }
3809 
3810         dmu_tx_commit(tx);
3811 out:
3812         if (zl != NULL)
3813                 zfs_rename_unlock(&zl);
3814 
3815         zfs_dirent_unlock(sdl);
3816         zfs_dirent_unlock(tdl);
3817 
3818         if (sdzp == tdzp)
3819                 rw_exit(&sdzp->z_name_lock);
3820 
3821 
3822         VN_RELE(ZTOV(szp));
3823         if (tzp)
3824                 VN_RELE(ZTOV(tzp));
3825 
3826         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3827                 zil_commit(zilog, 0);
3828 
3829         ZFS_EXIT(zfsvfs);
3830         return (error);
3831 }
3832 
3833 /*
3834  * Insert the indicated symbolic reference entry into the directory.
3835  *
3836  *      IN:     dvp     - Directory to contain new symbolic link.
3837  *              link    - Name for new symlink entry.
3838  *              vap     - Attributes of new entry.
3839  *              cr      - credentials of caller.
3840  *              ct      - caller context
3841  *              flags   - case flags
3842  *
3843  *      RETURN: 0 on success, error code on failure.
3844  *
3845  * Timestamps:
3846  *      dvp - ctime|mtime updated
3847  */
3848 /*ARGSUSED*/
3849 static int
3850 zfs_symlink(vnode_t *dvp, char *name, vattr_t *vap, char *link, cred_t *cr,
3851     caller_context_t *ct, int flags)
3852 {
3853         znode_t         *zp, *dzp = VTOZ(dvp);
3854         zfs_dirlock_t   *dl;
3855         dmu_tx_t        *tx;
3856         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
3857         zilog_t         *zilog;
3858         uint64_t        len = strlen(link);
3859         int             error;
3860         int             zflg = ZNEW;
3861         zfs_acl_ids_t   acl_ids;
3862         boolean_t       fuid_dirtied;
3863         uint64_t        txtype = TX_SYMLINK;
3864         boolean_t       waited = B_FALSE;
3865 
3866         ASSERT(vap->va_type == VLNK);
3867 
3868         ZFS_ENTER(zfsvfs);
3869         ZFS_VERIFY_ZP(dzp);
3870         zilog = zfsvfs->z_log;
3871 
3872         if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
3873             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3874                 ZFS_EXIT(zfsvfs);
3875                 return (SET_ERROR(EILSEQ));
3876         }
3877         if (flags & FIGNORECASE)
3878                 zflg |= ZCILOOK;
3879 
3880         if (len > MAXPATHLEN) {
3881                 ZFS_EXIT(zfsvfs);
3882                 return (SET_ERROR(ENAMETOOLONG));
3883         }
3884 
3885         if ((error = zfs_acl_ids_create(dzp, 0,
3886             vap, cr, NULL, &acl_ids)) != 0) {
3887                 ZFS_EXIT(zfsvfs);
3888                 return (error);
3889         }
3890 top:
3891         /*
3892          * Attempt to lock directory; fail if entry already exists.
3893          */
3894         error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
3895         if (error) {
3896                 zfs_acl_ids_free(&acl_ids);
3897                 ZFS_EXIT(zfsvfs);
3898                 return (error);
3899         }
3900 
3901         if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
3902                 zfs_acl_ids_free(&acl_ids);
3903                 zfs_dirent_unlock(dl);
3904                 ZFS_EXIT(zfsvfs);
3905                 return (error);
3906         }
3907 
3908         if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
3909                 zfs_acl_ids_free(&acl_ids);
3910                 zfs_dirent_unlock(dl);
3911                 ZFS_EXIT(zfsvfs);
3912                 return (SET_ERROR(EDQUOT));
3913         }
3914         tx = dmu_tx_create(zfsvfs->z_os);
3915         fuid_dirtied = zfsvfs->z_fuid_dirty;
3916         dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3917         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3918         dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
3919             ZFS_SA_BASE_ATTR_SIZE + len);
3920         dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
3921         if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3922                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3923                     acl_ids.z_aclp->z_acl_bytes);
3924         }
3925         if (fuid_dirtied)
3926                 zfs_fuid_txhold(zfsvfs, tx);
3927         error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
3928         if (error) {
3929                 zfs_dirent_unlock(dl);
3930                 if (error == ERESTART) {
3931                         waited = B_TRUE;
3932                         dmu_tx_wait(tx);
3933                         dmu_tx_abort(tx);
3934                         goto top;
3935                 }
3936                 zfs_acl_ids_free(&acl_ids);
3937                 dmu_tx_abort(tx);
3938                 ZFS_EXIT(zfsvfs);
3939                 return (error);
3940         }
3941 
3942         /*
3943          * Create a new object for the symlink.
3944          * for version 4 ZPL datsets the symlink will be an SA attribute
3945          */
3946         zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
3947 
3948         if (fuid_dirtied)
3949                 zfs_fuid_sync(zfsvfs, tx);
3950 
3951         mutex_enter(&zp->z_lock);
3952         if (zp->z_is_sa)
3953                 error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs),
3954                     link, len, tx);
3955         else
3956                 zfs_sa_symlink(zp, link, len, tx);
3957         mutex_exit(&zp->z_lock);
3958 
3959         zp->z_size = len;
3960         (void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
3961             &zp->z_size, sizeof (zp->z_size), tx);
3962         /*
3963          * Insert the new object into the directory.
3964          */
3965         (void) zfs_link_create(dl, zp, tx, ZNEW);
3966 
3967         if (flags & FIGNORECASE)
3968                 txtype |= TX_CI;
3969         zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3970 
3971         zfs_acl_ids_free(&acl_ids);
3972 
3973         dmu_tx_commit(tx);
3974 
3975         zfs_dirent_unlock(dl);
3976 
3977         VN_RELE(ZTOV(zp));
3978 
3979         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3980                 zil_commit(zilog, 0);
3981 
3982         ZFS_EXIT(zfsvfs);
3983         return (error);
3984 }
3985 
3986 /*
3987  * Return, in the buffer contained in the provided uio structure,
3988  * the symbolic path referred to by vp.
3989  *
3990  *      IN:     vp      - vnode of symbolic link.
3991  *              uio     - structure to contain the link path.
3992  *              cr      - credentials of caller.
3993  *              ct      - caller context
3994  *
3995  *      OUT:    uio     - structure containing the link path.
3996  *
3997  *      RETURN: 0 on success, error code on failure.
3998  *
3999  * Timestamps:
4000  *      vp - atime updated
4001  */
4002 /* ARGSUSED */
4003 static int
4004 zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr, caller_context_t *ct)
4005 {
4006         znode_t         *zp = VTOZ(vp);
4007         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4008         int             error;
4009 
4010         ZFS_ENTER(zfsvfs);
4011         ZFS_VERIFY_ZP(zp);
4012 
4013         mutex_enter(&zp->z_lock);
4014         if (zp->z_is_sa)
4015                 error = sa_lookup_uio(zp->z_sa_hdl,
4016                     SA_ZPL_SYMLINK(zfsvfs), uio);
4017         else
4018                 error = zfs_sa_readlink(zp, uio);
4019         mutex_exit(&zp->z_lock);
4020 
4021         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4022 
4023         ZFS_EXIT(zfsvfs);
4024         return (error);
4025 }
4026 
4027 /*
4028  * Insert a new entry into directory tdvp referencing svp.
4029  *
4030  *      IN:     tdvp    - Directory to contain new entry.
4031  *              svp     - vnode of new entry.
4032  *              name    - name of new entry.
4033  *              cr      - credentials of caller.
4034  *              ct      - caller context
4035  *
4036  *      RETURN: 0 on success, error code on failure.
4037  *
4038  * Timestamps:
4039  *      tdvp - ctime|mtime updated
4040  *       svp - ctime updated
4041  */
4042 /* ARGSUSED */
4043 static int
4044 zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
4045     caller_context_t *ct, int flags)
4046 {
4047         znode_t         *dzp = VTOZ(tdvp);
4048         znode_t         *tzp, *szp;
4049         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
4050         zilog_t         *zilog;
4051         zfs_dirlock_t   *dl;
4052         dmu_tx_t        *tx;
4053         vnode_t         *realvp;
4054         int             error;
4055         int             zf = ZNEW;
4056         uint64_t        parent;
4057         uid_t           owner;
4058         boolean_t       waited = B_FALSE;
4059 
4060         ASSERT(tdvp->v_type == VDIR);
4061 
4062         ZFS_ENTER(zfsvfs);
4063         ZFS_VERIFY_ZP(dzp);
4064         zilog = zfsvfs->z_log;
4065 
4066         if (VOP_REALVP(svp, &realvp, ct) == 0)
4067                 svp = realvp;
4068 
4069         /*
4070          * POSIX dictates that we return EPERM here.
4071          * Better choices include ENOTSUP or EISDIR.
4072          */
4073         if (svp->v_type == VDIR) {
4074                 ZFS_EXIT(zfsvfs);
4075                 return (SET_ERROR(EPERM));
4076         }
4077 
4078         szp = VTOZ(svp);
4079         ZFS_VERIFY_ZP(szp);
4080 
4081         /*
4082          * We check z_zfsvfs rather than v_vfsp here, because snapshots and the
4083          * ctldir appear to have the same v_vfsp.
4084          */
4085         if (szp->z_zfsvfs != zfsvfs || zfsctl_is_node(svp)) {
4086                 ZFS_EXIT(zfsvfs);
4087                 return (SET_ERROR(EXDEV));
4088         }
4089 
4090         /* Prevent links to .zfs/shares files */
4091 
4092         if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
4093             &parent, sizeof (uint64_t))) != 0) {
4094                 ZFS_EXIT(zfsvfs);
4095                 return (error);
4096         }
4097         if (parent == zfsvfs->z_shares_dir) {
4098                 ZFS_EXIT(zfsvfs);
4099                 return (SET_ERROR(EPERM));
4100         }
4101 
4102         if (zfsvfs->z_utf8 && u8_validate(name,
4103             strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
4104                 ZFS_EXIT(zfsvfs);
4105                 return (SET_ERROR(EILSEQ));
4106         }
4107         if (flags & FIGNORECASE)
4108                 zf |= ZCILOOK;
4109 
4110         /*
4111          * We do not support links between attributes and non-attributes
4112          * because of the potential security risk of creating links
4113          * into "normal" file space in order to circumvent restrictions
4114          * imposed in attribute space.
4115          */
4116         if ((szp->z_pflags & ZFS_XATTR) != (dzp->z_pflags & ZFS_XATTR)) {
4117                 ZFS_EXIT(zfsvfs);
4118                 return (SET_ERROR(EINVAL));
4119         }
4120 
4121 
4122         owner = zfs_fuid_map_id(zfsvfs, szp->z_uid, cr, ZFS_OWNER);
4123         if (owner != crgetuid(cr) && secpolicy_basic_link(cr) != 0) {
4124                 ZFS_EXIT(zfsvfs);
4125                 return (SET_ERROR(EPERM));
4126         }
4127 
4128         if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
4129                 ZFS_EXIT(zfsvfs);
4130                 return (error);
4131         }
4132 
4133 top:
4134         /*
4135          * Attempt to lock directory; fail if entry already exists.
4136          */
4137         error = zfs_dirent_lock(&dl, dzp, name, &tzp, zf, NULL, NULL);
4138         if (error) {
4139                 ZFS_EXIT(zfsvfs);
4140                 return (error);
4141         }
4142 
4143         tx = dmu_tx_create(zfsvfs->z_os);
4144         dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
4145         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
4146         zfs_sa_upgrade_txholds(tx, szp);
4147         zfs_sa_upgrade_txholds(tx, dzp);
4148         error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
4149         if (error) {
4150                 zfs_dirent_unlock(dl);
4151                 if (error == ERESTART) {
4152                         waited = B_TRUE;
4153                         dmu_tx_wait(tx);
4154                         dmu_tx_abort(tx);
4155                         goto top;
4156                 }
4157                 dmu_tx_abort(tx);
4158                 ZFS_EXIT(zfsvfs);
4159                 return (error);
4160         }
4161 
4162         error = zfs_link_create(dl, szp, tx, 0);
4163 
4164         if (error == 0) {
4165                 uint64_t txtype = TX_LINK;
4166                 if (flags & FIGNORECASE)
4167                         txtype |= TX_CI;
4168                 zfs_log_link(zilog, tx, txtype, dzp, szp, name);
4169         }
4170 
4171         dmu_tx_commit(tx);
4172 
4173         zfs_dirent_unlock(dl);
4174 
4175         if (error == 0) {
4176                 vnevent_link(svp, ct);
4177         }
4178 
4179         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4180                 zil_commit(zilog, 0);
4181 
4182         ZFS_EXIT(zfsvfs);
4183         return (error);
4184 }
4185 
4186 /*
4187  * zfs_null_putapage() is used when the file system has been force
4188  * unmounted. It just drops the pages.
4189  */
4190 /* ARGSUSED */
4191 static int
4192 zfs_null_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4193                 size_t *lenp, int flags, cred_t *cr)
4194 {
4195         pvn_write_done(pp, B_INVAL|B_FORCE|B_ERROR);
4196         return (0);
4197 }
4198 
4199 /*
4200  * Push a page out to disk, klustering if possible.
4201  *
4202  *      IN:     vp      - file to push page to.
4203  *              pp      - page to push.
4204  *              flags   - additional flags.
4205  *              cr      - credentials of caller.
4206  *
4207  *      OUT:    offp    - start of range pushed.
4208  *              lenp    - len of range pushed.
4209  *
4210  *      RETURN: 0 on success, error code on failure.
4211  *
4212  * NOTE: callers must have locked the page to be pushed.  On
4213  * exit, the page (and all other pages in the kluster) must be
4214  * unlocked.
4215  */
4216 /* ARGSUSED */
4217 static int
4218 zfs_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4219                 size_t *lenp, int flags, cred_t *cr)
4220 {
4221         znode_t         *zp = VTOZ(vp);
4222         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4223         dmu_tx_t        *tx;
4224         u_offset_t      off, koff;
4225         size_t          len, klen;
4226         int             err;
4227 
4228         off = pp->p_offset;
4229         len = PAGESIZE;
4230         /*
4231          * If our blocksize is bigger than the page size, try to kluster
4232          * multiple pages so that we write a full block (thus avoiding
4233          * a read-modify-write).
4234          */
4235         if (off < zp->z_size && zp->z_blksz > PAGESIZE) {
4236                 klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
4237                 koff = ISP2(klen) ? P2ALIGN(off, (u_offset_t)klen) : 0;
4238                 ASSERT(koff <= zp->z_size);
4239                 if (koff + klen > zp->z_size)
4240                         klen = P2ROUNDUP(zp->z_size - koff, (uint64_t)PAGESIZE);
4241                 pp = pvn_write_kluster(vp, pp, &off, &len, koff, klen, flags);
4242         }
4243         ASSERT3U(btop(len), ==, btopr(len));
4244 
4245         /*
4246          * Can't push pages past end-of-file.
4247          */
4248         if (off >= zp->z_size) {
4249                 /* ignore all pages */
4250                 err = 0;
4251                 goto out;
4252         } else if (off + len > zp->z_size) {
4253                 int npages = btopr(zp->z_size - off);
4254                 page_t *trunc;
4255 
4256                 page_list_break(&pp, &trunc, npages);
4257                 /* ignore pages past end of file */
4258                 if (trunc)
4259                         pvn_write_done(trunc, flags);
4260                 len = zp->z_size - off;
4261         }
4262 
4263         if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
4264             zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
4265                 err = SET_ERROR(EDQUOT);
4266                 goto out;
4267         }
4268         tx = dmu_tx_create(zfsvfs->z_os);
4269         dmu_tx_hold_write(tx, zp->z_id, off, len);
4270 
4271         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4272         zfs_sa_upgrade_txholds(tx, zp);
4273         err = dmu_tx_assign(tx, TXG_WAIT);
4274         if (err != 0) {
4275                 dmu_tx_abort(tx);
4276                 goto out;
4277         }
4278 
4279         if (zp->z_blksz <= PAGESIZE) {
4280                 caddr_t va = zfs_map_page(pp, S_READ);
4281                 ASSERT3U(len, <=, PAGESIZE);
4282                 dmu_write(zfsvfs->z_os, zp->z_id, off, len, va, tx);
4283                 zfs_unmap_page(pp, va);
4284         } else {
4285                 err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, pp, tx);
4286         }
4287 
4288         if (err == 0) {
4289                 uint64_t mtime[2], ctime[2];
4290                 sa_bulk_attr_t bulk[3];
4291                 int count = 0;
4292 
4293                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
4294                     &mtime, 16);
4295                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
4296                     &ctime, 16);
4297                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
4298                     &zp->z_pflags, 8);
4299                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
4300                     B_TRUE);
4301                 zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len, 0);
4302         }
4303         dmu_tx_commit(tx);
4304 
4305 out:
4306         pvn_write_done(pp, (err ? B_ERROR : 0) | flags);
4307         if (offp)
4308                 *offp = off;
4309         if (lenp)
4310                 *lenp = len;
4311 
4312         return (err);
4313 }
4314 
4315 /*
4316  * Copy the portion of the file indicated from pages into the file.
4317  * The pages are stored in a page list attached to the files vnode.
4318  *
4319  *      IN:     vp      - vnode of file to push page data to.
4320  *              off     - position in file to put data.
4321  *              len     - amount of data to write.
4322  *              flags   - flags to control the operation.
4323  *              cr      - credentials of caller.
4324  *              ct      - caller context.
4325  *
4326  *      RETURN: 0 on success, error code on failure.
4327  *
4328  * Timestamps:
4329  *      vp - ctime|mtime updated
4330  */
4331 /*ARGSUSED*/
4332 static int
4333 zfs_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
4334     caller_context_t *ct)
4335 {
4336         znode_t         *zp = VTOZ(vp);
4337         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4338         page_t          *pp;
4339         size_t          io_len;
4340         u_offset_t      io_off;
4341         uint_t          blksz;
4342         rl_t            *rl;
4343         int             error = 0;
4344 
4345         ZFS_ENTER(zfsvfs);
4346         ZFS_VERIFY_ZP(zp);
4347 
4348         /*
4349          * There's nothing to do if no data is cached.
4350          */
4351         if (!vn_has_cached_data(vp)) {
4352                 ZFS_EXIT(zfsvfs);
4353                 return (0);
4354         }
4355 
4356         /*
4357          * Align this request to the file block size in case we kluster.
4358          * XXX - this can result in pretty aggresive locking, which can
4359          * impact simultanious read/write access.  One option might be
4360          * to break up long requests (len == 0) into block-by-block
4361          * operations to get narrower locking.
4362          */
4363         blksz = zp->z_blksz;
4364         if (ISP2(blksz))
4365                 io_off = P2ALIGN_TYPED(off, blksz, u_offset_t);
4366         else
4367                 io_off = 0;
4368         if (len > 0 && ISP2(blksz))
4369                 io_len = P2ROUNDUP_TYPED(len + (off - io_off), blksz, size_t);
4370         else
4371                 io_len = 0;
4372 
4373         if (io_len == 0) {
4374                 /*
4375                  * Search the entire vp list for pages >= io_off.
4376                  */
4377                 rl = zfs_range_lock(zp, io_off, UINT64_MAX, RL_WRITER);
4378                 error = pvn_vplist_dirty(vp, io_off, zfs_putapage, flags, cr);
4379                 goto out;
4380         }
4381         rl = zfs_range_lock(zp, io_off, io_len, RL_WRITER);
4382 
4383         if (off > zp->z_size) {
4384                 /* past end of file */
4385                 zfs_range_unlock(rl);
4386                 ZFS_EXIT(zfsvfs);
4387                 return (0);
4388         }
4389 
4390         len = MIN(io_len, P2ROUNDUP(zp->z_size, PAGESIZE) - io_off);
4391 
4392         for (off = io_off; io_off < off + len; io_off += io_len) {
4393                 if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
4394                         pp = page_lookup(vp, io_off,
4395                             (flags & (B_INVAL | B_FREE)) ? SE_EXCL : SE_SHARED);
4396                 } else {
4397                         pp = page_lookup_nowait(vp, io_off,
4398                             (flags & B_FREE) ? SE_EXCL : SE_SHARED);
4399                 }
4400 
4401                 if (pp != NULL && pvn_getdirty(pp, flags)) {
4402                         int err;
4403 
4404                         /*
4405                          * Found a dirty page to push
4406                          */
4407                         err = zfs_putapage(vp, pp, &io_off, &io_len, flags, cr);
4408                         if (err)
4409                                 error = err;
4410                 } else {
4411                         io_len = PAGESIZE;
4412                 }
4413         }
4414 out:
4415         zfs_range_unlock(rl);
4416         if ((flags & B_ASYNC) == 0 || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4417                 zil_commit(zfsvfs->z_log, zp->z_id);
4418         ZFS_EXIT(zfsvfs);
4419         return (error);
4420 }
4421 
4422 /*ARGSUSED*/
4423 void
4424 zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4425 {
4426         znode_t *zp = VTOZ(vp);
4427         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4428         int error;
4429 
4430         rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
4431         if (zp->z_sa_hdl == NULL) {
4432                 /*
4433                  * The fs has been unmounted, or we did a
4434                  * suspend/resume and this file no longer exists.
4435                  */
4436                 if (vn_has_cached_data(vp)) {
4437                         (void) pvn_vplist_dirty(vp, 0, zfs_null_putapage,
4438                             B_INVAL, cr);
4439                 }
4440 
4441                 mutex_enter(&zp->z_lock);
4442                 mutex_enter(&vp->v_lock);
4443                 ASSERT(vp->v_count == 1);
4444                 vp->v_count = 0;
4445                 mutex_exit(&vp->v_lock);
4446                 mutex_exit(&zp->z_lock);
4447                 rw_exit(&zfsvfs->z_teardown_inactive_lock);
4448                 zfs_znode_free(zp);
4449                 return;
4450         }
4451 
4452         /*
4453          * Attempt to push any data in the page cache.  If this fails
4454          * we will get kicked out later in zfs_zinactive().
4455          */
4456         if (vn_has_cached_data(vp)) {
4457                 (void) pvn_vplist_dirty(vp, 0, zfs_putapage, B_INVAL|B_ASYNC,
4458                     cr);
4459         }
4460 
4461         if (zp->z_atime_dirty && zp->z_unlinked == 0) {
4462                 dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
4463 
4464                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4465                 zfs_sa_upgrade_txholds(tx, zp);
4466                 error = dmu_tx_assign(tx, TXG_WAIT);
4467                 if (error) {
4468                         dmu_tx_abort(tx);
4469                 } else {
4470                         mutex_enter(&zp->z_lock);
4471                         (void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zfsvfs),
4472                             (void *)&zp->z_atime, sizeof (zp->z_atime), tx);
4473                         zp->z_atime_dirty = 0;
4474                         mutex_exit(&zp->z_lock);
4475                         dmu_tx_commit(tx);
4476                 }
4477         }
4478 
4479         zfs_zinactive(zp);
4480         rw_exit(&zfsvfs->z_teardown_inactive_lock);
4481 }
4482 
4483 /*
4484  * Bounds-check the seek operation.
4485  *
4486  *      IN:     vp      - vnode seeking within
4487  *              ooff    - old file offset
4488  *              noffp   - pointer to new file offset
4489  *              ct      - caller context
4490  *
4491  *      RETURN: 0 on success, EINVAL if new offset invalid.
4492  */
4493 /* ARGSUSED */
4494 static int
4495 zfs_seek(vnode_t *vp, offset_t ooff, offset_t *noffp,
4496     caller_context_t *ct)
4497 {
4498         if (vp->v_type == VDIR)
4499                 return (0);
4500         return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
4501 }
4502 
4503 /*
4504  * Pre-filter the generic locking function to trap attempts to place
4505  * a mandatory lock on a memory mapped file.
4506  */
4507 static int
4508 zfs_frlock(vnode_t *vp, int cmd, flock64_t *bfp, int flag, offset_t offset,
4509     flk_callback_t *flk_cbp, cred_t *cr, caller_context_t *ct)
4510 {
4511         znode_t *zp = VTOZ(vp);
4512         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4513 
4514         ZFS_ENTER(zfsvfs);
4515         ZFS_VERIFY_ZP(zp);
4516 
4517         /*
4518          * We are following the UFS semantics with respect to mapcnt
4519          * here: If we see that the file is mapped already, then we will
4520          * return an error, but we don't worry about races between this
4521          * function and zfs_map().
4522          */
4523         if (zp->z_mapcnt > 0 && MANDMODE(zp->z_mode)) {
4524                 ZFS_EXIT(zfsvfs);
4525                 return (SET_ERROR(EAGAIN));
4526         }
4527         ZFS_EXIT(zfsvfs);
4528         return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
4529 }
4530 
4531 /*
4532  * If we can't find a page in the cache, we will create a new page
4533  * and fill it with file data.  For efficiency, we may try to fill
4534  * multiple pages at once (klustering) to fill up the supplied page
4535  * list.  Note that the pages to be filled are held with an exclusive
4536  * lock to prevent access by other threads while they are being filled.
4537  */
4538 static int
4539 zfs_fillpage(vnode_t *vp, u_offset_t off, struct seg *seg,
4540     caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw)
4541 {
4542         znode_t *zp = VTOZ(vp);
4543         page_t *pp, *cur_pp;
4544         objset_t *os = zp->z_zfsvfs->z_os;
4545         u_offset_t io_off, total;
4546         size_t io_len;
4547         int err;
4548 
4549         if (plsz == PAGESIZE || zp->z_blksz <= PAGESIZE) {
4550                 /*
4551                  * We only have a single page, don't bother klustering
4552                  */
4553                 io_off = off;
4554                 io_len = PAGESIZE;
4555                 pp = page_create_va(vp, io_off, io_len,
4556                     PG_EXCL | PG_WAIT, seg, addr);
4557         } else {
4558                 /*
4559                  * Try to find enough pages to fill the page list
4560                  */
4561                 pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
4562                     &io_len, off, plsz, 0);
4563         }
4564         if (pp == NULL) {
4565                 /*
4566                  * The page already exists, nothing to do here.
4567                  */
4568                 *pl = NULL;
4569                 return (0);
4570         }
4571 
4572         /*
4573          * Fill the pages in the kluster.
4574          */
4575         cur_pp = pp;
4576         for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
4577                 caddr_t va;
4578 
4579                 ASSERT3U(io_off, ==, cur_pp->p_offset);
4580                 va = zfs_map_page(cur_pp, S_WRITE);
4581                 err = dmu_read(os, zp->z_id, io_off, PAGESIZE, va,
4582                     DMU_READ_PREFETCH);
4583                 zfs_unmap_page(cur_pp, va);
4584                 if (err) {
4585                         /* On error, toss the entire kluster */
4586                         pvn_read_done(pp, B_ERROR);
4587                         /* convert checksum errors into IO errors */
4588                         if (err == ECKSUM)
4589                                 err = SET_ERROR(EIO);
4590                         return (err);
4591                 }
4592                 cur_pp = cur_pp->p_next;
4593         }
4594 
4595         /*
4596          * Fill in the page list array from the kluster starting
4597          * from the desired offset `off'.
4598          * NOTE: the page list will always be null terminated.
4599          */
4600         pvn_plist_init(pp, pl, plsz, off, io_len, rw);
4601         ASSERT(pl == NULL || (*pl)->p_offset == off);
4602 
4603         return (0);
4604 }
4605 
4606 /*
4607  * Return pointers to the pages for the file region [off, off + len]
4608  * in the pl array.  If plsz is greater than len, this function may
4609  * also return page pointers from after the specified region
4610  * (i.e. the region [off, off + plsz]).  These additional pages are
4611  * only returned if they are already in the cache, or were created as
4612  * part of a klustered read.
4613  *
4614  *      IN:     vp      - vnode of file to get data from.
4615  *              off     - position in file to get data from.
4616  *              len     - amount of data to retrieve.
4617  *              plsz    - length of provided page list.
4618  *              seg     - segment to obtain pages for.
4619  *              addr    - virtual address of fault.
4620  *              rw      - mode of created pages.
4621  *              cr      - credentials of caller.
4622  *              ct      - caller context.
4623  *
4624  *      OUT:    protp   - protection mode of created pages.
4625  *              pl      - list of pages created.
4626  *
4627  *      RETURN: 0 on success, error code on failure.
4628  *
4629  * Timestamps:
4630  *      vp - atime updated
4631  */
4632 /* ARGSUSED */
4633 static int
4634 zfs_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
4635     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
4636     enum seg_rw rw, cred_t *cr, caller_context_t *ct)
4637 {
4638         znode_t         *zp = VTOZ(vp);
4639         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4640         page_t          **pl0 = pl;
4641         int             err = 0;
4642 
4643         /* we do our own caching, faultahead is unnecessary */
4644         if (pl == NULL)
4645                 return (0);
4646         else if (len > plsz)
4647                 len = plsz;
4648         else
4649                 len = P2ROUNDUP(len, PAGESIZE);
4650         ASSERT(plsz >= len);
4651 
4652         ZFS_ENTER(zfsvfs);
4653         ZFS_VERIFY_ZP(zp);
4654 
4655         if (protp)
4656                 *protp = PROT_ALL;
4657 
4658         /*
4659          * Loop through the requested range [off, off + len) looking
4660          * for pages.  If we don't find a page, we will need to create
4661          * a new page and fill it with data from the file.
4662          */
4663         while (len > 0) {
4664                 if (*pl = page_lookup(vp, off, SE_SHARED))
4665                         *(pl+1) = NULL;
4666                 else if (err = zfs_fillpage(vp, off, seg, addr, pl, plsz, rw))
4667                         goto out;
4668                 while (*pl) {
4669                         ASSERT3U((*pl)->p_offset, ==, off);
4670                         off += PAGESIZE;
4671                         addr += PAGESIZE;
4672                         if (len > 0) {
4673                                 ASSERT3U(len, >=, PAGESIZE);
4674                                 len -= PAGESIZE;
4675                         }
4676                         ASSERT3U(plsz, >=, PAGESIZE);
4677                         plsz -= PAGESIZE;
4678                         pl++;
4679                 }
4680         }
4681 
4682         /*
4683          * Fill out the page array with any pages already in the cache.
4684          */
4685         while (plsz > 0 &&
4686             (*pl++ = page_lookup_nowait(vp, off, SE_SHARED))) {
4687                         off += PAGESIZE;
4688                         plsz -= PAGESIZE;
4689         }
4690 out:
4691         if (err) {
4692                 /*
4693                  * Release any pages we have previously locked.
4694                  */
4695                 while (pl > pl0)
4696                         page_unlock(*--pl);
4697         } else {
4698                 ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4699         }
4700 
4701         *pl = NULL;
4702 
4703         ZFS_EXIT(zfsvfs);
4704         return (err);
4705 }
4706 
4707 /*
4708  * Request a memory map for a section of a file.  This code interacts
4709  * with common code and the VM system as follows:
4710  *
4711  * - common code calls mmap(), which ends up in smmap_common()
4712  * - this calls VOP_MAP(), which takes you into (say) zfs
4713  * - zfs_map() calls as_map(), passing segvn_create() as the callback
4714  * - segvn_create() creates the new segment and calls VOP_ADDMAP()
4715  * - zfs_addmap() updates z_mapcnt
4716  */
4717 /*ARGSUSED*/
4718 static int
4719 zfs_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
4720     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4721     caller_context_t *ct)
4722 {
4723         znode_t *zp = VTOZ(vp);
4724         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4725         segvn_crargs_t  vn_a;
4726         int             error;
4727 
4728         ZFS_ENTER(zfsvfs);
4729         ZFS_VERIFY_ZP(zp);
4730 
4731         if ((prot & PROT_WRITE) && (zp->z_pflags &
4732             (ZFS_IMMUTABLE | ZFS_READONLY | ZFS_APPENDONLY))) {
4733                 ZFS_EXIT(zfsvfs);
4734                 return (SET_ERROR(EPERM));
4735         }
4736 
4737         if ((prot & (PROT_READ | PROT_EXEC)) &&
4738             (zp->z_pflags & ZFS_AV_QUARANTINED)) {
4739                 ZFS_EXIT(zfsvfs);
4740                 return (SET_ERROR(EACCES));
4741         }
4742 
4743         if (vp->v_flag & VNOMAP) {
4744                 ZFS_EXIT(zfsvfs);
4745                 return (SET_ERROR(ENOSYS));
4746         }
4747 
4748         if (off < 0 || len > MAXOFFSET_T - off) {
4749                 ZFS_EXIT(zfsvfs);
4750                 return (SET_ERROR(ENXIO));
4751         }
4752 
4753         if (vp->v_type != VREG) {
4754                 ZFS_EXIT(zfsvfs);
4755                 return (SET_ERROR(ENODEV));
4756         }
4757 
4758         /*
4759          * If file is locked, disallow mapping.
4760          */
4761         if (MANDMODE(zp->z_mode) && vn_has_flocks(vp)) {
4762                 ZFS_EXIT(zfsvfs);
4763                 return (SET_ERROR(EAGAIN));
4764         }
4765 
4766         as_rangelock(as);
4767         error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
4768         if (error != 0) {
4769                 as_rangeunlock(as);
4770                 ZFS_EXIT(zfsvfs);
4771                 return (error);
4772         }
4773 
4774         vn_a.vp = vp;
4775         vn_a.offset = (u_offset_t)off;
4776         vn_a.type = flags & MAP_TYPE;
4777         vn_a.prot = prot;
4778         vn_a.maxprot = maxprot;
4779         vn_a.cred = cr;
4780         vn_a.amp = NULL;
4781         vn_a.flags = flags & ~MAP_TYPE;
4782         vn_a.szc = 0;
4783         vn_a.lgrp_mem_policy_flags = 0;
4784 
4785         error = as_map(as, *addrp, len, segvn_create, &vn_a);
4786 
4787         as_rangeunlock(as);
4788         ZFS_EXIT(zfsvfs);
4789         return (error);
4790 }
4791 
4792 /* ARGSUSED */
4793 static int
4794 zfs_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4795     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4796     caller_context_t *ct)
4797 {
4798         uint64_t pages = btopr(len);
4799 
4800         atomic_add_64(&VTOZ(vp)->z_mapcnt, pages);
4801         return (0);
4802 }
4803 
4804 /*
4805  * The reason we push dirty pages as part of zfs_delmap() is so that we get a
4806  * more accurate mtime for the associated file.  Since we don't have a way of
4807  * detecting when the data was actually modified, we have to resort to
4808  * heuristics.  If an explicit msync() is done, then we mark the mtime when the
4809  * last page is pushed.  The problem occurs when the msync() call is omitted,
4810  * which by far the most common case:
4811  *
4812  *      open()
4813  *      mmap()
4814  *      <modify memory>
4815  *      munmap()
4816  *      close()
4817  *      <time lapse>
4818  *      putpage() via fsflush
4819  *
4820  * If we wait until fsflush to come along, we can have a modification time that
4821  * is some arbitrary point in the future.  In order to prevent this in the
4822  * common case, we flush pages whenever a (MAP_SHARED, PROT_WRITE) mapping is
4823  * torn down.
4824  */
4825 /* ARGSUSED */
4826 static int
4827 zfs_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4828     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
4829     caller_context_t *ct)
4830 {
4831         uint64_t pages = btopr(len);
4832 
4833         ASSERT3U(VTOZ(vp)->z_mapcnt, >=, pages);
4834         atomic_add_64(&VTOZ(vp)->z_mapcnt, -pages);
4835 
4836         if ((flags & MAP_SHARED) && (prot & PROT_WRITE) &&
4837             vn_has_cached_data(vp))
4838                 (void) VOP_PUTPAGE(vp, off, len, B_ASYNC, cr, ct);
4839 
4840         return (0);
4841 }
4842 
4843 /*
4844  * Free or allocate space in a file.  Currently, this function only
4845  * supports the `F_FREESP' command.  However, this command is somewhat
4846  * misnamed, as its functionality includes the ability to allocate as
4847  * well as free space.
4848  *
4849  *      IN:     vp      - vnode of file to free data in.
4850  *              cmd     - action to take (only F_FREESP supported).
4851  *              bfp     - section of file to free/alloc.
4852  *              flag    - current file open mode flags.
4853  *              offset  - current file offset.
4854  *              cr      - credentials of caller [UNUSED].
4855  *              ct      - caller context.
4856  *
4857  *      RETURN: 0 on success, error code on failure.
4858  *
4859  * Timestamps:
4860  *      vp - ctime|mtime updated
4861  */
4862 /* ARGSUSED */
4863 static int
4864 zfs_space(vnode_t *vp, int cmd, flock64_t *bfp, int flag,
4865     offset_t offset, cred_t *cr, caller_context_t *ct)
4866 {
4867         znode_t         *zp = VTOZ(vp);
4868         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4869         uint64_t        off, len;
4870         int             error;
4871 
4872         ZFS_ENTER(zfsvfs);
4873         ZFS_VERIFY_ZP(zp);
4874 
4875         if (cmd != F_FREESP) {
4876                 ZFS_EXIT(zfsvfs);
4877                 return (SET_ERROR(EINVAL));
4878         }
4879 
4880         /*
4881          * In a case vp->v_vfsp != zp->z_zfsvfs->z_vfs (e.g. snapshots) our
4882          * callers might not be able to detect properly that we are read-only,
4883          * so check it explicitly here.
4884          */
4885         if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
4886                 ZFS_EXIT(zfsvfs);
4887                 return (SET_ERROR(EROFS));
4888         }
4889 
4890         if (error = convoff(vp, bfp, 0, offset)) {
4891                 ZFS_EXIT(zfsvfs);
4892                 return (error);
4893         }
4894 
4895         if (bfp->l_len < 0) {
4896                 ZFS_EXIT(zfsvfs);
4897                 return (SET_ERROR(EINVAL));
4898         }
4899 
4900         off = bfp->l_start;
4901         len = bfp->l_len; /* 0 means from off to end of file */
4902 
4903         error = zfs_freesp(zp, off, len, flag, TRUE);
4904 
4905         if (error == 0 && off == 0 && len == 0)
4906                 vnevent_truncate(ZTOV(zp), ct);
4907 
4908         ZFS_EXIT(zfsvfs);
4909         return (error);
4910 }
4911 
4912 /*ARGSUSED*/
4913 static int
4914 zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
4915 {
4916         znode_t         *zp = VTOZ(vp);
4917         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4918         uint32_t        gen;
4919         uint64_t        gen64;
4920         uint64_t        object = zp->z_id;
4921         zfid_short_t    *zfid;
4922         int             size, i, error;
4923 
4924         ZFS_ENTER(zfsvfs);
4925         ZFS_VERIFY_ZP(zp);
4926 
4927         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs),
4928             &gen64, sizeof (uint64_t))) != 0) {
4929                 ZFS_EXIT(zfsvfs);
4930                 return (error);
4931         }
4932 
4933         gen = (uint32_t)gen64;
4934 
4935         size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
4936         if (fidp->fid_len < size) {
4937                 fidp->fid_len = size;
4938                 ZFS_EXIT(zfsvfs);
4939                 return (SET_ERROR(ENOSPC));
4940         }
4941 
4942         zfid = (zfid_short_t *)fidp;
4943 
4944         zfid->zf_len = size;
4945 
4946         for (i = 0; i < sizeof (zfid->zf_object); i++)
4947                 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
4948 
4949         /* Must have a non-zero generation number to distinguish from .zfs */
4950         if (gen == 0)
4951                 gen = 1;
4952         for (i = 0; i < sizeof (zfid->zf_gen); i++)
4953                 zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
4954 
4955         if (size == LONG_FID_LEN) {
4956                 uint64_t        objsetid = dmu_objset_id(zfsvfs->z_os);
4957                 zfid_long_t     *zlfid;
4958 
4959                 zlfid = (zfid_long_t *)fidp;
4960 
4961                 for (i = 0; i < sizeof (zlfid->zf_setid); i++)
4962                         zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
4963 
4964                 /* XXX - this should be the generation number for the objset */
4965                 for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
4966                         zlfid->zf_setgen[i] = 0;
4967         }
4968 
4969         ZFS_EXIT(zfsvfs);
4970         return (0);
4971 }
4972 
4973 static int
4974 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
4975     caller_context_t *ct)
4976 {
4977         znode_t         *zp, *xzp;
4978         zfsvfs_t        *zfsvfs;
4979         zfs_dirlock_t   *dl;
4980         int             error;
4981 
4982         switch (cmd) {
4983         case _PC_LINK_MAX:
4984                 *valp = ULONG_MAX;
4985                 return (0);
4986 
4987         case _PC_FILESIZEBITS:
4988                 *valp = 64;
4989                 return (0);
4990 
4991         case _PC_XATTR_EXISTS:
4992                 zp = VTOZ(vp);
4993                 zfsvfs = zp->z_zfsvfs;
4994                 ZFS_ENTER(zfsvfs);
4995                 ZFS_VERIFY_ZP(zp);
4996                 *valp = 0;
4997                 error = zfs_dirent_lock(&dl, zp, "", &xzp,
4998                     ZXATTR | ZEXISTS | ZSHARED, NULL, NULL);
4999                 if (error == 0) {
5000                         zfs_dirent_unlock(dl);
5001                         if (!zfs_dirempty(xzp))
5002                                 *valp = 1;
5003                         VN_RELE(ZTOV(xzp));
5004                 } else if (error == ENOENT) {
5005                         /*
5006                          * If there aren't extended attributes, it's the
5007                          * same as having zero of them.
5008                          */
5009                         error = 0;
5010                 }
5011                 ZFS_EXIT(zfsvfs);
5012                 return (error);
5013 
5014         case _PC_SATTR_ENABLED:
5015         case _PC_SATTR_EXISTS:
5016                 *valp = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
5017                     (vp->v_type == VREG || vp->v_type == VDIR);
5018                 return (0);
5019 
5020         case _PC_ACCESS_FILTERING:
5021                 *valp = vfs_has_feature(vp->v_vfsp, VFSFT_ACCESS_FILTER) &&
5022                     vp->v_type == VDIR;
5023                 return (0);
5024 
5025         case _PC_ACL_ENABLED:
5026                 *valp = _ACL_ACE_ENABLED;
5027                 return (0);
5028 
5029         case _PC_MIN_HOLE_SIZE:
5030                 *valp = (ulong_t)SPA_MINBLOCKSIZE;
5031                 return (0);
5032 
5033         case _PC_TIMESTAMP_RESOLUTION:
5034                 /* nanosecond timestamp resolution */
5035                 *valp = 1L;
5036                 return (0);
5037 
5038         default:
5039                 return (fs_pathconf(vp, cmd, valp, cr, ct));
5040         }
5041 }
5042 
5043 /*ARGSUSED*/
5044 static int
5045 zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5046     caller_context_t *ct)
5047 {
5048         znode_t *zp = VTOZ(vp);
5049         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5050         int error;
5051         boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5052 
5053         ZFS_ENTER(zfsvfs);
5054         ZFS_VERIFY_ZP(zp);
5055         error = zfs_getacl(zp, vsecp, skipaclchk, cr);
5056         ZFS_EXIT(zfsvfs);
5057 
5058         return (error);
5059 }
5060 
5061 /*ARGSUSED*/
5062 static int
5063 zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5064     caller_context_t *ct)
5065 {
5066         znode_t *zp = VTOZ(vp);
5067         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5068         int error;
5069         boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5070         zilog_t *zilog = zfsvfs->z_log;
5071 
5072         ZFS_ENTER(zfsvfs);
5073         ZFS_VERIFY_ZP(zp);
5074 
5075         error = zfs_setacl(zp, vsecp, skipaclchk, cr);
5076 
5077         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
5078                 zil_commit(zilog, 0);
5079 
5080         ZFS_EXIT(zfsvfs);
5081         return (error);
5082 }
5083 
5084 /*
5085  * The smallest read we may consider to loan out an arcbuf.
5086  * This must be a power of 2.
5087  */
5088 int zcr_blksz_min = (1 << 10);    /* 1K */
5089 /*
5090  * If set to less than the file block size, allow loaning out of an
5091  * arcbuf for a partial block read.  This must be a power of 2.
5092  */
5093 int zcr_blksz_max = (1 << 17);    /* 128K */
5094 
5095 /*ARGSUSED*/
5096 static int
5097 zfs_reqzcbuf(vnode_t *vp, enum uio_rw ioflag, xuio_t *xuio, cred_t *cr,
5098     caller_context_t *ct)
5099 {
5100         znode_t *zp = VTOZ(vp);
5101         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5102         int max_blksz = zfsvfs->z_max_blksz;
5103         uio_t *uio = &xuio->xu_uio;
5104         ssize_t size = uio->uio_resid;
5105         offset_t offset = uio->uio_loffset;
5106         int blksz;
5107         int fullblk, i;
5108         arc_buf_t *abuf;
5109         ssize_t maxsize;
5110         int preamble, postamble;
5111 
5112         if (xuio->xu_type != UIOTYPE_ZEROCOPY)
5113                 return (SET_ERROR(EINVAL));
5114 
5115         ZFS_ENTER(zfsvfs);
5116         ZFS_VERIFY_ZP(zp);
5117         switch (ioflag) {
5118         case UIO_WRITE:
5119                 /*
5120                  * Loan out an arc_buf for write if write size is bigger than
5121                  * max_blksz, and the file's block size is also max_blksz.
5122                  */
5123                 blksz = max_blksz;
5124                 if (size < blksz || zp->z_blksz != blksz) {
5125                         ZFS_EXIT(zfsvfs);
5126                         return (SET_ERROR(EINVAL));
5127                 }
5128                 /*
5129                  * Caller requests buffers for write before knowing where the
5130                  * write offset might be (e.g. NFS TCP write).
5131                  */
5132                 if (offset == -1) {
5133                         preamble = 0;
5134                 } else {
5135                         preamble = P2PHASE(offset, blksz);
5136                         if (preamble) {
5137                                 preamble = blksz - preamble;
5138                                 size -= preamble;
5139                         }
5140                 }
5141 
5142                 postamble = P2PHASE(size, blksz);
5143                 size -= postamble;
5144 
5145                 fullblk = size / blksz;
5146                 (void) dmu_xuio_init(xuio,
5147                     (preamble != 0) + fullblk + (postamble != 0));
5148                 DTRACE_PROBE3(zfs_reqzcbuf_align, int, preamble,
5149                     int, postamble, int,
5150                     (preamble != 0) + fullblk + (postamble != 0));
5151 
5152                 /*
5153                  * Have to fix iov base/len for partial buffers.  They
5154                  * currently represent full arc_buf's.
5155                  */
5156                 if (preamble) {
5157                         /* data begins in the middle of the arc_buf */
5158                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5159                             blksz);
5160                         ASSERT(abuf);
5161                         (void) dmu_xuio_add(xuio, abuf,
5162                             blksz - preamble, preamble);
5163                 }
5164 
5165                 for (i = 0; i < fullblk; i++) {
5166                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5167                             blksz);
5168                         ASSERT(abuf);
5169                         (void) dmu_xuio_add(xuio, abuf, 0, blksz);
5170                 }
5171 
5172                 if (postamble) {
5173                         /* data ends in the middle of the arc_buf */
5174                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5175                             blksz);
5176                         ASSERT(abuf);
5177                         (void) dmu_xuio_add(xuio, abuf, 0, postamble);
5178                 }
5179                 break;
5180         case UIO_READ:
5181                 /*
5182                  * Loan out an arc_buf for read if the read size is larger than
5183                  * the current file block size.  Block alignment is not
5184                  * considered.  Partial arc_buf will be loaned out for read.
5185                  */
5186                 blksz = zp->z_blksz;
5187                 if (blksz < zcr_blksz_min)
5188                         blksz = zcr_blksz_min;
5189                 if (blksz > zcr_blksz_max)
5190                         blksz = zcr_blksz_max;
5191                 /* avoid potential complexity of dealing with it */
5192                 if (blksz > max_blksz) {
5193                         ZFS_EXIT(zfsvfs);
5194                         return (SET_ERROR(EINVAL));
5195                 }
5196 
5197                 maxsize = zp->z_size - uio->uio_loffset;
5198                 if (size > maxsize)
5199                         size = maxsize;
5200 
5201                 if (size < blksz || vn_has_cached_data(vp)) {
5202                         ZFS_EXIT(zfsvfs);
5203                         return (SET_ERROR(EINVAL));
5204                 }
5205                 break;
5206         default:
5207                 ZFS_EXIT(zfsvfs);
5208                 return (SET_ERROR(EINVAL));
5209         }
5210 
5211         uio->uio_extflg = UIO_XUIO;
5212         XUIO_XUZC_RW(xuio) = ioflag;
5213         ZFS_EXIT(zfsvfs);
5214         return (0);
5215 }
5216 
5217 /*ARGSUSED*/
5218 static int
5219 zfs_retzcbuf(vnode_t *vp, xuio_t *xuio, cred_t *cr, caller_context_t *ct)
5220 {
5221         int i;
5222         arc_buf_t *abuf;
5223         int ioflag = XUIO_XUZC_RW(xuio);
5224 
5225         ASSERT(xuio->xu_type == UIOTYPE_ZEROCOPY);
5226 
5227         i = dmu_xuio_cnt(xuio);
5228         while (i-- > 0) {
5229                 abuf = dmu_xuio_arcbuf(xuio, i);
5230                 /*
5231                  * if abuf == NULL, it must be a write buffer
5232                  * that has been returned in zfs_write().
5233                  */
5234                 if (abuf)
5235                         dmu_return_arcbuf(abuf);
5236                 ASSERT(abuf || ioflag == UIO_WRITE);
5237         }
5238 
5239         dmu_xuio_fini(xuio);
5240         return (0);
5241 }
5242 
5243 /*
5244  * Predeclare these here so that the compiler assumes that
5245  * this is an "old style" function declaration that does
5246  * not include arguments => we won't get type mismatch errors
5247  * in the initializations that follow.
5248  */
5249 static int zfs_inval();
5250 static int zfs_isdir();
5251 
5252 static int
5253 zfs_inval()
5254 {
5255         return (SET_ERROR(EINVAL));
5256 }
5257 
5258 static int
5259 zfs_isdir()
5260 {
5261         return (SET_ERROR(EISDIR));
5262 }
5263 /*
5264  * Directory vnode operations template
5265  */
5266 vnodeops_t *zfs_dvnodeops;
5267 const fs_operation_def_t zfs_dvnodeops_template[] = {
5268         VOPNAME_OPEN,           { .vop_open = zfs_open },
5269         VOPNAME_CLOSE,          { .vop_close = zfs_close },
5270         VOPNAME_READ,           { .error = zfs_isdir },
5271         VOPNAME_WRITE,          { .error = zfs_isdir },
5272         VOPNAME_IOCTL,          { .vop_ioctl = zfs_ioctl },
5273         VOPNAME_GETATTR,        { .vop_getattr = zfs_getattr },
5274         VOPNAME_SETATTR,        { .vop_setattr = zfs_setattr },
5275         VOPNAME_ACCESS,         { .vop_access = zfs_access },
5276         VOPNAME_LOOKUP,         { .vop_lookup = zfs_lookup },
5277         VOPNAME_CREATE,         { .vop_create = zfs_create },
5278         VOPNAME_REMOVE,         { .vop_remove = zfs_remove },
5279         VOPNAME_LINK,           { .vop_link = zfs_link },
5280         VOPNAME_RENAME,         { .vop_rename = zfs_rename },
5281         VOPNAME_MKDIR,          { .vop_mkdir = zfs_mkdir },
5282         VOPNAME_RMDIR,          { .vop_rmdir = zfs_rmdir },
5283         VOPNAME_READDIR,        { .vop_readdir = zfs_readdir },
5284         VOPNAME_SYMLINK,        { .vop_symlink = zfs_symlink },
5285         VOPNAME_FSYNC,          { .vop_fsync = zfs_fsync },
5286         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5287         VOPNAME_FID,            { .vop_fid = zfs_fid },
5288         VOPNAME_SEEK,           { .vop_seek = zfs_seek },
5289         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5290         VOPNAME_GETSECATTR,     { .vop_getsecattr = zfs_getsecattr },
5291         VOPNAME_SETSECATTR,     { .vop_setsecattr = zfs_setsecattr },
5292         VOPNAME_VNEVENT,        { .vop_vnevent = fs_vnevent_support },
5293         NULL,                   NULL
5294 };
5295 
5296 /*
5297  * Regular file vnode operations template
5298  */
5299 vnodeops_t *zfs_fvnodeops;
5300 const fs_operation_def_t zfs_fvnodeops_template[] = {
5301         VOPNAME_OPEN,           { .vop_open = zfs_open },
5302         VOPNAME_CLOSE,          { .vop_close = zfs_close },
5303         VOPNAME_READ,           { .vop_read = zfs_read },
5304         VOPNAME_WRITE,          { .vop_write = zfs_write },
5305         VOPNAME_IOCTL,          { .vop_ioctl = zfs_ioctl },
5306         VOPNAME_GETATTR,        { .vop_getattr = zfs_getattr },
5307         VOPNAME_SETATTR,        { .vop_setattr = zfs_setattr },
5308         VOPNAME_ACCESS,         { .vop_access = zfs_access },
5309         VOPNAME_LOOKUP,         { .vop_lookup = zfs_lookup },
5310         VOPNAME_RENAME,         { .vop_rename = zfs_rename },
5311         VOPNAME_FSYNC,          { .vop_fsync = zfs_fsync },
5312         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5313         VOPNAME_FID,            { .vop_fid = zfs_fid },
5314         VOPNAME_SEEK,           { .vop_seek = zfs_seek },
5315         VOPNAME_FRLOCK,         { .vop_frlock = zfs_frlock },
5316         VOPNAME_SPACE,          { .vop_space = zfs_space },
5317         VOPNAME_GETPAGE,        { .vop_getpage = zfs_getpage },
5318         VOPNAME_PUTPAGE,        { .vop_putpage = zfs_putpage },
5319         VOPNAME_MAP,            { .vop_map = zfs_map },
5320         VOPNAME_ADDMAP,         { .vop_addmap = zfs_addmap },
5321         VOPNAME_DELMAP,         { .vop_delmap = zfs_delmap },
5322         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5323         VOPNAME_GETSECATTR,     { .vop_getsecattr = zfs_getsecattr },
5324         VOPNAME_SETSECATTR,     { .vop_setsecattr = zfs_setsecattr },
5325         VOPNAME_VNEVENT,        { .vop_vnevent = fs_vnevent_support },
5326         VOPNAME_REQZCBUF,       { .vop_reqzcbuf = zfs_reqzcbuf },
5327         VOPNAME_RETZCBUF,       { .vop_retzcbuf = zfs_retzcbuf },
5328         NULL,                   NULL
5329 };
5330 
5331 /*
5332  * Symbolic link vnode operations template
5333  */
5334 vnodeops_t *zfs_symvnodeops;
5335 const fs_operation_def_t zfs_symvnodeops_template[] = {
5336         VOPNAME_GETATTR,        { .vop_getattr = zfs_getattr },
5337         VOPNAME_SETATTR,        { .vop_setattr = zfs_setattr },
5338         VOPNAME_ACCESS,         { .vop_access = zfs_access },
5339         VOPNAME_RENAME,         { .vop_rename = zfs_rename },
5340         VOPNAME_READLINK,       { .vop_readlink = zfs_readlink },
5341         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5342         VOPNAME_FID,            { .vop_fid = zfs_fid },
5343         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5344         VOPNAME_VNEVENT,        { .vop_vnevent = fs_vnevent_support },
5345         NULL,                   NULL
5346 };
5347 
5348 /*
5349  * special share hidden files vnode operations template
5350  */
5351 vnodeops_t *zfs_sharevnodeops;
5352 const fs_operation_def_t zfs_sharevnodeops_template[] = {
5353         VOPNAME_GETATTR,        { .vop_getattr = zfs_getattr },
5354         VOPNAME_ACCESS,         { .vop_access = zfs_access },
5355         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5356         VOPNAME_FID,            { .vop_fid = zfs_fid },
5357         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5358         VOPNAME_GETSECATTR,     { .vop_getsecattr = zfs_getsecattr },
5359         VOPNAME_SETSECATTR,     { .vop_setsecattr = zfs_setsecattr },
5360         VOPNAME_VNEVENT,        { .vop_vnevent = fs_vnevent_support },
5361         NULL,                   NULL
5362 };
5363 
5364 /*
5365  * Extended attribute directory vnode operations template
5366  *
5367  * This template is identical to the directory vnodes
5368  * operation template except for restricted operations:
5369  *      VOP_MKDIR()
5370  *      VOP_SYMLINK()
5371  *
5372  * Note that there are other restrictions embedded in:
5373  *      zfs_create()    - restrict type to VREG
5374  *      zfs_link()      - no links into/out of attribute space
5375  *      zfs_rename()    - no moves into/out of attribute space
5376  */
5377 vnodeops_t *zfs_xdvnodeops;
5378 const fs_operation_def_t zfs_xdvnodeops_template[] = {
5379         VOPNAME_OPEN,           { .vop_open = zfs_open },
5380         VOPNAME_CLOSE,          { .vop_close = zfs_close },
5381         VOPNAME_IOCTL,          { .vop_ioctl = zfs_ioctl },
5382         VOPNAME_GETATTR,        { .vop_getattr = zfs_getattr },
5383         VOPNAME_SETATTR,        { .vop_setattr = zfs_setattr },
5384         VOPNAME_ACCESS,         { .vop_access = zfs_access },
5385         VOPNAME_LOOKUP,         { .vop_lookup = zfs_lookup },
5386         VOPNAME_CREATE,         { .vop_create = zfs_create },
5387         VOPNAME_REMOVE,         { .vop_remove = zfs_remove },
5388         VOPNAME_LINK,           { .vop_link = zfs_link },
5389         VOPNAME_RENAME,         { .vop_rename = zfs_rename },
5390         VOPNAME_MKDIR,          { .error = zfs_inval },
5391         VOPNAME_RMDIR,          { .vop_rmdir = zfs_rmdir },
5392         VOPNAME_READDIR,        { .vop_readdir = zfs_readdir },
5393         VOPNAME_SYMLINK,        { .error = zfs_inval },
5394         VOPNAME_FSYNC,          { .vop_fsync = zfs_fsync },
5395         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5396         VOPNAME_FID,            { .vop_fid = zfs_fid },
5397         VOPNAME_SEEK,           { .vop_seek = zfs_seek },
5398         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5399         VOPNAME_GETSECATTR,     { .vop_getsecattr = zfs_getsecattr },
5400         VOPNAME_SETSECATTR,     { .vop_setsecattr = zfs_setsecattr },
5401         VOPNAME_VNEVENT,        { .vop_vnevent = fs_vnevent_support },
5402         NULL,                   NULL
5403 };
5404 
5405 /*
5406  * Error vnode operations template
5407  */
5408 vnodeops_t *zfs_evnodeops;
5409 const fs_operation_def_t zfs_evnodeops_template[] = {
5410         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5411         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5412         NULL,                   NULL
5413 };