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