]> CyberLeo.Net >> Repos - FreeBSD/releng/9.1.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
[SA-14:24] Fix denial of service attack against sshd(8).
[FreeBSD/releng/9.1.git] / sys / cddl / contrib / opensolaris / uts / common / fs / 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 #include <sys/types.h>
29 #include <sys/param.h>
30 #include <sys/time.h>
31 #include <sys/systm.h>
32 #include <sys/sysmacros.h>
33 #include <sys/resource.h>
34 #include <sys/vfs.h>
35 #include <sys/vnode.h>
36 #include <sys/file.h>
37 #include <sys/stat.h>
38 #include <sys/kmem.h>
39 #include <sys/taskq.h>
40 #include <sys/uio.h>
41 #include <sys/atomic.h>
42 #include <sys/namei.h>
43 #include <sys/mman.h>
44 #include <sys/cmn_err.h>
45 #include <sys/errno.h>
46 #include <sys/unistd.h>
47 #include <sys/zfs_dir.h>
48 #include <sys/zfs_ioctl.h>
49 #include <sys/fs/zfs.h>
50 #include <sys/dmu.h>
51 #include <sys/dmu_objset.h>
52 #include <sys/spa.h>
53 #include <sys/txg.h>
54 #include <sys/dbuf.h>
55 #include <sys/zap.h>
56 #include <sys/sa.h>
57 #include <sys/dirent.h>
58 #include <sys/policy.h>
59 #include <sys/sunddi.h>
60 #include <sys/filio.h>
61 #include <sys/sid.h>
62 #include <sys/zfs_ctldir.h>
63 #include <sys/zfs_fuid.h>
64 #include <sys/zfs_sa.h>
65 #include <sys/dnlc.h>
66 #include <sys/zfs_rlock.h>
67 #include <sys/extdirent.h>
68 #include <sys/kidmap.h>
69 #include <sys/bio.h>
70 #include <sys/buf.h>
71 #include <sys/sf_buf.h>
72 #include <sys/sched.h>
73 #include <sys/acl.h>
74 #include <vm/vm_pageout.h>
75
76 /*
77  * Programming rules.
78  *
79  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
80  * properly lock its in-core state, create a DMU transaction, do the work,
81  * record this work in the intent log (ZIL), commit the DMU transaction,
82  * and wait for the intent log to commit if it is a synchronous operation.
83  * Moreover, the vnode ops must work in both normal and log replay context.
84  * The ordering of events is important to avoid deadlocks and references
85  * to freed memory.  The example below illustrates the following Big Rules:
86  *
87  *  (1) A check must be made in each zfs thread for a mounted file system.
88  *      This is done avoiding races using ZFS_ENTER(zfsvfs).
89  *      A ZFS_EXIT(zfsvfs) is needed before all returns.  Any znodes
90  *      must be checked with ZFS_VERIFY_ZP(zp).  Both of these macros
91  *      can return EIO from the calling function.
92  *
93  *  (2) VN_RELE() should always be the last thing except for zil_commit()
94  *      (if necessary) and ZFS_EXIT(). This is for 3 reasons:
95  *      First, if it's the last reference, the vnode/znode
96  *      can be freed, so the zp may point to freed memory.  Second, the last
97  *      reference will call zfs_zinactive(), which may induce a lot of work --
98  *      pushing cached pages (which acquires range locks) and syncing out
99  *      cached atime changes.  Third, zfs_zinactive() may require a new tx,
100  *      which could deadlock the system if you were already holding one.
101  *      If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
102  *
103  *  (3) All range locks must be grabbed before calling dmu_tx_assign(),
104  *      as they can span dmu_tx_assign() calls.
105  *
106  *  (4) Always pass TXG_NOWAIT as the second argument to dmu_tx_assign().
107  *      This is critical because we don't want to block while holding locks.
108  *      Note, in particular, that if a lock is sometimes acquired before
109  *      the tx assigns, and sometimes after (e.g. z_lock), then failing to
110  *      use a non-blocking assign can deadlock the system.  The scenario:
111  *
112  *      Thread A has grabbed a lock before calling dmu_tx_assign().
113  *      Thread B is in an already-assigned tx, and blocks for this lock.
114  *      Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
115  *      forever, because the previous txg can't quiesce until B's tx commits.
116  *
117  *      If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
118  *      then drop all locks, call dmu_tx_wait(), and try again.
119  *
120  *  (5) If the operation succeeded, generate the intent log entry for it
121  *      before dropping locks.  This ensures that the ordering of events
122  *      in the intent log matches the order in which they actually occurred.
123  *      During ZIL replay the zfs_log_* functions will update the sequence
124  *      number to indicate the zil transaction has replayed.
125  *
126  *  (6) At the end of each vnode op, the DMU tx must always commit,
127  *      regardless of whether there were any errors.
128  *
129  *  (7) After dropping all locks, invoke zil_commit(zilog, foid)
130  *      to ensure that synchronous semantics are provided when necessary.
131  *
132  * In general, this is how things should be ordered in each vnode op:
133  *
134  *      ZFS_ENTER(zfsvfs);              // exit if unmounted
135  * top:
136  *      zfs_dirent_lock(&dl, ...)       // lock directory entry (may VN_HOLD())
137  *      rw_enter(...);                  // grab any other locks you need
138  *      tx = dmu_tx_create(...);        // get DMU tx
139  *      dmu_tx_hold_*();                // hold each object you might modify
140  *      error = dmu_tx_assign(tx, TXG_NOWAIT);  // try to assign
141  *      if (error) {
142  *              rw_exit(...);           // drop locks
143  *              zfs_dirent_unlock(dl);  // unlock directory entry
144  *              VN_RELE(...);           // release held vnodes
145  *              if (error == ERESTART) {
146  *                      dmu_tx_wait(tx);
147  *                      dmu_tx_abort(tx);
148  *                      goto top;
149  *              }
150  *              dmu_tx_abort(tx);       // abort DMU tx
151  *              ZFS_EXIT(zfsvfs);       // finished in zfs
152  *              return (error);         // really out of space
153  *      }
154  *      error = do_real_work();         // do whatever this VOP does
155  *      if (error == 0)
156  *              zfs_log_*(...);         // on success, make ZIL entry
157  *      dmu_tx_commit(tx);              // commit DMU tx -- error or not
158  *      rw_exit(...);                   // drop locks
159  *      zfs_dirent_unlock(dl);          // unlock directory entry
160  *      VN_RELE(...);                   // release held vnodes
161  *      zil_commit(zilog, foid);        // synchronous when necessary
162  *      ZFS_EXIT(zfsvfs);               // finished in zfs
163  *      return (error);                 // done, report error
164  */
165
166 /* ARGSUSED */
167 static int
168 zfs_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
169 {
170         znode_t *zp = VTOZ(*vpp);
171         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
172
173         ZFS_ENTER(zfsvfs);
174         ZFS_VERIFY_ZP(zp);
175
176         if ((flag & FWRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
177             ((flag & FAPPEND) == 0)) {
178                 ZFS_EXIT(zfsvfs);
179                 return (EPERM);
180         }
181
182         if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
183             ZTOV(zp)->v_type == VREG &&
184             !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0) {
185                 if (fs_vscan(*vpp, cr, 0) != 0) {
186                         ZFS_EXIT(zfsvfs);
187                         return (EACCES);
188                 }
189         }
190
191         /* Keep a count of the synchronous opens in the znode */
192         if (flag & (FSYNC | FDSYNC))
193                 atomic_inc_32(&zp->z_sync_cnt);
194
195         ZFS_EXIT(zfsvfs);
196         return (0);
197 }
198
199 /* ARGSUSED */
200 static int
201 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
202     caller_context_t *ct)
203 {
204         znode_t *zp = VTOZ(vp);
205         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
206
207         /*
208          * Clean up any locks held by this process on the vp.
209          */
210         cleanlocks(vp, ddi_get_pid(), 0);
211         cleanshares(vp, ddi_get_pid());
212
213         ZFS_ENTER(zfsvfs);
214         ZFS_VERIFY_ZP(zp);
215
216         /* Decrement the synchronous opens in the znode */
217         if ((flag & (FSYNC | FDSYNC)) && (count == 1))
218                 atomic_dec_32(&zp->z_sync_cnt);
219
220         if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
221             ZTOV(zp)->v_type == VREG &&
222             !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0)
223                 VERIFY(fs_vscan(vp, cr, 1) == 0);
224
225         ZFS_EXIT(zfsvfs);
226         return (0);
227 }
228
229 /*
230  * Lseek support for finding holes (cmd == _FIO_SEEK_HOLE) and
231  * data (cmd == _FIO_SEEK_DATA). "off" is an in/out parameter.
232  */
233 static int
234 zfs_holey(vnode_t *vp, u_long cmd, offset_t *off)
235 {
236         znode_t *zp = VTOZ(vp);
237         uint64_t noff = (uint64_t)*off; /* new offset */
238         uint64_t file_sz;
239         int error;
240         boolean_t hole;
241
242         file_sz = zp->z_size;
243         if (noff >= file_sz)  {
244                 return (ENXIO);
245         }
246
247         if (cmd == _FIO_SEEK_HOLE)
248                 hole = B_TRUE;
249         else
250                 hole = B_FALSE;
251
252         error = dmu_offset_next(zp->z_zfsvfs->z_os, zp->z_id, hole, &noff);
253
254         /* end of file? */
255         if ((error == ESRCH) || (noff > file_sz)) {
256                 /*
257                  * Handle the virtual hole at the end of file.
258                  */
259                 if (hole) {
260                         *off = file_sz;
261                         return (0);
262                 }
263                 return (ENXIO);
264         }
265
266         if (noff < *off)
267                 return (error);
268         *off = noff;
269         return (error);
270 }
271
272 /* ARGSUSED */
273 static int
274 zfs_ioctl(vnode_t *vp, u_long com, intptr_t data, int flag, cred_t *cred,
275     int *rvalp, caller_context_t *ct)
276 {
277         offset_t off;
278         int error;
279         zfsvfs_t *zfsvfs;
280         znode_t *zp;
281
282         switch (com) {
283         case _FIOFFS:
284                 return (0);
285
286                 /*
287                  * The following two ioctls are used by bfu.  Faking out,
288                  * necessary to avoid bfu errors.
289                  */
290         case _FIOGDIO:
291         case _FIOSDIO:
292                 return (0);
293
294         case _FIO_SEEK_DATA:
295         case _FIO_SEEK_HOLE:
296 #ifdef sun
297                 if (ddi_copyin((void *)data, &off, sizeof (off), flag))
298                         return (EFAULT);
299 #else
300                 off = *(offset_t *)data;
301 #endif
302                 zp = VTOZ(vp);
303                 zfsvfs = zp->z_zfsvfs;
304                 ZFS_ENTER(zfsvfs);
305                 ZFS_VERIFY_ZP(zp);
306
307                 /* offset parameter is in/out */
308                 error = zfs_holey(vp, com, &off);
309                 ZFS_EXIT(zfsvfs);
310                 if (error)
311                         return (error);
312 #ifdef sun
313                 if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
314                         return (EFAULT);
315 #else
316                 *(offset_t *)data = off;
317 #endif
318                 return (0);
319         }
320         return (ENOTTY);
321 }
322
323 static vm_page_t
324 page_lookup(vnode_t *vp, int64_t start, int64_t off, int64_t nbytes)
325 {
326         vm_object_t obj;
327         vm_page_t pp;
328
329         obj = vp->v_object;
330         VM_OBJECT_LOCK_ASSERT(obj, MA_OWNED);
331
332         for (;;) {
333                 if ((pp = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
334                     vm_page_is_valid(pp, (vm_offset_t)off, nbytes)) {
335                         if ((pp->oflags & VPO_BUSY) != 0) {
336                                 /*
337                                  * Reference the page before unlocking and
338                                  * sleeping so that the page daemon is less
339                                  * likely to reclaim it.
340                                  */
341                                 vm_page_reference(pp);
342                                 vm_page_sleep(pp, "zfsmwb");
343                                 continue;
344                         }
345                         vm_page_busy(pp);
346                         vm_page_undirty(pp);
347                 } else {
348                         if (__predict_false(obj->cache != NULL)) {
349                                 vm_page_cache_free(obj, OFF_TO_IDX(start),
350                                     OFF_TO_IDX(start) + 1);
351                         }
352                         pp = NULL;
353                 }
354                 break;
355         }
356         return (pp);
357 }
358
359 static void
360 page_unlock(vm_page_t pp)
361 {
362
363         vm_page_wakeup(pp);
364 }
365
366 static caddr_t
367 zfs_map_page(vm_page_t pp, struct sf_buf **sfp)
368 {
369
370         *sfp = sf_buf_alloc(pp, 0);
371         return ((caddr_t)sf_buf_kva(*sfp));
372 }
373
374 static void
375 zfs_unmap_page(struct sf_buf *sf)
376 {
377
378         sf_buf_free(sf);
379 }
380
381 /*
382  * When a file is memory mapped, we must keep the IO data synchronized
383  * between the DMU cache and the memory mapped pages.  What this means:
384  *
385  * On Write:    If we find a memory mapped page, we write to *both*
386  *              the page and the dmu buffer.
387  */
388 static void
389 update_pages(vnode_t *vp, int64_t start, int len, objset_t *os, uint64_t oid,
390     int segflg, dmu_tx_t *tx)
391 {
392         vm_object_t obj;
393         struct sf_buf *sf;
394         int off;
395
396         ASSERT(vp->v_mount != NULL);
397         obj = vp->v_object;
398         ASSERT(obj != NULL);
399
400         off = start & PAGEOFFSET;
401         VM_OBJECT_LOCK(obj);
402         for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
403                 vm_page_t pp;
404                 int nbytes = MIN(PAGESIZE - off, len);
405
406                 if ((pp = page_lookup(vp, start, off, nbytes)) != NULL) {
407                         caddr_t va;
408
409                         VM_OBJECT_UNLOCK(obj);
410                         va = zfs_map_page(pp, &sf);
411                         if (segflg == UIO_NOCOPY) {
412                                 (void) dmu_write(os, oid, start+off, nbytes,
413                                     va+off, tx);
414                         } else {
415                                 (void) dmu_read(os, oid, start+off, nbytes,
416                                     va+off, DMU_READ_PREFETCH);
417                         }
418                         zfs_unmap_page(sf);
419                         VM_OBJECT_LOCK(obj);
420                         page_unlock(pp);
421                 }
422                 len -= nbytes;
423                 off = 0;
424         }
425         VM_OBJECT_UNLOCK(obj);
426 }
427
428 /*
429  * Read with UIO_NOCOPY flag means that sendfile(2) requests
430  * ZFS to populate a range of page cache pages with data.
431  *
432  * NOTE: this function could be optimized to pre-allocate
433  * all pages in advance, drain VPO_BUSY on all of them,
434  * map them into contiguous KVA region and populate them
435  * in one single dmu_read() call.
436  */
437 static int
438 mappedread_sf(vnode_t *vp, int nbytes, uio_t *uio)
439 {
440         znode_t *zp = VTOZ(vp);
441         objset_t *os = zp->z_zfsvfs->z_os;
442         struct sf_buf *sf;
443         vm_object_t obj;
444         vm_page_t pp;
445         int64_t start;
446         caddr_t va;
447         int len = nbytes;
448         int off;
449         int error = 0;
450
451         ASSERT(uio->uio_segflg == UIO_NOCOPY);
452         ASSERT(vp->v_mount != NULL);
453         obj = vp->v_object;
454         ASSERT(obj != NULL);
455         ASSERT((uio->uio_loffset & PAGEOFFSET) == 0);
456
457         VM_OBJECT_LOCK(obj);
458         for (start = uio->uio_loffset; len > 0; start += PAGESIZE) {
459                 int bytes = MIN(PAGESIZE, len);
460
461                 pp = vm_page_grab(obj, OFF_TO_IDX(start), VM_ALLOC_NOBUSY |
462                     VM_ALLOC_NORMAL | VM_ALLOC_RETRY | VM_ALLOC_IGN_SBUSY);
463                 if (pp->valid == 0) {
464                         vm_page_io_start(pp);
465                         VM_OBJECT_UNLOCK(obj);
466                         va = zfs_map_page(pp, &sf);
467                         error = dmu_read(os, zp->z_id, start, bytes, va,
468                             DMU_READ_PREFETCH);
469                         if (bytes != PAGESIZE && error == 0)
470                                 bzero(va + bytes, PAGESIZE - bytes);
471                         zfs_unmap_page(sf);
472                         VM_OBJECT_LOCK(obj);
473                         vm_page_io_finish(pp);
474                         vm_page_lock(pp);
475                         if (error) {
476                                 vm_page_free(pp);
477                         } else {
478                                 pp->valid = VM_PAGE_BITS_ALL;
479                                 vm_page_activate(pp);
480                         }
481                         vm_page_unlock(pp);
482                 }
483                 if (error)
484                         break;
485                 uio->uio_resid -= bytes;
486                 uio->uio_offset += bytes;
487                 len -= bytes;
488         }
489         VM_OBJECT_UNLOCK(obj);
490         return (error);
491 }
492
493 /*
494  * When a file is memory mapped, we must keep the IO data synchronized
495  * between the DMU cache and the memory mapped pages.  What this means:
496  *
497  * On Read:     We "read" preferentially from memory mapped pages,
498  *              else we default from the dmu buffer.
499  *
500  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
501  *      the file is memory mapped.
502  */
503 static int
504 mappedread(vnode_t *vp, int nbytes, uio_t *uio)
505 {
506         znode_t *zp = VTOZ(vp);
507         objset_t *os = zp->z_zfsvfs->z_os;
508         vm_object_t obj;
509         int64_t start;
510         caddr_t va;
511         int len = nbytes;
512         int off;
513         int error = 0;
514
515         ASSERT(vp->v_mount != NULL);
516         obj = vp->v_object;
517         ASSERT(obj != NULL);
518
519         start = uio->uio_loffset;
520         off = start & PAGEOFFSET;
521         VM_OBJECT_LOCK(obj);
522         for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
523                 vm_page_t pp;
524                 uint64_t bytes = MIN(PAGESIZE - off, len);
525
526                 if (pp = page_lookup(vp, start, off, bytes)) {
527                         struct sf_buf *sf;
528                         caddr_t va;
529
530                         VM_OBJECT_UNLOCK(obj);
531                         va = zfs_map_page(pp, &sf);
532                         error = uiomove(va + off, bytes, UIO_READ, uio);
533                         zfs_unmap_page(sf);
534                         VM_OBJECT_LOCK(obj);
535                         page_unlock(pp);
536                 } else {
537                         VM_OBJECT_UNLOCK(obj);
538                         error = dmu_read_uio(os, zp->z_id, uio, bytes);
539                         VM_OBJECT_LOCK(obj);
540                 }
541                 len -= bytes;
542                 off = 0;
543                 if (error)
544                         break;
545         }
546         VM_OBJECT_UNLOCK(obj);
547         return (error);
548 }
549
550 offset_t zfs_read_chunk_size = 1024 * 1024; /* Tunable */
551
552 /*
553  * Read bytes from specified file into supplied buffer.
554  *
555  *      IN:     vp      - vnode of file to be read from.
556  *              uio     - structure supplying read location, range info,
557  *                        and return buffer.
558  *              ioflag  - SYNC flags; used to provide FRSYNC semantics.
559  *              cr      - credentials of caller.
560  *              ct      - caller context
561  *
562  *      OUT:    uio     - updated offset and range, buffer filled.
563  *
564  *      RETURN: 0 if success
565  *              error code if failure
566  *
567  * Side Effects:
568  *      vp - atime updated if byte count > 0
569  */
570 /* ARGSUSED */
571 static int
572 zfs_read(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
573 {
574         znode_t         *zp = VTOZ(vp);
575         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
576         objset_t        *os;
577         ssize_t         n, nbytes;
578         int             error;
579         rl_t            *rl;
580         xuio_t          *xuio = NULL;
581
582         ZFS_ENTER(zfsvfs);
583         ZFS_VERIFY_ZP(zp);
584         os = zfsvfs->z_os;
585
586         if (zp->z_pflags & ZFS_AV_QUARANTINED) {
587                 ZFS_EXIT(zfsvfs);
588                 return (EACCES);
589         }
590
591         /*
592          * Validate file offset
593          */
594         if (uio->uio_loffset < (offset_t)0) {
595                 ZFS_EXIT(zfsvfs);
596                 return (EINVAL);
597         }
598
599         /*
600          * Fasttrack empty reads
601          */
602         if (uio->uio_resid == 0) {
603                 ZFS_EXIT(zfsvfs);
604                 return (0);
605         }
606
607         /*
608          * Check for mandatory locks
609          */
610         if (MANDMODE(zp->z_mode)) {
611                 if (error = chklock(vp, FREAD,
612                     uio->uio_loffset, uio->uio_resid, uio->uio_fmode, ct)) {
613                         ZFS_EXIT(zfsvfs);
614                         return (error);
615                 }
616         }
617
618         /*
619          * If we're in FRSYNC mode, sync out this znode before reading it.
620          */
621         if (zfsvfs->z_log &&
622             (ioflag & FRSYNC || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS))
623                 zil_commit(zfsvfs->z_log, zp->z_id);
624
625         /*
626          * Lock the range against changes.
627          */
628         rl = zfs_range_lock(zp, uio->uio_loffset, uio->uio_resid, RL_READER);
629
630         /*
631          * If we are reading past end-of-file we can skip
632          * to the end; but we might still need to set atime.
633          */
634         if (uio->uio_loffset >= zp->z_size) {
635                 error = 0;
636                 goto out;
637         }
638
639         ASSERT(uio->uio_loffset < zp->z_size);
640         n = MIN(uio->uio_resid, zp->z_size - uio->uio_loffset);
641
642 #ifdef sun
643         if ((uio->uio_extflg == UIO_XUIO) &&
644             (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY)) {
645                 int nblk;
646                 int blksz = zp->z_blksz;
647                 uint64_t offset = uio->uio_loffset;
648
649                 xuio = (xuio_t *)uio;
650                 if ((ISP2(blksz))) {
651                         nblk = (P2ROUNDUP(offset + n, blksz) - P2ALIGN(offset,
652                             blksz)) / blksz;
653                 } else {
654                         ASSERT(offset + n <= blksz);
655                         nblk = 1;
656                 }
657                 (void) dmu_xuio_init(xuio, nblk);
658
659                 if (vn_has_cached_data(vp)) {
660                         /*
661                          * For simplicity, we always allocate a full buffer
662                          * even if we only expect to read a portion of a block.
663                          */
664                         while (--nblk >= 0) {
665                                 (void) dmu_xuio_add(xuio,
666                                     dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
667                                     blksz), 0, blksz);
668                         }
669                 }
670         }
671 #endif  /* sun */
672
673         while (n > 0) {
674                 nbytes = MIN(n, zfs_read_chunk_size -
675                     P2PHASE(uio->uio_loffset, zfs_read_chunk_size));
676
677 #ifdef __FreeBSD__
678                 if (uio->uio_segflg == UIO_NOCOPY)
679                         error = mappedread_sf(vp, nbytes, uio);
680                 else
681 #endif /* __FreeBSD__ */
682                 if (vn_has_cached_data(vp))
683                         error = mappedread(vp, nbytes, uio);
684                 else
685                         error = dmu_read_uio(os, zp->z_id, uio, nbytes);
686                 if (error) {
687                         /* convert checksum errors into IO errors */
688                         if (error == ECKSUM)
689                                 error = EIO;
690                         break;
691                 }
692
693                 n -= nbytes;
694         }
695 out:
696         zfs_range_unlock(rl);
697
698         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
699         ZFS_EXIT(zfsvfs);
700         return (error);
701 }
702
703 /*
704  * Write the bytes to a file.
705  *
706  *      IN:     vp      - vnode of file to be written to.
707  *              uio     - structure supplying write location, range info,
708  *                        and data buffer.
709  *              ioflag  - FAPPEND flag set if in append mode.
710  *              cr      - credentials of caller.
711  *              ct      - caller context (NFS/CIFS fem monitor only)
712  *
713  *      OUT:    uio     - updated offset and range.
714  *
715  *      RETURN: 0 if success
716  *              error code if failure
717  *
718  * Timestamps:
719  *      vp - ctime|mtime updated if byte count > 0
720  */
721
722 /* ARGSUSED */
723 static int
724 zfs_write(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
725 {
726         znode_t         *zp = VTOZ(vp);
727         rlim64_t        limit = MAXOFFSET_T;
728         ssize_t         start_resid = uio->uio_resid;
729         ssize_t         tx_bytes;
730         uint64_t        end_size;
731         dmu_tx_t        *tx;
732         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
733         zilog_t         *zilog;
734         offset_t        woff;
735         ssize_t         n, nbytes;
736         rl_t            *rl;
737         int             max_blksz = zfsvfs->z_max_blksz;
738         int             error;
739         arc_buf_t       *abuf;
740         iovec_t         *aiov;
741         xuio_t          *xuio = NULL;
742         int             i_iov = 0;
743         int             iovcnt = uio->uio_iovcnt;
744         iovec_t         *iovp = uio->uio_iov;
745         int             write_eof;
746         int             count = 0;
747         sa_bulk_attr_t  bulk[4];
748         uint64_t        mtime[2], ctime[2];
749
750         /*
751          * Fasttrack empty write
752          */
753         n = start_resid;
754         if (n == 0)
755                 return (0);
756
757         if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
758                 limit = MAXOFFSET_T;
759
760         ZFS_ENTER(zfsvfs);
761         ZFS_VERIFY_ZP(zp);
762
763         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
764         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
765         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
766             &zp->z_size, 8);
767         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
768             &zp->z_pflags, 8);
769
770         /*
771          * If immutable or not appending then return EPERM
772          */
773         if ((zp->z_pflags & (ZFS_IMMUTABLE | ZFS_READONLY)) ||
774             ((zp->z_pflags & ZFS_APPENDONLY) && !(ioflag & FAPPEND) &&
775             (uio->uio_loffset < zp->z_size))) {
776                 ZFS_EXIT(zfsvfs);
777                 return (EPERM);
778         }
779
780         zilog = zfsvfs->z_log;
781
782         /*
783          * Validate file offset
784          */
785         woff = ioflag & FAPPEND ? zp->z_size : uio->uio_loffset;
786         if (woff < 0) {
787                 ZFS_EXIT(zfsvfs);
788                 return (EINVAL);
789         }
790
791         /*
792          * Check for mandatory locks before calling zfs_range_lock()
793          * in order to prevent a deadlock with locks set via fcntl().
794          */
795         if (MANDMODE((mode_t)zp->z_mode) &&
796             (error = chklock(vp, FWRITE, woff, n, uio->uio_fmode, ct)) != 0) {
797                 ZFS_EXIT(zfsvfs);
798                 return (error);
799         }
800
801 #ifdef sun
802         /*
803          * Pre-fault the pages to ensure slow (eg NFS) pages
804          * don't hold up txg.
805          * Skip this if uio contains loaned arc_buf.
806          */
807         if ((uio->uio_extflg == UIO_XUIO) &&
808             (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY))
809                 xuio = (xuio_t *)uio;
810         else
811                 uio_prefaultpages(MIN(n, max_blksz), uio);
812 #endif  /* sun */
813
814         /*
815          * If in append mode, set the io offset pointer to eof.
816          */
817         if (ioflag & FAPPEND) {
818                 /*
819                  * Obtain an appending range lock to guarantee file append
820                  * semantics.  We reset the write offset once we have the lock.
821                  */
822                 rl = zfs_range_lock(zp, 0, n, RL_APPEND);
823                 woff = rl->r_off;
824                 if (rl->r_len == UINT64_MAX) {
825                         /*
826                          * We overlocked the file because this write will cause
827                          * the file block size to increase.
828                          * Note that zp_size cannot change with this lock held.
829                          */
830                         woff = zp->z_size;
831                 }
832                 uio->uio_loffset = woff;
833         } else {
834                 /*
835                  * Note that if the file block size will change as a result of
836                  * this write, then this range lock will lock the entire file
837                  * so that we can re-write the block safely.
838                  */
839                 rl = zfs_range_lock(zp, woff, n, RL_WRITER);
840         }
841
842         if (vn_rlimit_fsize(vp, uio, uio->uio_td)) {
843                 zfs_range_unlock(rl);
844                 ZFS_EXIT(zfsvfs);
845                 return (EFBIG);
846         }
847
848         if (woff >= limit) {
849                 zfs_range_unlock(rl);
850                 ZFS_EXIT(zfsvfs);
851                 return (EFBIG);
852         }
853
854         if ((woff + n) > limit || woff > (limit - n))
855                 n = limit - woff;
856
857         /* Will this write extend the file length? */
858         write_eof = (woff + n > zp->z_size);
859
860         end_size = MAX(zp->z_size, woff + n);
861
862         /*
863          * Write the file in reasonable size chunks.  Each chunk is written
864          * in a separate transaction; this keeps the intent log records small
865          * and allows us to do more fine-grained space accounting.
866          */
867         while (n > 0) {
868                 abuf = NULL;
869                 woff = uio->uio_loffset;
870 again:
871                 if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
872                     zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
873                         if (abuf != NULL)
874                                 dmu_return_arcbuf(abuf);
875                         error = EDQUOT;
876                         break;
877                 }
878
879                 if (xuio && abuf == NULL) {
880                         ASSERT(i_iov < iovcnt);
881                         aiov = &iovp[i_iov];
882                         abuf = dmu_xuio_arcbuf(xuio, i_iov);
883                         dmu_xuio_clear(xuio, i_iov);
884                         DTRACE_PROBE3(zfs_cp_write, int, i_iov,
885                             iovec_t *, aiov, arc_buf_t *, abuf);
886                         ASSERT((aiov->iov_base == abuf->b_data) ||
887                             ((char *)aiov->iov_base - (char *)abuf->b_data +
888                             aiov->iov_len == arc_buf_size(abuf)));
889                         i_iov++;
890                 } else if (abuf == NULL && n >= max_blksz &&
891                     woff >= zp->z_size &&
892                     P2PHASE(woff, max_blksz) == 0 &&
893                     zp->z_blksz == max_blksz) {
894                         /*
895                          * This write covers a full block.  "Borrow" a buffer
896                          * from the dmu so that we can fill it before we enter
897                          * a transaction.  This avoids the possibility of
898                          * holding up the transaction if the data copy hangs
899                          * up on a pagefault (e.g., from an NFS server mapping).
900                          */
901                         size_t cbytes;
902
903                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
904                             max_blksz);
905                         ASSERT(abuf != NULL);
906                         ASSERT(arc_buf_size(abuf) == max_blksz);
907                         if (error = uiocopy(abuf->b_data, max_blksz,
908                             UIO_WRITE, uio, &cbytes)) {
909                                 dmu_return_arcbuf(abuf);
910                                 break;
911                         }
912                         ASSERT(cbytes == max_blksz);
913                 }
914
915                 /*
916                  * Start a transaction.
917                  */
918                 tx = dmu_tx_create(zfsvfs->z_os);
919                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
920                 dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
921                 zfs_sa_upgrade_txholds(tx, zp);
922                 error = dmu_tx_assign(tx, TXG_NOWAIT);
923                 if (error) {
924                         if (error == ERESTART) {
925                                 dmu_tx_wait(tx);
926                                 dmu_tx_abort(tx);
927                                 goto again;
928                         }
929                         dmu_tx_abort(tx);
930                         if (abuf != NULL)
931                                 dmu_return_arcbuf(abuf);
932                         break;
933                 }
934
935                 /*
936                  * If zfs_range_lock() over-locked we grow the blocksize
937                  * and then reduce the lock range.  This will only happen
938                  * on the first iteration since zfs_range_reduce() will
939                  * shrink down r_len to the appropriate size.
940                  */
941                 if (rl->r_len == UINT64_MAX) {
942                         uint64_t new_blksz;
943
944                         if (zp->z_blksz > max_blksz) {
945                                 ASSERT(!ISP2(zp->z_blksz));
946                                 new_blksz = MIN(end_size, SPA_MAXBLOCKSIZE);
947                         } else {
948                                 new_blksz = MIN(end_size, max_blksz);
949                         }
950                         zfs_grow_blocksize(zp, new_blksz, tx);
951                         zfs_range_reduce(rl, woff, n);
952                 }
953
954                 /*
955                  * XXX - should we really limit each write to z_max_blksz?
956                  * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
957                  */
958                 nbytes = MIN(n, max_blksz - P2PHASE(woff, max_blksz));
959
960                 if (woff + nbytes > zp->z_size)
961                         vnode_pager_setsize(vp, woff + nbytes);
962
963                 if (abuf == NULL) {
964                         tx_bytes = uio->uio_resid;
965                         error = dmu_write_uio_dbuf(sa_get_db(zp->z_sa_hdl),
966                             uio, nbytes, tx);
967                         tx_bytes -= uio->uio_resid;
968                 } else {
969                         tx_bytes = nbytes;
970                         ASSERT(xuio == NULL || tx_bytes == aiov->iov_len);
971                         /*
972                          * If this is not a full block write, but we are
973                          * extending the file past EOF and this data starts
974                          * block-aligned, use assign_arcbuf().  Otherwise,
975                          * write via dmu_write().
976                          */
977                         if (tx_bytes < max_blksz && (!write_eof ||
978                             aiov->iov_base != abuf->b_data)) {
979                                 ASSERT(xuio);
980                                 dmu_write(zfsvfs->z_os, zp->z_id, woff,
981                                     aiov->iov_len, aiov->iov_base, tx);
982                                 dmu_return_arcbuf(abuf);
983                                 xuio_stat_wbuf_copied();
984                         } else {
985                                 ASSERT(xuio || tx_bytes == max_blksz);
986                                 dmu_assign_arcbuf(sa_get_db(zp->z_sa_hdl),
987                                     woff, abuf, tx);
988                         }
989                         ASSERT(tx_bytes <= uio->uio_resid);
990                         uioskip(uio, tx_bytes);
991                 }
992                 if (tx_bytes && vn_has_cached_data(vp)) {
993                         update_pages(vp, woff, tx_bytes, zfsvfs->z_os,
994                             zp->z_id, uio->uio_segflg, tx);
995                 }
996
997                 /*
998                  * If we made no progress, we're done.  If we made even
999                  * partial progress, update the znode and ZIL accordingly.
1000                  */
1001                 if (tx_bytes == 0) {
1002                         (void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
1003                             (void *)&zp->z_size, sizeof (uint64_t), tx);
1004                         dmu_tx_commit(tx);
1005                         ASSERT(error != 0);
1006                         break;
1007                 }
1008
1009                 /*
1010                  * Clear Set-UID/Set-GID bits on successful write if not
1011                  * privileged and at least one of the excute bits is set.
1012                  *
1013                  * It would be nice to to this after all writes have
1014                  * been done, but that would still expose the ISUID/ISGID
1015                  * to another app after the partial write is committed.
1016                  *
1017                  * Note: we don't call zfs_fuid_map_id() here because
1018                  * user 0 is not an ephemeral uid.
1019                  */
1020                 mutex_enter(&zp->z_acl_lock);
1021                 if ((zp->z_mode & (S_IXUSR | (S_IXUSR >> 3) |
1022                     (S_IXUSR >> 6))) != 0 &&
1023                     (zp->z_mode & (S_ISUID | S_ISGID)) != 0 &&
1024                     secpolicy_vnode_setid_retain(vp, cr,
1025                     (zp->z_mode & S_ISUID) != 0 && zp->z_uid == 0) != 0) {
1026                         uint64_t newmode;
1027                         zp->z_mode &= ~(S_ISUID | S_ISGID);
1028                         newmode = zp->z_mode;
1029                         (void) sa_update(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs),
1030                             (void *)&newmode, sizeof (uint64_t), tx);
1031                 }
1032                 mutex_exit(&zp->z_acl_lock);
1033
1034                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
1035                     B_TRUE);
1036
1037                 /*
1038                  * Update the file size (zp_size) if it has changed;
1039                  * account for possible concurrent updates.
1040                  */
1041                 while ((end_size = zp->z_size) < uio->uio_loffset) {
1042                         (void) atomic_cas_64(&zp->z_size, end_size,
1043                             uio->uio_loffset);
1044                         ASSERT(error == 0);
1045                 }
1046                 /*
1047                  * If we are replaying and eof is non zero then force
1048                  * the file size to the specified eof. Note, there's no
1049                  * concurrency during replay.
1050                  */
1051                 if (zfsvfs->z_replay && zfsvfs->z_replay_eof != 0)
1052                         zp->z_size = zfsvfs->z_replay_eof;
1053
1054                 error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1055
1056                 zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, ioflag);
1057                 dmu_tx_commit(tx);
1058
1059                 if (error != 0)
1060                         break;
1061                 ASSERT(tx_bytes == nbytes);
1062                 n -= nbytes;
1063
1064 #ifdef sun
1065                 if (!xuio && n > 0)
1066                         uio_prefaultpages(MIN(n, max_blksz), uio);
1067 #endif  /* sun */
1068         }
1069
1070         zfs_range_unlock(rl);
1071
1072         /*
1073          * If we're in replay mode, or we made no progress, return error.
1074          * Otherwise, it's at least a partial write, so it's successful.
1075          */
1076         if (zfsvfs->z_replay || uio->uio_resid == start_resid) {
1077                 ZFS_EXIT(zfsvfs);
1078                 return (error);
1079         }
1080
1081         if (ioflag & (FSYNC | FDSYNC) ||
1082             zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1083                 zil_commit(zilog, zp->z_id);
1084
1085         ZFS_EXIT(zfsvfs);
1086         return (0);
1087 }
1088
1089 void
1090 zfs_get_done(zgd_t *zgd, int error)
1091 {
1092         znode_t *zp = zgd->zgd_private;
1093         objset_t *os = zp->z_zfsvfs->z_os;
1094         int vfslocked;
1095
1096         if (zgd->zgd_db)
1097                 dmu_buf_rele(zgd->zgd_db, zgd);
1098
1099         zfs_range_unlock(zgd->zgd_rl);
1100
1101         vfslocked = VFS_LOCK_GIANT(zp->z_zfsvfs->z_vfs);
1102         /*
1103          * Release the vnode asynchronously as we currently have the
1104          * txg stopped from syncing.
1105          */
1106         VN_RELE_ASYNC(ZTOV(zp), dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1107
1108         if (error == 0 && zgd->zgd_bp)
1109                 zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
1110
1111         kmem_free(zgd, sizeof (zgd_t));
1112         VFS_UNLOCK_GIANT(vfslocked);
1113 }
1114
1115 #ifdef DEBUG
1116 static int zil_fault_io = 0;
1117 #endif
1118
1119 /*
1120  * Get data to generate a TX_WRITE intent log record.
1121  */
1122 int
1123 zfs_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
1124 {
1125         zfsvfs_t *zfsvfs = arg;
1126         objset_t *os = zfsvfs->z_os;
1127         znode_t *zp;
1128         uint64_t object = lr->lr_foid;
1129         uint64_t offset = lr->lr_offset;
1130         uint64_t size = lr->lr_length;
1131         blkptr_t *bp = &lr->lr_blkptr;
1132         dmu_buf_t *db;
1133         zgd_t *zgd;
1134         int error = 0;
1135
1136         ASSERT(zio != NULL);
1137         ASSERT(size != 0);
1138
1139         /*
1140          * Nothing to do if the file has been removed
1141          */
1142         if (zfs_zget(zfsvfs, object, &zp) != 0)
1143                 return (ENOENT);
1144         if (zp->z_unlinked) {
1145                 /*
1146                  * Release the vnode asynchronously as we currently have the
1147                  * txg stopped from syncing.
1148                  */
1149                 VN_RELE_ASYNC(ZTOV(zp),
1150                     dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1151                 return (ENOENT);
1152         }
1153
1154         zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1155         zgd->zgd_zilog = zfsvfs->z_log;
1156         zgd->zgd_private = zp;
1157
1158         /*
1159          * Write records come in two flavors: immediate and indirect.
1160          * For small writes it's cheaper to store the data with the
1161          * log record (immediate); for large writes it's cheaper to
1162          * sync the data and get a pointer to it (indirect) so that
1163          * we don't have to write the data twice.
1164          */
1165         if (buf != NULL) { /* immediate write */
1166                 zgd->zgd_rl = zfs_range_lock(zp, offset, size, RL_READER);
1167                 /* test for truncation needs to be done while range locked */
1168                 if (offset >= zp->z_size) {
1169                         error = ENOENT;
1170                 } else {
1171                         error = dmu_read(os, object, offset, size, buf,
1172                             DMU_READ_NO_PREFETCH);
1173                 }
1174                 ASSERT(error == 0 || error == ENOENT);
1175         } else { /* indirect write */
1176                 /*
1177                  * Have to lock the whole block to ensure when it's
1178                  * written out and it's checksum is being calculated
1179                  * that no one can change the data. We need to re-check
1180                  * blocksize after we get the lock in case it's changed!
1181                  */
1182                 for (;;) {
1183                         uint64_t blkoff;
1184                         size = zp->z_blksz;
1185                         blkoff = ISP2(size) ? P2PHASE(offset, size) : offset;
1186                         offset -= blkoff;
1187                         zgd->zgd_rl = zfs_range_lock(zp, offset, size,
1188                             RL_READER);
1189                         if (zp->z_blksz == size)
1190                                 break;
1191                         offset += blkoff;
1192                         zfs_range_unlock(zgd->zgd_rl);
1193                 }
1194                 /* test for truncation needs to be done while range locked */
1195                 if (lr->lr_offset >= zp->z_size)
1196                         error = ENOENT;
1197 #ifdef DEBUG
1198                 if (zil_fault_io) {
1199                         error = EIO;
1200                         zil_fault_io = 0;
1201                 }
1202 #endif
1203                 if (error == 0)
1204                         error = dmu_buf_hold(os, object, offset, zgd, &db,
1205                             DMU_READ_NO_PREFETCH);
1206
1207                 if (error == 0) {
1208                         zgd->zgd_db = db;
1209                         zgd->zgd_bp = bp;
1210
1211                         ASSERT(db->db_offset == offset);
1212                         ASSERT(db->db_size == size);
1213
1214                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
1215                             zfs_get_done, zgd);
1216                         ASSERT(error || lr->lr_length <= zp->z_blksz);
1217
1218                         /*
1219                          * On success, we need to wait for the write I/O
1220                          * initiated by dmu_sync() to complete before we can
1221                          * release this dbuf.  We will finish everything up
1222                          * in the zfs_get_done() callback.
1223                          */
1224                         if (error == 0)
1225                                 return (0);
1226
1227                         if (error == EALREADY) {
1228                                 lr->lr_common.lrc_txtype = TX_WRITE2;
1229                                 error = 0;
1230                         }
1231                 }
1232         }
1233
1234         zfs_get_done(zgd, error);
1235
1236         return (error);
1237 }
1238
1239 /*ARGSUSED*/
1240 static int
1241 zfs_access(vnode_t *vp, int mode, int flag, cred_t *cr,
1242     caller_context_t *ct)
1243 {
1244         znode_t *zp = VTOZ(vp);
1245         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1246         int error;
1247
1248         ZFS_ENTER(zfsvfs);
1249         ZFS_VERIFY_ZP(zp);
1250
1251         if (flag & V_ACE_MASK)
1252                 error = zfs_zaccess(zp, mode, flag, B_FALSE, cr);
1253         else
1254                 error = zfs_zaccess_rwx(zp, mode, flag, cr);
1255
1256         ZFS_EXIT(zfsvfs);
1257         return (error);
1258 }
1259
1260 /*
1261  * If vnode is for a device return a specfs vnode instead.
1262  */
1263 static int
1264 specvp_check(vnode_t **vpp, cred_t *cr)
1265 {
1266         int error = 0;
1267
1268         if (IS_DEVVP(*vpp)) {
1269                 struct vnode *svp;
1270
1271                 svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1272                 VN_RELE(*vpp);
1273                 if (svp == NULL)
1274                         error = ENOSYS;
1275                 *vpp = svp;
1276         }
1277         return (error);
1278 }
1279
1280
1281 /*
1282  * Lookup an entry in a directory, or an extended attribute directory.
1283  * If it exists, return a held vnode reference for it.
1284  *
1285  *      IN:     dvp     - vnode of directory to search.
1286  *              nm      - name of entry to lookup.
1287  *              pnp     - full pathname to lookup [UNUSED].
1288  *              flags   - LOOKUP_XATTR set if looking for an attribute.
1289  *              rdir    - root directory vnode [UNUSED].
1290  *              cr      - credentials of caller.
1291  *              ct      - caller context
1292  *              direntflags - directory lookup flags
1293  *              realpnp - returned pathname.
1294  *
1295  *      OUT:    vpp     - vnode of located entry, NULL if not found.
1296  *
1297  *      RETURN: 0 if success
1298  *              error code if failure
1299  *
1300  * Timestamps:
1301  *      NA
1302  */
1303 /* ARGSUSED */
1304 static int
1305 zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct componentname *cnp,
1306     int nameiop, cred_t *cr, kthread_t *td, int flags)
1307 {
1308         znode_t *zdp = VTOZ(dvp);
1309         zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
1310         int     error = 0;
1311         int *direntflags = NULL;
1312         void *realpnp = NULL;
1313
1314         /* fast path */
1315         if (!(flags & (LOOKUP_XATTR | FIGNORECASE))) {
1316
1317                 if (dvp->v_type != VDIR) {
1318                         return (ENOTDIR);
1319                 } else if (zdp->z_sa_hdl == NULL) {
1320                         return (EIO);
1321                 }
1322
1323                 if (nm[0] == 0 || (nm[0] == '.' && nm[1] == '\0')) {
1324                         error = zfs_fastaccesschk_execute(zdp, cr);
1325                         if (!error) {
1326                                 *vpp = dvp;
1327                                 VN_HOLD(*vpp);
1328                                 return (0);
1329                         }
1330                         return (error);
1331                 } else {
1332                         vnode_t *tvp = dnlc_lookup(dvp, nm);
1333
1334                         if (tvp) {
1335                                 error = zfs_fastaccesschk_execute(zdp, cr);
1336                                 if (error) {
1337                                         VN_RELE(tvp);
1338                                         return (error);
1339                                 }
1340                                 if (tvp == DNLC_NO_VNODE) {
1341                                         VN_RELE(tvp);
1342                                         return (ENOENT);
1343                                 } else {
1344                                         *vpp = tvp;
1345                                         return (specvp_check(vpp, cr));
1346                                 }
1347                         }
1348                 }
1349         }
1350
1351         DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp, char *, nm);
1352
1353         ZFS_ENTER(zfsvfs);
1354         ZFS_VERIFY_ZP(zdp);
1355
1356         *vpp = NULL;
1357
1358         if (flags & LOOKUP_XATTR) {
1359 #ifdef TODO
1360                 /*
1361                  * If the xattr property is off, refuse the lookup request.
1362                  */
1363                 if (!(zfsvfs->z_vfs->vfs_flag & VFS_XATTR)) {
1364                         ZFS_EXIT(zfsvfs);
1365                         return (EINVAL);
1366                 }
1367 #endif
1368
1369                 /*
1370                  * We don't allow recursive attributes..
1371                  * Maybe someday we will.
1372                  */
1373                 if (zdp->z_pflags & ZFS_XATTR) {
1374                         ZFS_EXIT(zfsvfs);
1375                         return (EINVAL);
1376                 }
1377
1378                 if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr, flags)) {
1379                         ZFS_EXIT(zfsvfs);
1380                         return (error);
1381                 }
1382
1383                 /*
1384                  * Do we have permission to get into attribute directory?
1385                  */
1386
1387                 if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, 0,
1388                     B_FALSE, cr)) {
1389                         VN_RELE(*vpp);
1390                         *vpp = NULL;
1391                 }
1392
1393                 ZFS_EXIT(zfsvfs);
1394                 return (error);
1395         }
1396
1397         if (dvp->v_type != VDIR) {
1398                 ZFS_EXIT(zfsvfs);
1399                 return (ENOTDIR);
1400         }
1401
1402         /*
1403          * Check accessibility of directory.
1404          */
1405
1406         if (error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr)) {
1407                 ZFS_EXIT(zfsvfs);
1408                 return (error);
1409         }
1410
1411         if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
1412             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1413                 ZFS_EXIT(zfsvfs);
1414                 return (EILSEQ);
1415         }
1416
1417         error = zfs_dirlook(zdp, nm, vpp, flags, direntflags, realpnp);
1418         if (error == 0)
1419                 error = specvp_check(vpp, cr);
1420
1421         /* Translate errors and add SAVENAME when needed. */
1422         if (cnp->cn_flags & ISLASTCN) {
1423                 switch (nameiop) {
1424                 case CREATE:
1425                 case RENAME:
1426                         if (error == ENOENT) {
1427                                 error = EJUSTRETURN;
1428                                 cnp->cn_flags |= SAVENAME;
1429                                 break;
1430                         }
1431                         /* FALLTHROUGH */
1432                 case DELETE:
1433                         if (error == 0)
1434                                 cnp->cn_flags |= SAVENAME;
1435                         break;
1436                 }
1437         }
1438         if (error == 0 && (nm[0] != '.' || nm[1] != '\0')) {
1439                 int ltype = 0;
1440
1441                 if (cnp->cn_flags & ISDOTDOT) {
1442                         ltype = VOP_ISLOCKED(dvp);
1443                         VOP_UNLOCK(dvp, 0);
1444                 }
1445                 ZFS_EXIT(zfsvfs);
1446                 error = zfs_vnode_lock(*vpp, cnp->cn_lkflags);
1447                 if (cnp->cn_flags & ISDOTDOT)
1448                         vn_lock(dvp, ltype | LK_RETRY);
1449                 if (error != 0) {
1450                         VN_RELE(*vpp);
1451                         *vpp = NULL;
1452                         return (error);
1453                 }
1454         } else {
1455                 ZFS_EXIT(zfsvfs);
1456         }
1457
1458 #ifdef FREEBSD_NAMECACHE
1459         /*
1460          * Insert name into cache (as non-existent) if appropriate.
1461          */
1462         if (error == ENOENT && (cnp->cn_flags & MAKEENTRY) && nameiop != CREATE)
1463                 cache_enter(dvp, *vpp, cnp);
1464         /*
1465          * Insert name into cache if appropriate.
1466          */
1467         if (error == 0 && (cnp->cn_flags & MAKEENTRY)) {
1468                 if (!(cnp->cn_flags & ISLASTCN) ||
1469                     (nameiop != DELETE && nameiop != RENAME)) {
1470                         cache_enter(dvp, *vpp, cnp);
1471                 }
1472         }
1473 #endif
1474
1475         return (error);
1476 }
1477
1478 /*
1479  * Attempt to create a new entry in a directory.  If the entry
1480  * already exists, truncate the file if permissible, else return
1481  * an error.  Return the vp of the created or trunc'd file.
1482  *
1483  *      IN:     dvp     - vnode of directory to put new file entry in.
1484  *              name    - name of new file entry.
1485  *              vap     - attributes of new file.
1486  *              excl    - flag indicating exclusive or non-exclusive mode.
1487  *              mode    - mode to open file with.
1488  *              cr      - credentials of caller.
1489  *              flag    - large file flag [UNUSED].
1490  *              ct      - caller context
1491  *              vsecp   - ACL to be set
1492  *
1493  *      OUT:    vpp     - vnode of created or trunc'd entry.
1494  *
1495  *      RETURN: 0 if success
1496  *              error code if failure
1497  *
1498  * Timestamps:
1499  *      dvp - ctime|mtime updated if new entry created
1500  *       vp - ctime|mtime always, atime if new
1501  */
1502
1503 /* ARGSUSED */
1504 static int
1505 zfs_create(vnode_t *dvp, char *name, vattr_t *vap, int excl, int mode,
1506     vnode_t **vpp, cred_t *cr, kthread_t *td)
1507 {
1508         znode_t         *zp, *dzp = VTOZ(dvp);
1509         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1510         zilog_t         *zilog;
1511         objset_t        *os;
1512         zfs_dirlock_t   *dl;
1513         dmu_tx_t        *tx;
1514         int             error;
1515         ksid_t          *ksid;
1516         uid_t           uid;
1517         gid_t           gid = crgetgid(cr);
1518         zfs_acl_ids_t   acl_ids;
1519         boolean_t       fuid_dirtied;
1520         boolean_t       have_acl = B_FALSE;
1521         void            *vsecp = NULL;
1522         int             flag = 0;
1523
1524         /*
1525          * If we have an ephemeral id, ACL, or XVATTR then
1526          * make sure file system is at proper version
1527          */
1528
1529         ksid = crgetsid(cr, KSID_OWNER);
1530         if (ksid)
1531                 uid = ksid_getid(ksid);
1532         else
1533                 uid = crgetuid(cr);
1534
1535         if (zfsvfs->z_use_fuids == B_FALSE &&
1536             (vsecp || (vap->va_mask & AT_XVATTR) ||
1537             IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1538                 return (EINVAL);
1539
1540         ZFS_ENTER(zfsvfs);
1541         ZFS_VERIFY_ZP(dzp);
1542         os = zfsvfs->z_os;
1543         zilog = zfsvfs->z_log;
1544
1545         if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1546             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1547                 ZFS_EXIT(zfsvfs);
1548                 return (EILSEQ);
1549         }
1550
1551         if (vap->va_mask & AT_XVATTR) {
1552                 if ((error = secpolicy_xvattr(dvp, (xvattr_t *)vap,
1553                     crgetuid(cr), cr, vap->va_type)) != 0) {
1554                         ZFS_EXIT(zfsvfs);
1555                         return (error);
1556                 }
1557         }
1558 top:
1559         *vpp = NULL;
1560
1561         if ((vap->va_mode & S_ISVTX) && secpolicy_vnode_stky_modify(cr))
1562                 vap->va_mode &= ~S_ISVTX;
1563
1564         if (*name == '\0') {
1565                 /*
1566                  * Null component name refers to the directory itself.
1567                  */
1568                 VN_HOLD(dvp);
1569                 zp = dzp;
1570                 dl = NULL;
1571                 error = 0;
1572         } else {
1573                 /* possible VN_HOLD(zp) */
1574                 int zflg = 0;
1575
1576                 if (flag & FIGNORECASE)
1577                         zflg |= ZCILOOK;
1578
1579                 error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1580                     NULL, NULL);
1581                 if (error) {
1582                         if (have_acl)
1583                                 zfs_acl_ids_free(&acl_ids);
1584                         if (strcmp(name, "..") == 0)
1585                                 error = EISDIR;
1586                         ZFS_EXIT(zfsvfs);
1587                         return (error);
1588                 }
1589         }
1590
1591         if (zp == NULL) {
1592                 uint64_t txtype;
1593
1594                 /*
1595                  * Create a new file object and update the directory
1596                  * to reference it.
1597                  */
1598                 if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
1599                         if (have_acl)
1600                                 zfs_acl_ids_free(&acl_ids);
1601                         goto out;
1602                 }
1603
1604                 /*
1605                  * We only support the creation of regular files in
1606                  * extended attribute directories.
1607                  */
1608
1609                 if ((dzp->z_pflags & ZFS_XATTR) &&
1610                     (vap->va_type != VREG)) {
1611                         if (have_acl)
1612                                 zfs_acl_ids_free(&acl_ids);
1613                         error = EINVAL;
1614                         goto out;
1615                 }
1616
1617                 if (!have_acl && (error = zfs_acl_ids_create(dzp, 0, vap,
1618                     cr, vsecp, &acl_ids)) != 0)
1619                         goto out;
1620                 have_acl = B_TRUE;
1621
1622                 if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1623                         zfs_acl_ids_free(&acl_ids);
1624                         error = EDQUOT;
1625                         goto out;
1626                 }
1627
1628                 tx = dmu_tx_create(os);
1629
1630                 dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1631                     ZFS_SA_BASE_ATTR_SIZE);
1632
1633                 fuid_dirtied = zfsvfs->z_fuid_dirty;
1634                 if (fuid_dirtied)
1635                         zfs_fuid_txhold(zfsvfs, tx);
1636                 dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1637                 dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
1638                 if (!zfsvfs->z_use_sa &&
1639                     acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1640                         dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1641                             0, acl_ids.z_aclp->z_acl_bytes);
1642                 }
1643                 error = dmu_tx_assign(tx, TXG_NOWAIT);
1644                 if (error) {
1645                         zfs_dirent_unlock(dl);
1646                         if (error == ERESTART) {
1647                                 dmu_tx_wait(tx);
1648                                 dmu_tx_abort(tx);
1649                                 goto top;
1650                         }
1651                         zfs_acl_ids_free(&acl_ids);
1652                         dmu_tx_abort(tx);
1653                         ZFS_EXIT(zfsvfs);
1654                         return (error);
1655                 }
1656                 zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1657
1658                 if (fuid_dirtied)
1659                         zfs_fuid_sync(zfsvfs, tx);
1660
1661                 (void) zfs_link_create(dl, zp, tx, ZNEW);
1662                 txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1663                 if (flag & FIGNORECASE)
1664                         txtype |= TX_CI;
1665                 zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1666                     vsecp, acl_ids.z_fuidp, vap);
1667                 zfs_acl_ids_free(&acl_ids);
1668                 dmu_tx_commit(tx);
1669         } else {
1670                 int aflags = (flag & FAPPEND) ? V_APPEND : 0;
1671
1672                 if (have_acl)
1673                         zfs_acl_ids_free(&acl_ids);
1674                 have_acl = B_FALSE;
1675
1676                 /*
1677                  * A directory entry already exists for this name.
1678                  */
1679                 /*
1680                  * Can't truncate an existing file if in exclusive mode.
1681                  */
1682                 if (excl == EXCL) {
1683                         error = EEXIST;
1684                         goto out;
1685                 }
1686                 /*
1687                  * Can't open a directory for writing.
1688                  */
1689                 if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1690                         error = EISDIR;
1691                         goto out;
1692                 }
1693                 /*
1694                  * Verify requested access to file.
1695                  */
1696                 if (mode && (error = zfs_zaccess_rwx(zp, mode, aflags, cr))) {
1697                         goto out;
1698                 }
1699
1700                 mutex_enter(&dzp->z_lock);
1701                 dzp->z_seq++;
1702                 mutex_exit(&dzp->z_lock);
1703
1704                 /*
1705                  * Truncate regular files if requested.
1706                  */
1707                 if ((ZTOV(zp)->v_type == VREG) &&
1708                     (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1709                         /* we can't hold any locks when calling zfs_freesp() */
1710                         zfs_dirent_unlock(dl);
1711                         dl = NULL;
1712                         error = zfs_freesp(zp, 0, 0, mode, TRUE);
1713                         if (error == 0) {
1714                                 vnevent_create(ZTOV(zp), ct);
1715                         }
1716                 }
1717         }
1718 out:
1719         if (dl)
1720                 zfs_dirent_unlock(dl);
1721
1722         if (error) {
1723                 if (zp)
1724                         VN_RELE(ZTOV(zp));
1725         } else {
1726                 *vpp = ZTOV(zp);
1727                 error = specvp_check(vpp, cr);
1728         }
1729
1730         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1731                 zil_commit(zilog, 0);
1732
1733         ZFS_EXIT(zfsvfs);
1734         return (error);
1735 }
1736
1737 /*
1738  * Remove an entry from a directory.
1739  *
1740  *      IN:     dvp     - vnode of directory to remove entry from.
1741  *              name    - name of entry to remove.
1742  *              cr      - credentials of caller.
1743  *              ct      - caller context
1744  *              flags   - case flags
1745  *
1746  *      RETURN: 0 if success
1747  *              error code if failure
1748  *
1749  * Timestamps:
1750  *      dvp - ctime|mtime
1751  *       vp - ctime (if nlink > 0)
1752  */
1753
1754 uint64_t null_xattr = 0;
1755
1756 /*ARGSUSED*/
1757 static int
1758 zfs_remove(vnode_t *dvp, char *name, cred_t *cr, caller_context_t *ct,
1759     int flags)
1760 {
1761         znode_t         *zp, *dzp = VTOZ(dvp);
1762         znode_t         *xzp;
1763         vnode_t         *vp;
1764         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1765         zilog_t         *zilog;
1766         uint64_t        acl_obj, xattr_obj;
1767         uint64_t        xattr_obj_unlinked = 0;
1768         uint64_t        obj = 0;
1769         zfs_dirlock_t   *dl;
1770         dmu_tx_t        *tx;
1771         boolean_t       may_delete_now, delete_now = FALSE;
1772         boolean_t       unlinked, toobig = FALSE;
1773         uint64_t        txtype;
1774         pathname_t      *realnmp = NULL;
1775         pathname_t      realnm;
1776         int             error;
1777         int             zflg = ZEXISTS;
1778
1779         ZFS_ENTER(zfsvfs);
1780         ZFS_VERIFY_ZP(dzp);
1781         zilog = zfsvfs->z_log;
1782
1783         if (flags & FIGNORECASE) {
1784                 zflg |= ZCILOOK;
1785                 pn_alloc(&realnm);
1786                 realnmp = &realnm;
1787         }
1788
1789 top:
1790         xattr_obj = 0;
1791         xzp = NULL;
1792         /*
1793          * Attempt to lock directory; fail if entry doesn't exist.
1794          */
1795         if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1796             NULL, realnmp)) {
1797                 if (realnmp)
1798                         pn_free(realnmp);
1799                 ZFS_EXIT(zfsvfs);
1800                 return (error);
1801         }
1802
1803         vp = ZTOV(zp);
1804
1805         if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1806                 goto out;
1807         }
1808
1809         /*
1810          * Need to use rmdir for removing directories.
1811          */
1812         if (vp->v_type == VDIR) {
1813                 error = EPERM;
1814                 goto out;
1815         }
1816
1817         vnevent_remove(vp, dvp, name, ct);
1818
1819         if (realnmp)
1820                 dnlc_remove(dvp, realnmp->pn_buf);
1821         else
1822                 dnlc_remove(dvp, name);
1823
1824         VI_LOCK(vp);
1825         may_delete_now = vp->v_count == 1 && !vn_has_cached_data(vp);
1826         VI_UNLOCK(vp);
1827
1828         /*
1829          * We may delete the znode now, or we may put it in the unlinked set;
1830          * it depends on whether we're the last link, and on whether there are
1831          * other holds on the vnode.  So we dmu_tx_hold() the right things to
1832          * allow for either case.
1833          */
1834         obj = zp->z_id;
1835         tx = dmu_tx_create(zfsvfs->z_os);
1836         dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1837         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1838         zfs_sa_upgrade_txholds(tx, zp);
1839         zfs_sa_upgrade_txholds(tx, dzp);
1840         if (may_delete_now) {
1841                 toobig =
1842                     zp->z_size > zp->z_blksz * DMU_MAX_DELETEBLKCNT;
1843                 /* if the file is too big, only hold_free a token amount */
1844                 dmu_tx_hold_free(tx, zp->z_id, 0,
1845                     (toobig ? DMU_MAX_ACCESS : DMU_OBJECT_END));
1846         }
1847
1848         /* are there any extended attributes? */
1849         error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1850             &xattr_obj, sizeof (xattr_obj));
1851         if (error == 0 && xattr_obj) {
1852                 error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1853                 ASSERT3U(error, ==, 0);
1854                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1855                 dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1856         }
1857
1858         mutex_enter(&zp->z_lock);
1859         if ((acl_obj = zfs_external_acl(zp)) != 0 && may_delete_now)
1860                 dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1861         mutex_exit(&zp->z_lock);
1862
1863         /* charge as an update -- would be nice not to charge at all */
1864         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1865
1866         error = dmu_tx_assign(tx, TXG_NOWAIT);
1867         if (error) {
1868                 zfs_dirent_unlock(dl);
1869                 VN_RELE(vp);
1870                 if (xzp)
1871                         VN_RELE(ZTOV(xzp));
1872                 if (error == ERESTART) {
1873                         dmu_tx_wait(tx);
1874                         dmu_tx_abort(tx);
1875                         goto top;
1876                 }
1877                 if (realnmp)
1878                         pn_free(realnmp);
1879                 dmu_tx_abort(tx);
1880                 ZFS_EXIT(zfsvfs);
1881                 return (error);
1882         }
1883
1884         /*
1885          * Remove the directory entry.
1886          */
1887         error = zfs_link_destroy(dl, zp, tx, zflg, &unlinked);
1888
1889         if (error) {
1890                 dmu_tx_commit(tx);
1891                 goto out;
1892         }
1893
1894         if (unlinked) {
1895
1896                 /*
1897                  * Hold z_lock so that we can make sure that the ACL obj
1898                  * hasn't changed.  Could have been deleted due to
1899                  * zfs_sa_upgrade().
1900                  */
1901                 mutex_enter(&zp->z_lock);
1902                 VI_LOCK(vp);
1903                 (void) sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1904                     &xattr_obj_unlinked, sizeof (xattr_obj_unlinked));
1905                 delete_now = may_delete_now && !toobig &&
1906                     vp->v_count == 1 && !vn_has_cached_data(vp) &&
1907                     xattr_obj == xattr_obj_unlinked && zfs_external_acl(zp) ==
1908                     acl_obj;
1909                 VI_UNLOCK(vp);
1910         }
1911
1912         if (delete_now) {
1913                 if (xattr_obj_unlinked) {
1914                         ASSERT3U(xzp->z_links, ==, 2);
1915                         mutex_enter(&xzp->z_lock);
1916                         xzp->z_unlinked = 1;
1917                         xzp->z_links = 0;
1918                         error = sa_update(xzp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
1919                             &xzp->z_links, sizeof (xzp->z_links), tx);
1920                         ASSERT3U(error,  ==,  0);
1921                         mutex_exit(&xzp->z_lock);
1922                         zfs_unlinked_add(xzp, tx);
1923
1924                         if (zp->z_is_sa)
1925                                 error = sa_remove(zp->z_sa_hdl,
1926                                     SA_ZPL_XATTR(zfsvfs), tx);
1927                         else
1928                                 error = sa_update(zp->z_sa_hdl,
1929                                     SA_ZPL_XATTR(zfsvfs), &null_xattr,
1930                                     sizeof (uint64_t), tx);
1931                         ASSERT3U(error, ==, 0);
1932                 }
1933                 VI_LOCK(vp);
1934                 vp->v_count--;
1935                 ASSERT3U(vp->v_count, ==, 0);
1936                 VI_UNLOCK(vp);
1937                 mutex_exit(&zp->z_lock);
1938                 zfs_znode_delete(zp, tx);
1939         } else if (unlinked) {
1940                 mutex_exit(&zp->z_lock);
1941                 zfs_unlinked_add(zp, tx);
1942         }
1943
1944         txtype = TX_REMOVE;
1945         if (flags & FIGNORECASE)
1946                 txtype |= TX_CI;
1947         zfs_log_remove(zilog, tx, txtype, dzp, name, obj);
1948
1949         dmu_tx_commit(tx);
1950 out:
1951         if (realnmp)
1952                 pn_free(realnmp);
1953
1954         zfs_dirent_unlock(dl);
1955
1956         if (!delete_now)
1957                 VN_RELE(vp);
1958         if (xzp)
1959                 VN_RELE(ZTOV(xzp));
1960
1961         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1962                 zil_commit(zilog, 0);
1963
1964         ZFS_EXIT(zfsvfs);
1965         return (error);
1966 }
1967
1968 /*
1969  * Create a new directory and insert it into dvp using the name
1970  * provided.  Return a pointer to the inserted directory.
1971  *
1972  *      IN:     dvp     - vnode of directory to add subdir to.
1973  *              dirname - name of new directory.
1974  *              vap     - attributes of new directory.
1975  *              cr      - credentials of caller.
1976  *              ct      - caller context
1977  *              vsecp   - ACL to be set
1978  *
1979  *      OUT:    vpp     - vnode of created directory.
1980  *
1981  *      RETURN: 0 if success
1982  *              error code if failure
1983  *
1984  * Timestamps:
1985  *      dvp - ctime|mtime updated
1986  *       vp - ctime|mtime|atime updated
1987  */
1988 /*ARGSUSED*/
1989 static int
1990 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr,
1991     caller_context_t *ct, int flags, vsecattr_t *vsecp)
1992 {
1993         znode_t         *zp, *dzp = VTOZ(dvp);
1994         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1995         zilog_t         *zilog;
1996         zfs_dirlock_t   *dl;
1997         uint64_t        txtype;
1998         dmu_tx_t        *tx;
1999         int             error;
2000         int             zf = ZNEW;
2001         ksid_t          *ksid;
2002         uid_t           uid;
2003         gid_t           gid = crgetgid(cr);
2004         zfs_acl_ids_t   acl_ids;
2005         boolean_t       fuid_dirtied;
2006
2007         ASSERT(vap->va_type == VDIR);
2008
2009         /*
2010          * If we have an ephemeral id, ACL, or XVATTR then
2011          * make sure file system is at proper version
2012          */
2013
2014         ksid = crgetsid(cr, KSID_OWNER);
2015         if (ksid)
2016                 uid = ksid_getid(ksid);
2017         else
2018                 uid = crgetuid(cr);
2019         if (zfsvfs->z_use_fuids == B_FALSE &&
2020             (vsecp || (vap->va_mask & AT_XVATTR) ||
2021             IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
2022                 return (EINVAL);
2023
2024         ZFS_ENTER(zfsvfs);
2025         ZFS_VERIFY_ZP(dzp);
2026         zilog = zfsvfs->z_log;
2027
2028         if (dzp->z_pflags & ZFS_XATTR) {
2029                 ZFS_EXIT(zfsvfs);
2030                 return (EINVAL);
2031         }
2032
2033         if (zfsvfs->z_utf8 && u8_validate(dirname,
2034             strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
2035                 ZFS_EXIT(zfsvfs);
2036                 return (EILSEQ);
2037         }
2038         if (flags & FIGNORECASE)
2039                 zf |= ZCILOOK;
2040
2041         if (vap->va_mask & AT_XVATTR) {
2042                 if ((error = secpolicy_xvattr(dvp, (xvattr_t *)vap,
2043                     crgetuid(cr), cr, vap->va_type)) != 0) {
2044                         ZFS_EXIT(zfsvfs);
2045                         return (error);
2046                 }
2047         }
2048
2049         if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
2050             vsecp, &acl_ids)) != 0) {
2051                 ZFS_EXIT(zfsvfs);
2052                 return (error);
2053         }
2054         /*
2055          * First make sure the new directory doesn't exist.
2056          *
2057          * Existence is checked first to make sure we don't return
2058          * EACCES instead of EEXIST which can cause some applications
2059          * to fail.
2060          */
2061 top:
2062         *vpp = NULL;
2063
2064         if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, zf,
2065             NULL, NULL)) {
2066                 zfs_acl_ids_free(&acl_ids);
2067                 ZFS_EXIT(zfsvfs);
2068                 return (error);
2069         }
2070
2071         if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr)) {
2072                 zfs_acl_ids_free(&acl_ids);
2073                 zfs_dirent_unlock(dl);
2074                 ZFS_EXIT(zfsvfs);
2075                 return (error);
2076         }
2077
2078         if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
2079                 zfs_acl_ids_free(&acl_ids);
2080                 zfs_dirent_unlock(dl);
2081                 ZFS_EXIT(zfsvfs);
2082                 return (EDQUOT);
2083         }
2084
2085         /*
2086          * Add a new entry to the directory.
2087          */
2088         tx = dmu_tx_create(zfsvfs->z_os);
2089         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
2090         dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
2091         fuid_dirtied = zfsvfs->z_fuid_dirty;
2092         if (fuid_dirtied)
2093                 zfs_fuid_txhold(zfsvfs, tx);
2094         if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
2095                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
2096                     acl_ids.z_aclp->z_acl_bytes);
2097         }
2098
2099         dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
2100             ZFS_SA_BASE_ATTR_SIZE);
2101
2102         error = dmu_tx_assign(tx, TXG_NOWAIT);
2103         if (error) {
2104                 zfs_dirent_unlock(dl);
2105                 if (error == ERESTART) {
2106                         dmu_tx_wait(tx);
2107                         dmu_tx_abort(tx);
2108                         goto top;
2109                 }
2110                 zfs_acl_ids_free(&acl_ids);
2111                 dmu_tx_abort(tx);
2112                 ZFS_EXIT(zfsvfs);
2113                 return (error);
2114         }
2115
2116         /*
2117          * Create new node.
2118          */
2119         zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
2120
2121         if (fuid_dirtied)
2122                 zfs_fuid_sync(zfsvfs, tx);
2123
2124         /*
2125          * Now put new name in parent dir.
2126          */
2127         (void) zfs_link_create(dl, zp, tx, ZNEW);
2128
2129         *vpp = ZTOV(zp);
2130
2131         txtype = zfs_log_create_txtype(Z_DIR, vsecp, vap);
2132         if (flags & FIGNORECASE)
2133                 txtype |= TX_CI;
2134         zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, vsecp,
2135             acl_ids.z_fuidp, vap);
2136
2137         zfs_acl_ids_free(&acl_ids);
2138
2139         dmu_tx_commit(tx);
2140
2141         zfs_dirent_unlock(dl);
2142
2143         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2144                 zil_commit(zilog, 0);
2145
2146         ZFS_EXIT(zfsvfs);
2147         return (0);
2148 }
2149
2150 /*
2151  * Remove a directory subdir entry.  If the current working
2152  * directory is the same as the subdir to be removed, the
2153  * remove will fail.
2154  *
2155  *      IN:     dvp     - vnode of directory to remove from.
2156  *              name    - name of directory to be removed.
2157  *              cwd     - vnode of current working directory.
2158  *              cr      - credentials of caller.
2159  *              ct      - caller context
2160  *              flags   - case flags
2161  *
2162  *      RETURN: 0 if success
2163  *              error code if failure
2164  *
2165  * Timestamps:
2166  *      dvp - ctime|mtime updated
2167  */
2168 /*ARGSUSED*/
2169 static int
2170 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr,
2171     caller_context_t *ct, int flags)
2172 {
2173         znode_t         *dzp = VTOZ(dvp);
2174         znode_t         *zp;
2175         vnode_t         *vp;
2176         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
2177         zilog_t         *zilog;
2178         zfs_dirlock_t   *dl;
2179         dmu_tx_t        *tx;
2180         int             error;
2181         int             zflg = ZEXISTS;
2182
2183         ZFS_ENTER(zfsvfs);
2184         ZFS_VERIFY_ZP(dzp);
2185         zilog = zfsvfs->z_log;
2186
2187         if (flags & FIGNORECASE)
2188                 zflg |= ZCILOOK;
2189 top:
2190         zp = NULL;
2191
2192         /*
2193          * Attempt to lock directory; fail if entry doesn't exist.
2194          */
2195         if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
2196             NULL, NULL)) {
2197                 ZFS_EXIT(zfsvfs);
2198                 return (error);
2199         }
2200
2201         vp = ZTOV(zp);
2202
2203         if (error = zfs_zaccess_delete(dzp, zp, cr)) {
2204                 goto out;
2205         }
2206
2207         if (vp->v_type != VDIR) {
2208                 error = ENOTDIR;
2209                 goto out;
2210         }
2211
2212         if (vp == cwd) {
2213                 error = EINVAL;
2214                 goto out;
2215         }
2216
2217         vnevent_rmdir(vp, dvp, name, ct);
2218
2219         /*
2220          * Grab a lock on the directory to make sure that noone is
2221          * trying to add (or lookup) entries while we are removing it.
2222          */
2223         rw_enter(&zp->z_name_lock, RW_WRITER);
2224
2225         /*
2226          * Grab a lock on the parent pointer to make sure we play well
2227          * with the treewalk and directory rename code.
2228          */
2229         rw_enter(&zp->z_parent_lock, RW_WRITER);
2230
2231         tx = dmu_tx_create(zfsvfs->z_os);
2232         dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
2233         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2234         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
2235         zfs_sa_upgrade_txholds(tx, zp);
2236         zfs_sa_upgrade_txholds(tx, dzp);
2237         error = dmu_tx_assign(tx, TXG_NOWAIT);
2238         if (error) {
2239                 rw_exit(&zp->z_parent_lock);
2240                 rw_exit(&zp->z_name_lock);
2241                 zfs_dirent_unlock(dl);
2242                 VN_RELE(vp);
2243                 if (error == ERESTART) {
2244                         dmu_tx_wait(tx);
2245                         dmu_tx_abort(tx);
2246                         goto top;
2247                 }
2248                 dmu_tx_abort(tx);
2249                 ZFS_EXIT(zfsvfs);
2250                 return (error);
2251         }
2252
2253 #ifdef FREEBSD_NAMECACHE
2254         cache_purge(dvp);
2255 #endif
2256
2257         error = zfs_link_destroy(dl, zp, tx, zflg, NULL);
2258
2259         if (error == 0) {
2260                 uint64_t txtype = TX_RMDIR;
2261                 if (flags & FIGNORECASE)
2262                         txtype |= TX_CI;
2263                 zfs_log_remove(zilog, tx, txtype, dzp, name, ZFS_NO_OBJECT);
2264         }
2265
2266         dmu_tx_commit(tx);
2267
2268         rw_exit(&zp->z_parent_lock);
2269         rw_exit(&zp->z_name_lock);
2270 #ifdef FREEBSD_NAMECACHE
2271         cache_purge(vp);
2272 #endif
2273 out:
2274         zfs_dirent_unlock(dl);
2275
2276         VN_RELE(vp);
2277
2278         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2279                 zil_commit(zilog, 0);
2280
2281         ZFS_EXIT(zfsvfs);
2282         return (error);
2283 }
2284
2285 /*
2286  * Read as many directory entries as will fit into the provided
2287  * buffer from the given directory cursor position (specified in
2288  * the uio structure.
2289  *
2290  *      IN:     vp      - vnode of directory to read.
2291  *              uio     - structure supplying read location, range info,
2292  *                        and return buffer.
2293  *              cr      - credentials of caller.
2294  *              ct      - caller context
2295  *              flags   - case flags
2296  *
2297  *      OUT:    uio     - updated offset and range, buffer filled.
2298  *              eofp    - set to true if end-of-file detected.
2299  *
2300  *      RETURN: 0 if success
2301  *              error code if failure
2302  *
2303  * Timestamps:
2304  *      vp - atime updated
2305  *
2306  * Note that the low 4 bits of the cookie returned by zap is always zero.
2307  * This allows us to use the low range for "special" directory entries:
2308  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
2309  * we use the offset 2 for the '.zfs' directory.
2310  */
2311 /* ARGSUSED */
2312 static int
2313 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp, int *ncookies, u_long **cookies)
2314 {
2315         znode_t         *zp = VTOZ(vp);
2316         iovec_t         *iovp;
2317         edirent_t       *eodp;
2318         dirent64_t      *odp;
2319         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
2320         objset_t        *os;
2321         caddr_t         outbuf;
2322         size_t          bufsize;
2323         zap_cursor_t    zc;
2324         zap_attribute_t zap;
2325         uint_t          bytes_wanted;
2326         uint64_t        offset; /* must be unsigned; checks for < 1 */
2327         uint64_t        parent;
2328         int             local_eof;
2329         int             outcount;
2330         int             error;
2331         uint8_t         prefetch;
2332         boolean_t       check_sysattrs;
2333         uint8_t         type;
2334         int             ncooks;
2335         u_long          *cooks = NULL;
2336         int             flags = 0;
2337
2338         ZFS_ENTER(zfsvfs);
2339         ZFS_VERIFY_ZP(zp);
2340
2341         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
2342             &parent, sizeof (parent))) != 0) {
2343                 ZFS_EXIT(zfsvfs);
2344                 return (error);
2345         }
2346
2347         /*
2348          * If we are not given an eof variable,
2349          * use a local one.
2350          */
2351         if (eofp == NULL)
2352                 eofp = &local_eof;
2353
2354         /*
2355          * Check for valid iov_len.
2356          */
2357         if (uio->uio_iov->iov_len <= 0) {
2358                 ZFS_EXIT(zfsvfs);
2359                 return (EINVAL);
2360         }
2361
2362         /*
2363          * Quit if directory has been removed (posix)
2364          */
2365         if ((*eofp = zp->z_unlinked) != 0) {
2366                 ZFS_EXIT(zfsvfs);
2367                 return (0);
2368         }
2369
2370         error = 0;
2371         os = zfsvfs->z_os;
2372         offset = uio->uio_loffset;
2373         prefetch = zp->z_zn_prefetch;
2374
2375         /*
2376          * Initialize the iterator cursor.
2377          */
2378         if (offset <= 3) {
2379                 /*
2380                  * Start iteration from the beginning of the directory.
2381                  */
2382                 zap_cursor_init(&zc, os, zp->z_id);
2383         } else {
2384                 /*
2385                  * The offset is a serialized cursor.
2386                  */
2387                 zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
2388         }
2389
2390         /*
2391          * Get space to change directory entries into fs independent format.
2392          */
2393         iovp = uio->uio_iov;
2394         bytes_wanted = iovp->iov_len;
2395         if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
2396                 bufsize = bytes_wanted;
2397                 outbuf = kmem_alloc(bufsize, KM_SLEEP);
2398                 odp = (struct dirent64 *)outbuf;
2399         } else {
2400                 bufsize = bytes_wanted;
2401                 odp = (struct dirent64 *)iovp->iov_base;
2402         }
2403         eodp = (struct edirent *)odp;
2404
2405         if (ncookies != NULL) {
2406                 /*
2407                  * Minimum entry size is dirent size and 1 byte for a file name.
2408                  */
2409                 ncooks = uio->uio_resid / (sizeof(struct dirent) - sizeof(((struct dirent *)NULL)->d_name) + 1);
2410                 cooks = malloc(ncooks * sizeof(u_long), M_TEMP, M_WAITOK);
2411                 *cookies = cooks;
2412                 *ncookies = ncooks;
2413         }
2414         /*
2415          * If this VFS supports the system attribute view interface; and
2416          * we're looking at an extended attribute directory; and we care
2417          * about normalization conflicts on this vfs; then we must check
2418          * for normalization conflicts with the sysattr name space.
2419          */
2420 #ifdef TODO
2421         check_sysattrs = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
2422             (vp->v_flag & V_XATTRDIR) && zfsvfs->z_norm &&
2423             (flags & V_RDDIR_ENTFLAGS);
2424 #else
2425         check_sysattrs = 0;
2426 #endif
2427
2428         /*
2429          * Transform to file-system independent format
2430          */
2431         outcount = 0;
2432         while (outcount < bytes_wanted) {
2433                 ino64_t objnum;
2434                 ushort_t reclen;
2435                 off64_t *next = NULL;
2436
2437                 /*
2438                  * Special case `.', `..', and `.zfs'.
2439                  */
2440                 if (offset == 0) {
2441                         (void) strcpy(zap.za_name, ".");
2442                         zap.za_normalization_conflict = 0;
2443                         objnum = zp->z_id;
2444                         type = DT_DIR;
2445                 } else if (offset == 1) {
2446                         (void) strcpy(zap.za_name, "..");
2447                         zap.za_normalization_conflict = 0;
2448                         objnum = parent;
2449                         type = DT_DIR;
2450                 } else if (offset == 2 && zfs_show_ctldir(zp)) {
2451                         (void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
2452                         zap.za_normalization_conflict = 0;
2453                         objnum = ZFSCTL_INO_ROOT;
2454                         type = DT_DIR;
2455                 } else {
2456                         /*
2457                          * Grab next entry.
2458                          */
2459                         if (error = zap_cursor_retrieve(&zc, &zap)) {
2460                                 if ((*eofp = (error == ENOENT)) != 0)
2461                                         break;
2462                                 else
2463                                         goto update;
2464                         }
2465
2466                         if (zap.za_integer_length != 8 ||
2467                             zap.za_num_integers != 1) {
2468                                 cmn_err(CE_WARN, "zap_readdir: bad directory "
2469                                     "entry, obj = %lld, offset = %lld\n",
2470                                     (u_longlong_t)zp->z_id,
2471                                     (u_longlong_t)offset);
2472                                 error = ENXIO;
2473                                 goto update;
2474                         }
2475
2476                         objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
2477                         /*
2478                          * MacOS X can extract the object type here such as:
2479                          * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2480                          */
2481                         type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2482
2483                         if (check_sysattrs && !zap.za_normalization_conflict) {
2484 #ifdef TODO
2485                                 zap.za_normalization_conflict =
2486                                     xattr_sysattr_casechk(zap.za_name);
2487 #else
2488                                 panic("%s:%u: TODO", __func__, __LINE__);
2489 #endif
2490                         }
2491                 }
2492
2493                 if (flags & V_RDDIR_ACCFILTER) {
2494                         /*
2495                          * If we have no access at all, don't include
2496                          * this entry in the returned information
2497                          */
2498                         znode_t *ezp;
2499                         if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
2500                                 goto skip_entry;
2501                         if (!zfs_has_access(ezp, cr)) {
2502                                 VN_RELE(ZTOV(ezp));
2503                                 goto skip_entry;
2504                         }
2505                         VN_RELE(ZTOV(ezp));
2506                 }
2507
2508                 if (flags & V_RDDIR_ENTFLAGS)
2509                         reclen = EDIRENT_RECLEN(strlen(zap.za_name));
2510                 else
2511                         reclen = DIRENT64_RECLEN(strlen(zap.za_name));
2512
2513                 /*
2514                  * Will this entry fit in the buffer?
2515                  */
2516                 if (outcount + reclen > bufsize) {
2517                         /*
2518                          * Did we manage to fit anything in the buffer?
2519                          */
2520                         if (!outcount) {
2521                                 error = EINVAL;
2522                                 goto update;
2523                         }
2524                         break;
2525                 }
2526                 if (flags & V_RDDIR_ENTFLAGS) {
2527                         /*
2528                          * Add extended flag entry:
2529                          */
2530                         eodp->ed_ino = objnum;
2531                         eodp->ed_reclen = reclen;
2532                         /* NOTE: ed_off is the offset for the *next* entry */
2533                         next = &(eodp->ed_off);
2534                         eodp->ed_eflags = zap.za_normalization_conflict ?
2535                             ED_CASE_CONFLICT : 0;
2536                         (void) strncpy(eodp->ed_name, zap.za_name,
2537                             EDIRENT_NAMELEN(reclen));
2538                         eodp = (edirent_t *)((intptr_t)eodp + reclen);
2539                 } else {
2540                         /*
2541                          * Add normal entry:
2542                          */
2543                         odp->d_ino = objnum;
2544                         odp->d_reclen = reclen;
2545                         odp->d_namlen = strlen(zap.za_name);
2546                         (void) strlcpy(odp->d_name, zap.za_name, odp->d_namlen + 1);
2547                         odp->d_type = type;
2548                         odp = (dirent64_t *)((intptr_t)odp + reclen);
2549                 }
2550                 outcount += reclen;
2551
2552                 ASSERT(outcount <= bufsize);
2553
2554                 /* Prefetch znode */
2555                 if (prefetch)
2556                         dmu_prefetch(os, objnum, 0, 0);
2557
2558         skip_entry:
2559                 /*
2560                  * Move to the next entry, fill in the previous offset.
2561                  */
2562                 if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
2563                         zap_cursor_advance(&zc);
2564                         offset = zap_cursor_serialize(&zc);
2565                 } else {
2566                         offset += 1;
2567                 }
2568
2569                 if (cooks != NULL) {
2570                         *cooks++ = offset;
2571                         ncooks--;
2572                         KASSERT(ncooks >= 0, ("ncookies=%d", ncooks));
2573                 }
2574         }
2575         zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
2576
2577         /* Subtract unused cookies */
2578         if (ncookies != NULL)
2579                 *ncookies -= ncooks;
2580
2581         if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
2582                 iovp->iov_base += outcount;
2583                 iovp->iov_len -= outcount;
2584                 uio->uio_resid -= outcount;
2585         } else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
2586                 /*
2587                  * Reset the pointer.
2588                  */
2589                 offset = uio->uio_loffset;
2590         }
2591
2592 update:
2593         zap_cursor_fini(&zc);
2594         if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
2595                 kmem_free(outbuf, bufsize);
2596
2597         if (error == ENOENT)
2598                 error = 0;
2599
2600         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2601
2602         uio->uio_loffset = offset;
2603         ZFS_EXIT(zfsvfs);
2604         if (error != 0 && cookies != NULL) {
2605                 free(*cookies, M_TEMP);
2606                 *cookies = NULL;
2607                 *ncookies = 0;
2608         }
2609         return (error);
2610 }
2611
2612 ulong_t zfs_fsync_sync_cnt = 4;
2613
2614 static int
2615 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
2616 {
2617         znode_t *zp = VTOZ(vp);
2618         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2619
2620         (void) tsd_set(zfs_fsyncer_key, (void *)zfs_fsync_sync_cnt);
2621
2622         if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) {
2623                 ZFS_ENTER(zfsvfs);
2624                 ZFS_VERIFY_ZP(zp);
2625                 zil_commit(zfsvfs->z_log, zp->z_id);
2626                 ZFS_EXIT(zfsvfs);
2627         }
2628         return (0);
2629 }
2630
2631
2632 /*
2633  * Get the requested file attributes and place them in the provided
2634  * vattr structure.
2635  *
2636  *      IN:     vp      - vnode of file.
2637  *              vap     - va_mask identifies requested attributes.
2638  *                        If AT_XVATTR set, then optional attrs are requested
2639  *              flags   - ATTR_NOACLCHECK (CIFS server context)
2640  *              cr      - credentials of caller.
2641  *              ct      - caller context
2642  *
2643  *      OUT:    vap     - attribute values.
2644  *
2645  *      RETURN: 0 (always succeeds)
2646  */
2647 /* ARGSUSED */
2648 static int
2649 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2650     caller_context_t *ct)
2651 {
2652         znode_t *zp = VTOZ(vp);
2653         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2654         int     error = 0;
2655         uint32_t blksize;
2656         u_longlong_t nblocks;
2657         uint64_t links;
2658         uint64_t mtime[2], ctime[2], crtime[2], rdev;
2659         xvattr_t *xvap = (xvattr_t *)vap;       /* vap may be an xvattr_t * */
2660         xoptattr_t *xoap = NULL;
2661         boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2662         sa_bulk_attr_t bulk[4];
2663         int count = 0;
2664
2665         ZFS_ENTER(zfsvfs);
2666         ZFS_VERIFY_ZP(zp);
2667
2668         zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
2669
2670         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
2671         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
2672         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &crtime, 16);
2673         if (vp->v_type == VBLK || vp->v_type == VCHR)
2674                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_RDEV(zfsvfs), NULL,
2675                     &rdev, 8);
2676
2677         if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
2678                 ZFS_EXIT(zfsvfs);
2679                 return (error);
2680         }
2681
2682         /*
2683          * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2684          * Also, if we are the owner don't bother, since owner should
2685          * always be allowed to read basic attributes of file.
2686          */
2687         if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
2688             (vap->va_uid != crgetuid(cr))) {
2689                 if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2690                     skipaclchk, cr)) {
2691                         ZFS_EXIT(zfsvfs);
2692                         return (error);
2693                 }
2694         }
2695
2696         /*
2697          * Return all attributes.  It's cheaper to provide the answer
2698          * than to determine whether we were asked the question.
2699          */
2700
2701         mutex_enter(&zp->z_lock);
2702         vap->va_type = IFTOVT(zp->z_mode);
2703         vap->va_mode = zp->z_mode & ~S_IFMT;
2704 #ifdef sun
2705         vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
2706 #else
2707         vap->va_fsid = vp->v_mount->mnt_stat.f_fsid.val[0];
2708 #endif
2709         vap->va_nodeid = zp->z_id;
2710         if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp))
2711                 links = zp->z_links + 1;
2712         else
2713                 links = zp->z_links;
2714         vap->va_nlink = MIN(links, LINK_MAX);   /* nlink_t limit! */
2715         vap->va_size = zp->z_size;
2716 #ifdef sun
2717         vap->va_rdev = vp->v_rdev;
2718 #else
2719         if (vp->v_type == VBLK || vp->v_type == VCHR)
2720                 vap->va_rdev = zfs_cmpldev(rdev);
2721 #endif
2722         vap->va_seq = zp->z_seq;
2723         vap->va_flags = 0;      /* FreeBSD: Reset chflags(2) flags. */
2724         vap->va_filerev = zp->z_seq;
2725
2726         /*
2727          * Add in any requested optional attributes and the create time.
2728          * Also set the corresponding bits in the returned attribute bitmap.
2729          */
2730         if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2731                 if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2732                         xoap->xoa_archive =
2733                             ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2734                         XVA_SET_RTN(xvap, XAT_ARCHIVE);
2735                 }
2736
2737                 if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2738                         xoap->xoa_readonly =
2739                             ((zp->z_pflags & ZFS_READONLY) != 0);
2740                         XVA_SET_RTN(xvap, XAT_READONLY);
2741                 }
2742
2743                 if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2744                         xoap->xoa_system =
2745                             ((zp->z_pflags & ZFS_SYSTEM) != 0);
2746                         XVA_SET_RTN(xvap, XAT_SYSTEM);
2747                 }
2748
2749                 if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2750                         xoap->xoa_hidden =
2751                             ((zp->z_pflags & ZFS_HIDDEN) != 0);
2752                         XVA_SET_RTN(xvap, XAT_HIDDEN);
2753                 }
2754
2755                 if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2756                         xoap->xoa_nounlink =
2757                             ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2758                         XVA_SET_RTN(xvap, XAT_NOUNLINK);
2759                 }
2760
2761                 if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2762                         xoap->xoa_immutable =
2763                             ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2764                         XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2765                 }
2766
2767                 if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2768                         xoap->xoa_appendonly =
2769                             ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2770                         XVA_SET_RTN(xvap, XAT_APPENDONLY);
2771                 }
2772
2773                 if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2774                         xoap->xoa_nodump =
2775                             ((zp->z_pflags & ZFS_NODUMP) != 0);
2776                         XVA_SET_RTN(xvap, XAT_NODUMP);
2777                 }
2778
2779                 if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2780                         xoap->xoa_opaque =
2781                             ((zp->z_pflags & ZFS_OPAQUE) != 0);
2782                         XVA_SET_RTN(xvap, XAT_OPAQUE);
2783                 }
2784
2785                 if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2786                         xoap->xoa_av_quarantined =
2787                             ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2788                         XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2789                 }
2790
2791                 if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2792                         xoap->xoa_av_modified =
2793                             ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2794                         XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2795                 }
2796
2797                 if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2798                     vp->v_type == VREG) {
2799                         zfs_sa_get_scanstamp(zp, xvap);
2800                 }
2801
2802                 if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
2803                         uint64_t times[2];
2804
2805                         (void) sa_lookup(zp->z_sa_hdl, SA_ZPL_CRTIME(zfsvfs),
2806                             times, sizeof (times));
2807                         ZFS_TIME_DECODE(&xoap->xoa_createtime, times);
2808                         XVA_SET_RTN(xvap, XAT_CREATETIME);
2809                 }
2810
2811                 if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2812                         xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2813                         XVA_SET_RTN(xvap, XAT_REPARSE);
2814                 }
2815                 if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2816                         xoap->xoa_generation = zp->z_gen;
2817                         XVA_SET_RTN(xvap, XAT_GEN);
2818                 }
2819
2820                 if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2821                         xoap->xoa_offline =
2822                             ((zp->z_pflags & ZFS_OFFLINE) != 0);
2823                         XVA_SET_RTN(xvap, XAT_OFFLINE);
2824                 }
2825
2826                 if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2827                         xoap->xoa_sparse =
2828                             ((zp->z_pflags & ZFS_SPARSE) != 0);
2829                         XVA_SET_RTN(xvap, XAT_SPARSE);
2830                 }
2831         }
2832
2833         ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2834         ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2835         ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2836         ZFS_TIME_DECODE(&vap->va_birthtime, crtime);
2837
2838         mutex_exit(&zp->z_lock);
2839
2840         sa_object_size(zp->z_sa_hdl, &blksize, &nblocks);
2841         vap->va_blksize = blksize;
2842         vap->va_bytes = nblocks << 9;   /* nblocks * 512 */
2843
2844         if (zp->z_blksz == 0) {
2845                 /*
2846                  * Block size hasn't been set; suggest maximal I/O transfers.
2847                  */
2848                 vap->va_blksize = zfsvfs->z_max_blksz;
2849         }
2850
2851         ZFS_EXIT(zfsvfs);
2852         return (0);
2853 }
2854
2855 /*
2856  * Set the file attributes to the values contained in the
2857  * vattr structure.
2858  *
2859  *      IN:     vp      - vnode of file to be modified.
2860  *              vap     - new attribute values.
2861  *                        If AT_XVATTR set, then optional attrs are being set
2862  *              flags   - ATTR_UTIME set if non-default time values provided.
2863  *                      - ATTR_NOACLCHECK (CIFS context only).
2864  *              cr      - credentials of caller.
2865  *              ct      - caller context
2866  *
2867  *      RETURN: 0 if success
2868  *              error code if failure
2869  *
2870  * Timestamps:
2871  *      vp - ctime updated, mtime updated if size changed.
2872  */
2873 /* ARGSUSED */
2874 static int
2875 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2876         caller_context_t *ct)
2877 {
2878         znode_t         *zp = VTOZ(vp);
2879         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
2880         zilog_t         *zilog;
2881         dmu_tx_t        *tx;
2882         vattr_t         oldva;
2883         xvattr_t        tmpxvattr;
2884         uint_t          mask = vap->va_mask;
2885         uint_t          saved_mask;
2886         uint64_t        saved_mode;
2887         int             trim_mask = 0;
2888         uint64_t        new_mode;
2889         uint64_t        new_uid, new_gid;
2890         uint64_t        xattr_obj;
2891         uint64_t        mtime[2], ctime[2];
2892         znode_t         *attrzp;
2893         int             need_policy = FALSE;
2894         int             err, err2;
2895         zfs_fuid_info_t *fuidp = NULL;
2896         xvattr_t *xvap = (xvattr_t *)vap;       /* vap may be an xvattr_t * */
2897         xoptattr_t      *xoap;
2898         zfs_acl_t       *aclp;
2899         boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2900         boolean_t       fuid_dirtied = B_FALSE;
2901         sa_bulk_attr_t  bulk[7], xattr_bulk[7];
2902         int             count = 0, xattr_count = 0;
2903
2904         if (mask == 0)
2905                 return (0);
2906
2907         if (mask & AT_NOSET)
2908                 return (EINVAL);
2909
2910         ZFS_ENTER(zfsvfs);
2911         ZFS_VERIFY_ZP(zp);
2912
2913         zilog = zfsvfs->z_log;
2914
2915         /*
2916          * Make sure that if we have ephemeral uid/gid or xvattr specified
2917          * that file system is at proper version level
2918          */
2919
2920         if (zfsvfs->z_use_fuids == B_FALSE &&
2921             (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2922             ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2923             (mask & AT_XVATTR))) {
2924                 ZFS_EXIT(zfsvfs);
2925                 return (EINVAL);
2926         }
2927
2928         if (mask & AT_SIZE && vp->v_type == VDIR) {
2929                 ZFS_EXIT(zfsvfs);
2930                 return (EISDIR);
2931         }
2932
2933         if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2934                 ZFS_EXIT(zfsvfs);
2935                 return (EINVAL);
2936         }
2937
2938         /*
2939          * If this is an xvattr_t, then get a pointer to the structure of
2940          * optional attributes.  If this is NULL, then we have a vattr_t.
2941          */
2942         xoap = xva_getxoptattr(xvap);
2943
2944         xva_init(&tmpxvattr);
2945
2946         /*
2947          * Immutable files can only alter immutable bit and atime
2948          */
2949         if ((zp->z_pflags & ZFS_IMMUTABLE) &&
2950             ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2951             ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2952                 ZFS_EXIT(zfsvfs);
2953                 return (EPERM);
2954         }
2955
2956         if ((mask & AT_SIZE) && (zp->z_pflags & ZFS_READONLY)) {
2957                 ZFS_EXIT(zfsvfs);
2958                 return (EPERM);
2959         }
2960
2961         /*
2962          * Verify timestamps doesn't overflow 32 bits.
2963          * ZFS can handle large timestamps, but 32bit syscalls can't
2964          * handle times greater than 2039.  This check should be removed
2965          * once large timestamps are fully supported.
2966          */
2967         if (mask & (AT_ATIME | AT_MTIME)) {
2968                 if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2969                     ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2970                         ZFS_EXIT(zfsvfs);
2971                         return (EOVERFLOW);
2972                 }
2973         }
2974
2975 top:
2976         attrzp = NULL;
2977         aclp = NULL;
2978
2979         /* Can this be moved to before the top label? */
2980         if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2981                 ZFS_EXIT(zfsvfs);
2982                 return (EROFS);
2983         }
2984
2985         /*
2986          * First validate permissions
2987          */
2988
2989         if (mask & AT_SIZE) {
2990                 /*
2991                  * XXX - Note, we are not providing any open
2992                  * mode flags here (like FNDELAY), so we may
2993                  * block if there are locks present... this
2994                  * should be addressed in openat().
2995                  */
2996                 /* XXX - would it be OK to generate a log record here? */
2997                 err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2998                 if (err) {
2999                         ZFS_EXIT(zfsvfs);
3000                         return (err);
3001                 }
3002         }
3003
3004         if (mask & (AT_ATIME|AT_MTIME) ||
3005             ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
3006             XVA_ISSET_REQ(xvap, XAT_READONLY) ||
3007             XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
3008             XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
3009             XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
3010             XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
3011             XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
3012                 need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
3013                     skipaclchk, cr);
3014         }
3015
3016         if (mask & (AT_UID|AT_GID)) {
3017                 int     idmask = (mask & (AT_UID|AT_GID));
3018                 int     take_owner;
3019                 int     take_group;
3020
3021                 /*
3022                  * NOTE: even if a new mode is being set,
3023                  * we may clear S_ISUID/S_ISGID bits.
3024                  */
3025
3026                 if (!(mask & AT_MODE))
3027                         vap->va_mode = zp->z_mode;
3028
3029                 /*
3030                  * Take ownership or chgrp to group we are a member of
3031                  */
3032
3033                 take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
3034                 take_group = (mask & AT_GID) &&
3035                     zfs_groupmember(zfsvfs, vap->va_gid, cr);
3036
3037                 /*
3038                  * If both AT_UID and AT_GID are set then take_owner and
3039                  * take_group must both be set in order to allow taking
3040                  * ownership.
3041                  *
3042                  * Otherwise, send the check through secpolicy_vnode_setattr()
3043                  *
3044                  */
3045
3046                 if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
3047                     ((idmask == AT_UID) && take_owner) ||
3048                     ((idmask == AT_GID) && take_group)) {
3049                         if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
3050                             skipaclchk, cr) == 0) {
3051                                 /*
3052                                  * Remove setuid/setgid for non-privileged users
3053                                  */
3054                                 secpolicy_setid_clear(vap, vp, cr);
3055                                 trim_mask = (mask & (AT_UID|AT_GID));
3056                         } else {
3057                                 need_policy =  TRUE;
3058                         }
3059                 } else {
3060                         need_policy =  TRUE;
3061                 }
3062         }
3063
3064         mutex_enter(&zp->z_lock);
3065         oldva.va_mode = zp->z_mode;
3066         zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
3067         if (mask & AT_XVATTR) {
3068                 /*
3069                  * Update xvattr mask to include only those attributes
3070                  * that are actually changing.
3071                  *
3072                  * the bits will be restored prior to actually setting
3073                  * the attributes so the caller thinks they were set.
3074                  */
3075                 if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
3076                         if (xoap->xoa_appendonly !=
3077                             ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
3078                                 need_policy = TRUE;
3079                         } else {
3080                                 XVA_CLR_REQ(xvap, XAT_APPENDONLY);
3081                                 XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
3082                         }
3083                 }
3084
3085                 if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
3086                         if (xoap->xoa_nounlink !=
3087                             ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
3088                                 need_policy = TRUE;
3089                         } else {
3090                                 XVA_CLR_REQ(xvap, XAT_NOUNLINK);
3091                                 XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
3092                         }
3093                 }
3094
3095                 if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
3096                         if (xoap->xoa_immutable !=
3097                             ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
3098                                 need_policy = TRUE;
3099                         } else {
3100                                 XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
3101                                 XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
3102                         }
3103                 }
3104
3105                 if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
3106                         if (xoap->xoa_nodump !=
3107                             ((zp->z_pflags & ZFS_NODUMP) != 0)) {
3108                                 need_policy = TRUE;
3109                         } else {
3110                                 XVA_CLR_REQ(xvap, XAT_NODUMP);
3111                                 XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
3112                         }
3113                 }
3114
3115                 if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
3116                         if (xoap->xoa_av_modified !=
3117                             ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
3118                                 need_policy = TRUE;
3119                         } else {
3120                                 XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
3121                                 XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
3122                         }
3123                 }
3124
3125                 if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
3126                         if ((vp->v_type != VREG &&
3127                             xoap->xoa_av_quarantined) ||
3128                             xoap->xoa_av_quarantined !=
3129                             ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
3130                                 need_policy = TRUE;
3131                         } else {
3132                                 XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
3133                                 XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
3134                         }
3135                 }
3136
3137                 if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
3138                         mutex_exit(&zp->z_lock);
3139                         ZFS_EXIT(zfsvfs);
3140                         return (EPERM);
3141                 }
3142
3143                 if (need_policy == FALSE &&
3144                     (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
3145                     XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
3146                         need_policy = TRUE;
3147                 }
3148         }
3149
3150         mutex_exit(&zp->z_lock);
3151
3152         if (mask & AT_MODE) {
3153                 if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
3154                         err = secpolicy_setid_setsticky_clear(vp, vap,
3155                             &oldva, cr);
3156                         if (err) {
3157                                 ZFS_EXIT(zfsvfs);
3158                                 return (err);
3159                         }
3160                         trim_mask |= AT_MODE;
3161                 } else {
3162                         need_policy = TRUE;
3163                 }
3164         }
3165
3166         if (need_policy) {
3167                 /*
3168                  * If trim_mask is set then take ownership
3169                  * has been granted or write_acl is present and user
3170                  * has the ability to modify mode.  In that case remove
3171                  * UID|GID and or MODE from mask so that
3172                  * secpolicy_vnode_setattr() doesn't revoke it.
3173                  */
3174
3175                 if (trim_mask) {
3176                         saved_mask = vap->va_mask;
3177                         vap->va_mask &= ~trim_mask;
3178                         if (trim_mask & AT_MODE) {
3179                                 /*
3180                                  * Save the mode, as secpolicy_vnode_setattr()
3181                                  * will overwrite it with ova.va_mode.
3182                                  */
3183                                 saved_mode = vap->va_mode;
3184                         }
3185                 }
3186                 err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
3187                     (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
3188                 if (err) {
3189                         ZFS_EXIT(zfsvfs);
3190                         return (err);
3191                 }
3192
3193                 if (trim_mask) {
3194                         vap->va_mask |= saved_mask;
3195                         if (trim_mask & AT_MODE) {
3196                                 /*
3197                                  * Recover the mode after
3198                                  * secpolicy_vnode_setattr().
3199                                  */
3200                                 vap->va_mode = saved_mode;
3201                         }
3202                 }
3203         }
3204
3205         /*
3206          * secpolicy_vnode_setattr, or take ownership may have
3207          * changed va_mask
3208          */
3209         mask = vap->va_mask;
3210
3211         if ((mask & (AT_UID | AT_GID))) {
3212                 err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
3213                     &xattr_obj, sizeof (xattr_obj));
3214
3215                 if (err == 0 && xattr_obj) {
3216                         err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp);
3217                         if (err)
3218                                 goto out2;
3219                 }
3220                 if (mask & AT_UID) {
3221                         new_uid = zfs_fuid_create(zfsvfs,
3222                             (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
3223                         if (new_uid != zp->z_uid &&
3224                             zfs_fuid_overquota(zfsvfs, B_FALSE, new_uid)) {
3225                                 if (attrzp)
3226                                         VN_RELE(ZTOV(attrzp));
3227                                 err = EDQUOT;
3228                                 goto out2;
3229                         }
3230                 }
3231
3232                 if (mask & AT_GID) {
3233                         new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
3234                             cr, ZFS_GROUP, &fuidp);
3235                         if (new_gid != zp->z_gid &&
3236                             zfs_fuid_overquota(zfsvfs, B_TRUE, new_gid)) {
3237                                 if (attrzp)
3238                                         VN_RELE(ZTOV(attrzp));
3239                                 err = EDQUOT;
3240                                 goto out2;
3241                         }
3242                 }
3243         }
3244         tx = dmu_tx_create(zfsvfs->z_os);
3245
3246         if (mask & AT_MODE) {
3247                 uint64_t pmode = zp->z_mode;
3248                 uint64_t acl_obj;
3249                 new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
3250
3251                 if (err = zfs_acl_chmod_setattr(zp, &aclp, new_mode))
3252                         goto out;
3253
3254                 mutex_enter(&zp->z_lock);
3255                 if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
3256                         /*
3257                          * Are we upgrading ACL from old V0 format
3258                          * to V1 format?
3259                          */
3260                         if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
3261                             zfs_znode_acl_version(zp) ==
3262                             ZFS_ACL_VERSION_INITIAL) {
3263                                 dmu_tx_hold_free(tx, acl_obj, 0,
3264                                     DMU_OBJECT_END);
3265                                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3266                                     0, aclp->z_acl_bytes);
3267                         } else {
3268                                 dmu_tx_hold_write(tx, acl_obj, 0,
3269                                     aclp->z_acl_bytes);
3270                         }
3271                 } else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3272                         dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3273                             0, aclp->z_acl_bytes);
3274                 }
3275                 mutex_exit(&zp->z_lock);
3276                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3277         } else {
3278                 if ((mask & AT_XVATTR) &&
3279                     XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3280                         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
3281                 else
3282                         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3283         }
3284
3285         if (attrzp) {
3286                 dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, B_FALSE);
3287         }
3288
3289         fuid_dirtied = zfsvfs->z_fuid_dirty;
3290         if (fuid_dirtied)
3291                 zfs_fuid_txhold(zfsvfs, tx);
3292
3293         zfs_sa_upgrade_txholds(tx, zp);
3294
3295         err = dmu_tx_assign(tx, TXG_NOWAIT);
3296         if (err) {
3297                 if (err == ERESTART)
3298                         dmu_tx_wait(tx);
3299                 goto out;
3300         }
3301
3302         count = 0;
3303         /*
3304          * Set each attribute requested.
3305          * We group settings according to the locks they need to acquire.
3306          *
3307          * Note: you cannot set ctime directly, although it will be
3308          * updated as a side-effect of calling this function.
3309          */
3310
3311
3312         if (mask & (AT_UID|AT_GID|AT_MODE))
3313                 mutex_enter(&zp->z_acl_lock);
3314         mutex_enter(&zp->z_lock);
3315
3316         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
3317             &zp->z_pflags, sizeof (zp->z_pflags));
3318
3319         if (attrzp) {
3320                 if (mask & (AT_UID|AT_GID|AT_MODE))
3321                         mutex_enter(&attrzp->z_acl_lock);
3322                 mutex_enter(&attrzp->z_lock);
3323                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3324                     SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
3325                     sizeof (attrzp->z_pflags));
3326         }
3327
3328         if (mask & (AT_UID|AT_GID)) {
3329
3330                 if (mask & AT_UID) {
3331                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
3332                             &new_uid, sizeof (new_uid));
3333                         zp->z_uid = new_uid;
3334                         if (attrzp) {
3335                                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3336                                     SA_ZPL_UID(zfsvfs), NULL, &new_uid,
3337                                     sizeof (new_uid));
3338                                 attrzp->z_uid = new_uid;
3339                         }
3340                 }
3341
3342                 if (mask & AT_GID) {
3343                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
3344                             NULL, &new_gid, sizeof (new_gid));
3345                         zp->z_gid = new_gid;
3346                         if (attrzp) {
3347                                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3348                                     SA_ZPL_GID(zfsvfs), NULL, &new_gid,
3349                                     sizeof (new_gid));
3350                                 attrzp->z_gid = new_gid;
3351                         }
3352                 }
3353                 if (!(mask & AT_MODE)) {
3354                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
3355                             NULL, &new_mode, sizeof (new_mode));
3356                         new_mode = zp->z_mode;
3357                 }
3358                 err = zfs_acl_chown_setattr(zp);
3359                 ASSERT(err == 0);
3360                 if (attrzp) {
3361                         err = zfs_acl_chown_setattr(attrzp);
3362                         ASSERT(err == 0);
3363                 }
3364         }
3365
3366         if (mask & AT_MODE) {
3367                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
3368                     &new_mode, sizeof (new_mode));
3369                 zp->z_mode = new_mode;
3370                 ASSERT3U((uintptr_t)aclp, !=, 0);
3371                 err = zfs_aclset_common(zp, aclp, cr, tx);
3372                 ASSERT3U(err, ==, 0);
3373                 if (zp->z_acl_cached)
3374                         zfs_acl_free(zp->z_acl_cached);
3375                 zp->z_acl_cached = aclp;
3376                 aclp = NULL;
3377         }
3378
3379
3380         if (mask & AT_ATIME) {
3381                 ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
3382                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
3383                     &zp->z_atime, sizeof (zp->z_atime));
3384         }
3385
3386         if (mask & AT_MTIME) {
3387                 ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
3388                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
3389                     mtime, sizeof (mtime));
3390         }
3391
3392         /* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
3393         if (mask & AT_SIZE && !(mask & AT_MTIME)) {
3394                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
3395                     NULL, mtime, sizeof (mtime));
3396                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3397                     &ctime, sizeof (ctime));
3398                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
3399                     B_TRUE);
3400         } else if (mask != 0) {
3401                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3402                     &ctime, sizeof (ctime));
3403                 zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime,
3404                     B_TRUE);
3405                 if (attrzp) {
3406                         SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3407                             SA_ZPL_CTIME(zfsvfs), NULL,
3408                             &ctime, sizeof (ctime));
3409                         zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
3410                             mtime, ctime, B_TRUE);
3411                 }
3412         }
3413         /*
3414          * Do this after setting timestamps to prevent timestamp
3415          * update from toggling bit
3416          */
3417
3418         if (xoap && (mask & AT_XVATTR)) {
3419
3420                 /*
3421                  * restore trimmed off masks
3422                  * so that return masks can be set for caller.
3423                  */
3424
3425                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
3426                         XVA_SET_REQ(xvap, XAT_APPENDONLY);
3427                 }
3428                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
3429                         XVA_SET_REQ(xvap, XAT_NOUNLINK);
3430                 }
3431                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
3432                         XVA_SET_REQ(xvap, XAT_IMMUTABLE);
3433                 }
3434                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
3435                         XVA_SET_REQ(xvap, XAT_NODUMP);
3436                 }
3437                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
3438                         XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
3439                 }
3440                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
3441                         XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
3442                 }
3443
3444                 if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3445                         ASSERT(vp->v_type == VREG);
3446
3447                 zfs_xvattr_set(zp, xvap, tx);
3448         }
3449
3450         if (fuid_dirtied)
3451                 zfs_fuid_sync(zfsvfs, tx);
3452
3453         if (mask != 0)
3454                 zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
3455
3456         mutex_exit(&zp->z_lock);
3457         if (mask & (AT_UID|AT_GID|AT_MODE))
3458                 mutex_exit(&zp->z_acl_lock);
3459
3460         if (attrzp) {
3461                 if (mask & (AT_UID|AT_GID|AT_MODE))
3462                         mutex_exit(&attrzp->z_acl_lock);
3463                 mutex_exit(&attrzp->z_lock);
3464         }
3465 out:
3466         if (err == 0 && attrzp) {
3467                 err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
3468                     xattr_count, tx);
3469                 ASSERT(err2 == 0);
3470         }
3471
3472         if (attrzp)
3473                 VN_RELE(ZTOV(attrzp));
3474         if (aclp)
3475                 zfs_acl_free(aclp);
3476
3477         if (fuidp) {
3478                 zfs_fuid_info_free(fuidp);
3479                 fuidp = NULL;
3480         }
3481
3482         if (err) {
3483                 dmu_tx_abort(tx);
3484                 if (err == ERESTART)
3485                         goto top;
3486         } else {
3487                 err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
3488                 dmu_tx_commit(tx);
3489         }
3490
3491 out2:
3492         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3493                 zil_commit(zilog, 0);
3494
3495         ZFS_EXIT(zfsvfs);
3496         return (err);
3497 }
3498
3499 typedef struct zfs_zlock {
3500         krwlock_t       *zl_rwlock;     /* lock we acquired */
3501         znode_t         *zl_znode;      /* znode we held */
3502         struct zfs_zlock *zl_next;      /* next in list */
3503 } zfs_zlock_t;
3504
3505 /*
3506  * Drop locks and release vnodes that were held by zfs_rename_lock().
3507  */
3508 static void
3509 zfs_rename_unlock(zfs_zlock_t **zlpp)
3510 {
3511         zfs_zlock_t *zl;
3512
3513         while ((zl = *zlpp) != NULL) {
3514                 if (zl->zl_znode != NULL)
3515                         VN_RELE(ZTOV(zl->zl_znode));
3516                 rw_exit(zl->zl_rwlock);
3517                 *zlpp = zl->zl_next;
3518                 kmem_free(zl, sizeof (*zl));
3519         }
3520 }
3521
3522 /*
3523  * Search back through the directory tree, using the ".." entries.
3524  * Lock each directory in the chain to prevent concurrent renames.
3525  * Fail any attempt to move a directory into one of its own descendants.
3526  * XXX - z_parent_lock can overlap with map or grow locks
3527  */
3528 static int
3529 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
3530 {
3531         zfs_zlock_t     *zl;
3532         znode_t         *zp = tdzp;
3533         uint64_t        rootid = zp->z_zfsvfs->z_root;
3534         uint64_t        oidp = zp->z_id;
3535         krwlock_t       *rwlp = &szp->z_parent_lock;
3536         krw_t           rw = RW_WRITER;
3537
3538         /*
3539          * First pass write-locks szp and compares to zp->z_id.
3540          * Later passes read-lock zp and compare to zp->z_parent.
3541          */
3542         do {
3543                 if (!rw_tryenter(rwlp, rw)) {
3544                         /*
3545                          * Another thread is renaming in this path.
3546                          * Note that if we are a WRITER, we don't have any
3547                          * parent_locks held yet.
3548                          */
3549                         if (rw == RW_READER && zp->z_id > szp->z_id) {
3550                                 /*
3551                                  * Drop our locks and restart
3552                                  */
3553                                 zfs_rename_unlock(&zl);
3554                                 *zlpp = NULL;
3555                                 zp = tdzp;
3556                                 oidp = zp->z_id;
3557                                 rwlp = &szp->z_parent_lock;
3558                                 rw = RW_WRITER;
3559                                 continue;
3560                         } else {
3561                                 /*
3562                                  * Wait for other thread to drop its locks
3563                                  */
3564                                 rw_enter(rwlp, rw);
3565                         }
3566                 }
3567
3568                 zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
3569                 zl->zl_rwlock = rwlp;
3570                 zl->zl_znode = NULL;
3571                 zl->zl_next = *zlpp;
3572                 *zlpp = zl;
3573
3574                 if (oidp == szp->z_id)          /* We're a descendant of szp */
3575                         return (EINVAL);
3576
3577                 if (oidp == rootid)             /* We've hit the top */
3578                         return (0);
3579
3580                 if (rw == RW_READER) {          /* i.e. not the first pass */
3581                         int error = zfs_zget(zp->z_zfsvfs, oidp, &zp);
3582                         if (error)
3583                                 return (error);
3584                         zl->zl_znode = zp;
3585                 }
3586                 (void) sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zp->z_zfsvfs),
3587                     &oidp, sizeof (oidp));
3588                 rwlp = &zp->z_parent_lock;
3589                 rw = RW_READER;
3590
3591         } while (zp->z_id != sdzp->z_id);
3592
3593         return (0);
3594 }
3595
3596 /*
3597  * Move an entry from the provided source directory to the target
3598  * directory.  Change the entry name as indicated.
3599  *
3600  *      IN:     sdvp    - Source directory containing the "old entry".
3601  *              snm     - Old entry name.
3602  *              tdvp    - Target directory to contain the "new entry".
3603  *              tnm     - New entry name.
3604  *              cr      - credentials of caller.
3605  *              ct      - caller context
3606  *              flags   - case flags
3607  *
3608  *      RETURN: 0 if success
3609  *              error code if failure
3610  *
3611  * Timestamps:
3612  *      sdvp,tdvp - ctime|mtime updated
3613  */
3614 /*ARGSUSED*/
3615 static int
3616 zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr,
3617     caller_context_t *ct, int flags)
3618 {
3619         znode_t         *tdzp, *szp, *tzp;
3620         znode_t         *sdzp = VTOZ(sdvp);
3621         zfsvfs_t        *zfsvfs = sdzp->z_zfsvfs;
3622         zilog_t         *zilog;
3623         vnode_t         *realvp;
3624         zfs_dirlock_t   *sdl, *tdl;
3625         dmu_tx_t        *tx;
3626         zfs_zlock_t     *zl;
3627         int             cmp, serr, terr;
3628         int             error = 0;
3629         int             zflg = 0;
3630
3631         ZFS_ENTER(zfsvfs);
3632         ZFS_VERIFY_ZP(sdzp);
3633         zilog = zfsvfs->z_log;
3634
3635         /*
3636          * Make sure we have the real vp for the target directory.
3637          */
3638         if (VOP_REALVP(tdvp, &realvp, ct) == 0)
3639                 tdvp = realvp;
3640
3641         if (tdvp->v_vfsp != sdvp->v_vfsp || zfsctl_is_node(tdvp)) {
3642                 ZFS_EXIT(zfsvfs);
3643                 return (EXDEV);
3644         }
3645
3646         tdzp = VTOZ(tdvp);
3647         ZFS_VERIFY_ZP(tdzp);
3648         if (zfsvfs->z_utf8 && u8_validate(tnm,
3649             strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3650                 ZFS_EXIT(zfsvfs);
3651                 return (EILSEQ);
3652         }
3653
3654         if (flags & FIGNORECASE)
3655                 zflg |= ZCILOOK;
3656
3657 top:
3658         szp = NULL;
3659         tzp = NULL;
3660         zl = NULL;
3661
3662         /*
3663          * This is to prevent the creation of links into attribute space
3664          * by renaming a linked file into/outof an attribute directory.
3665          * See the comment in zfs_link() for why this is considered bad.
3666          */
3667         if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3668                 ZFS_EXIT(zfsvfs);
3669                 return (EINVAL);
3670         }
3671
3672         /*
3673          * Lock source and target directory entries.  To prevent deadlock,
3674          * a lock ordering must be defined.  We lock the directory with
3675          * the smallest object id first, or if it's a tie, the one with
3676          * the lexically first name.
3677          */
3678         if (sdzp->z_id < tdzp->z_id) {
3679                 cmp = -1;
3680         } else if (sdzp->z_id > tdzp->z_id) {
3681                 cmp = 1;
3682         } else {
3683                 /*
3684                  * First compare the two name arguments without
3685                  * considering any case folding.
3686                  */
3687                 int nofold = (zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER);
3688
3689                 cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
3690                 ASSERT(error == 0 || !zfsvfs->z_utf8);
3691                 if (cmp == 0) {
3692                         /*
3693                          * POSIX: "If the old argument and the new argument
3694                          * both refer to links to the same existing file,
3695                          * the rename() function shall return successfully
3696                          * and perform no other action."
3697                          */
3698                         ZFS_EXIT(zfsvfs);
3699                         return (0);
3700                 }
3701                 /*
3702                  * If the file system is case-folding, then we may
3703                  * have some more checking to do.  A case-folding file
3704                  * system is either supporting mixed case sensitivity
3705                  * access or is completely case-insensitive.  Note
3706                  * that the file system is always case preserving.
3707                  *
3708                  * In mixed sensitivity mode case sensitive behavior
3709                  * is the default.  FIGNORECASE must be used to
3710                  * explicitly request case insensitive behavior.
3711                  *
3712                  * If the source and target names provided differ only
3713                  * by case (e.g., a request to rename 'tim' to 'Tim'),
3714                  * we will treat this as a special case in the
3715                  * case-insensitive mode: as long as the source name
3716                  * is an exact match, we will allow this to proceed as
3717                  * a name-change request.
3718                  */
3719                 if ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
3720                     (zfsvfs->z_case == ZFS_CASE_MIXED &&
3721                     flags & FIGNORECASE)) &&
3722                     u8_strcmp(snm, tnm, 0, zfsvfs->z_norm, U8_UNICODE_LATEST,
3723                     &error) == 0) {
3724                         /*
3725                          * case preserving rename request, require exact
3726                          * name matches
3727                          */
3728                         zflg |= ZCIEXACT;
3729                         zflg &= ~ZCILOOK;
3730                 }
3731         }
3732
3733         /*
3734          * If the source and destination directories are the same, we should
3735          * grab the z_name_lock of that directory only once.
3736          */
3737         if (sdzp == tdzp) {
3738                 zflg |= ZHAVELOCK;
3739                 rw_enter(&sdzp->z_name_lock, RW_READER);
3740         }
3741
3742         if (cmp < 0) {
3743                 serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
3744                     ZEXISTS | zflg, NULL, NULL);
3745                 terr = zfs_dirent_lock(&tdl,
3746                     tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
3747         } else {
3748                 terr = zfs_dirent_lock(&tdl,
3749                     tdzp, tnm, &tzp, zflg, NULL, NULL);
3750                 serr = zfs_dirent_lock(&sdl,
3751                     sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
3752                     NULL, NULL);
3753         }
3754
3755         if (serr) {
3756                 /*
3757                  * Source entry invalid or not there.
3758                  */
3759                 if (!terr) {
3760                         zfs_dirent_unlock(tdl);
3761                         if (tzp)
3762                                 VN_RELE(ZTOV(tzp));
3763                 }
3764
3765                 if (sdzp == tdzp)
3766                         rw_exit(&sdzp->z_name_lock);
3767
3768                 /*
3769                  * FreeBSD: In OpenSolaris they only check if rename source is
3770                  * ".." here, because "." is handled in their lookup. This is
3771                  * not the case for FreeBSD, so we check for "." explicitly.
3772                  */
3773                 if (strcmp(snm, ".") == 0 || strcmp(snm, "..") == 0)
3774                         serr = EINVAL;
3775                 ZFS_EXIT(zfsvfs);
3776                 return (serr);
3777         }
3778         if (terr) {
3779                 zfs_dirent_unlock(sdl);
3780                 VN_RELE(ZTOV(szp));
3781
3782                 if (sdzp == tdzp)
3783                         rw_exit(&sdzp->z_name_lock);
3784
3785                 if (strcmp(tnm, "..") == 0)
3786                         terr = EINVAL;
3787                 ZFS_EXIT(zfsvfs);
3788                 return (terr);
3789         }
3790
3791         /*
3792          * Must have write access at the source to remove the old entry
3793          * and write access at the target to create the new entry.
3794          * Note that if target and source are the same, this can be
3795          * done in a single check.
3796          */
3797
3798         if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
3799                 goto out;
3800
3801         if (ZTOV(szp)->v_type == VDIR) {
3802                 /*
3803                  * Check to make sure rename is valid.
3804                  * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3805                  */
3806                 if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
3807                         goto out;
3808         }
3809
3810         /*
3811          * Does target exist?
3812          */
3813         if (tzp) {
3814                 /*
3815                  * Source and target must be the same type.
3816                  */
3817                 if (ZTOV(szp)->v_type == VDIR) {
3818                         if (ZTOV(tzp)->v_type != VDIR) {
3819                                 error = ENOTDIR;
3820                                 goto out;
3821                         }
3822                 } else {
3823                         if (ZTOV(tzp)->v_type == VDIR) {
3824                                 error = EISDIR;
3825                                 goto out;
3826                         }
3827                 }
3828                 /*
3829                  * POSIX dictates that when the source and target
3830                  * entries refer to the same file object, rename
3831                  * must do nothing and exit without error.
3832                  */
3833                 if (szp->z_id == tzp->z_id) {
3834                         error = 0;
3835                         goto out;
3836                 }
3837         }
3838
3839         vnevent_rename_src(ZTOV(szp), sdvp, snm, ct);
3840         if (tzp)
3841                 vnevent_rename_dest(ZTOV(tzp), tdvp, tnm, ct);
3842
3843         /*
3844          * notify the target directory if it is not the same
3845          * as source directory.
3846          */
3847         if (tdvp != sdvp) {
3848                 vnevent_rename_dest_dir(tdvp, ct);
3849         }
3850
3851         tx = dmu_tx_create(zfsvfs->z_os);
3852         dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3853         dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
3854         dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3855         dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3856         if (sdzp != tdzp) {
3857                 dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, B_FALSE);
3858                 zfs_sa_upgrade_txholds(tx, tdzp);
3859         }
3860         if (tzp) {
3861                 dmu_tx_hold_sa(tx, tzp->z_sa_hdl, B_FALSE);
3862                 zfs_sa_upgrade_txholds(tx, tzp);
3863         }
3864
3865         zfs_sa_upgrade_txholds(tx, szp);
3866         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3867         error = dmu_tx_assign(tx, TXG_NOWAIT);
3868         if (error) {
3869                 if (zl != NULL)
3870                         zfs_rename_unlock(&zl);
3871                 zfs_dirent_unlock(sdl);
3872                 zfs_dirent_unlock(tdl);
3873
3874                 if (sdzp == tdzp)
3875                         rw_exit(&sdzp->z_name_lock);
3876
3877                 VN_RELE(ZTOV(szp));
3878                 if (tzp)
3879                         VN_RELE(ZTOV(tzp));
3880                 if (error == ERESTART) {
3881                         dmu_tx_wait(tx);
3882                         dmu_tx_abort(tx);
3883                         goto top;
3884                 }
3885                 dmu_tx_abort(tx);
3886                 ZFS_EXIT(zfsvfs);
3887                 return (error);
3888         }
3889
3890         if (tzp)        /* Attempt to remove the existing target */
3891                 error = zfs_link_destroy(tdl, tzp, tx, zflg, NULL);
3892
3893         if (error == 0) {
3894                 error = zfs_link_create(tdl, szp, tx, ZRENAMING);
3895                 if (error == 0) {
3896                         szp->z_pflags |= ZFS_AV_MODIFIED;
3897
3898                         error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
3899                             (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3900                         ASSERT3U(error, ==, 0);
3901
3902                         error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
3903                         if (error == 0) {
3904                                 zfs_log_rename(zilog, tx, TX_RENAME |
3905                                     (flags & FIGNORECASE ? TX_CI : 0), sdzp,
3906                                     sdl->dl_name, tdzp, tdl->dl_name, szp);
3907
3908                                 /*
3909                                  * Update path information for the target vnode
3910                                  */
3911                                 vn_renamepath(tdvp, ZTOV(szp), tnm,
3912                                     strlen(tnm));
3913                         } else {
3914                                 /*
3915                                  * At this point, we have successfully created
3916                                  * the target name, but have failed to remove
3917                                  * the source name.  Since the create was done
3918                                  * with the ZRENAMING flag, there are
3919                                  * complications; for one, the link count is
3920                                  * wrong.  The easiest way to deal with this
3921                                  * is to remove the newly created target, and
3922                                  * return the original error.  This must
3923                                  * succeed; fortunately, it is very unlikely to
3924                                  * fail, since we just created it.
3925                                  */
3926                                 VERIFY3U(zfs_link_destroy(tdl, szp, tx,
3927                                     ZRENAMING, NULL), ==, 0);
3928                         }
3929                 }
3930 #ifdef FREEBSD_NAMECACHE
3931                 if (error == 0) {
3932                         cache_purge(sdvp);
3933                         cache_purge(tdvp);
3934                 }
3935 #endif
3936         }
3937
3938         dmu_tx_commit(tx);
3939 out:
3940         if (zl != NULL)
3941                 zfs_rename_unlock(&zl);
3942
3943         zfs_dirent_unlock(sdl);
3944         zfs_dirent_unlock(tdl);
3945
3946         if (sdzp == tdzp)
3947                 rw_exit(&sdzp->z_name_lock);
3948
3949
3950         VN_RELE(ZTOV(szp));
3951         if (tzp)
3952                 VN_RELE(ZTOV(tzp));
3953
3954         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3955                 zil_commit(zilog, 0);
3956
3957         ZFS_EXIT(zfsvfs);
3958
3959         return (error);
3960 }
3961
3962 /*
3963  * Insert the indicated symbolic reference entry into the directory.
3964  *
3965  *      IN:     dvp     - Directory to contain new symbolic link.
3966  *              link    - Name for new symlink entry.
3967  *              vap     - Attributes of new entry.
3968  *              target  - Target path of new symlink.
3969  *              cr      - credentials of caller.
3970  *              ct      - caller context
3971  *              flags   - case flags
3972  *
3973  *      RETURN: 0 if success
3974  *              error code if failure
3975  *
3976  * Timestamps:
3977  *      dvp - ctime|mtime updated
3978  */
3979 /*ARGSUSED*/
3980 static int
3981 zfs_symlink(vnode_t *dvp, vnode_t **vpp, char *name, vattr_t *vap, char *link,
3982     cred_t *cr, kthread_t *td)
3983 {
3984         znode_t         *zp, *dzp = VTOZ(dvp);
3985         zfs_dirlock_t   *dl;
3986         dmu_tx_t        *tx;
3987         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
3988         zilog_t         *zilog;
3989         uint64_t        len = strlen(link);
3990         int             error;
3991         int             zflg = ZNEW;
3992         zfs_acl_ids_t   acl_ids;
3993         boolean_t       fuid_dirtied;
3994         uint64_t        txtype = TX_SYMLINK;
3995         int             flags = 0;
3996
3997         ASSERT(vap->va_type == VLNK);
3998
3999         ZFS_ENTER(zfsvfs);
4000         ZFS_VERIFY_ZP(dzp);
4001         zilog = zfsvfs->z_log;
4002
4003         if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
4004             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
4005                 ZFS_EXIT(zfsvfs);
4006                 return (EILSEQ);
4007         }
4008         if (flags & FIGNORECASE)
4009                 zflg |= ZCILOOK;
4010
4011         if (len > MAXPATHLEN) {
4012                 ZFS_EXIT(zfsvfs);
4013                 return (ENAMETOOLONG);
4014         }
4015
4016         if ((error = zfs_acl_ids_create(dzp, 0,
4017             vap, cr, NULL, &acl_ids)) != 0) {
4018                 ZFS_EXIT(zfsvfs);
4019                 return (error);
4020         }
4021 top:
4022         /*
4023          * Attempt to lock directory; fail if entry already exists.
4024          */
4025         error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
4026         if (error) {
4027                 zfs_acl_ids_free(&acl_ids);
4028                 ZFS_EXIT(zfsvfs);
4029                 return (error);
4030         }
4031
4032         if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
4033                 zfs_acl_ids_free(&acl_ids);
4034                 zfs_dirent_unlock(dl);
4035                 ZFS_EXIT(zfsvfs);
4036                 return (error);
4037         }
4038
4039         if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
4040                 zfs_acl_ids_free(&acl_ids);
4041                 zfs_dirent_unlock(dl);
4042                 ZFS_EXIT(zfsvfs);
4043                 return (EDQUOT);
4044         }
4045         tx = dmu_tx_create(zfsvfs->z_os);
4046         fuid_dirtied = zfsvfs->z_fuid_dirty;
4047         dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
4048         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
4049         dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
4050             ZFS_SA_BASE_ATTR_SIZE + len);
4051         dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
4052         if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
4053                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
4054                     acl_ids.z_aclp->z_acl_bytes);
4055         }
4056         if (fuid_dirtied)
4057                 zfs_fuid_txhold(zfsvfs, tx);
4058         error = dmu_tx_assign(tx, TXG_NOWAIT);
4059         if (error) {
4060                 zfs_dirent_unlock(dl);
4061                 if (error == ERESTART) {
4062                         dmu_tx_wait(tx);
4063                         dmu_tx_abort(tx);
4064                         goto top;
4065                 }
4066                 zfs_acl_ids_free(&acl_ids);
4067                 dmu_tx_abort(tx);
4068                 ZFS_EXIT(zfsvfs);
4069                 return (error);
4070         }
4071
4072         /*
4073          * Create a new object for the symlink.
4074          * for version 4 ZPL datsets the symlink will be an SA attribute
4075          */
4076         zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
4077
4078         if (fuid_dirtied)
4079                 zfs_fuid_sync(zfsvfs, tx);
4080
4081         mutex_enter(&zp->z_lock);
4082         if (zp->z_is_sa)
4083                 error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs),
4084                     link, len, tx);
4085         else
4086                 zfs_sa_symlink(zp, link, len, tx);
4087         mutex_exit(&zp->z_lock);
4088
4089         zp->z_size = len;
4090         (void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
4091             &zp->z_size, sizeof (zp->z_size), tx);
4092         /*
4093          * Insert the new object into the directory.
4094          */
4095         (void) zfs_link_create(dl, zp, tx, ZNEW);
4096
4097         if (flags & FIGNORECASE)
4098                 txtype |= TX_CI;
4099         zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
4100         *vpp = ZTOV(zp);
4101
4102         zfs_acl_ids_free(&acl_ids);
4103
4104         dmu_tx_commit(tx);
4105
4106         zfs_dirent_unlock(dl);
4107
4108         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4109                 zil_commit(zilog, 0);
4110
4111         ZFS_EXIT(zfsvfs);
4112         return (error);
4113 }
4114
4115 /*
4116  * Return, in the buffer contained in the provided uio structure,
4117  * the symbolic path referred to by vp.
4118  *
4119  *      IN:     vp      - vnode of symbolic link.
4120  *              uoip    - structure to contain the link path.
4121  *              cr      - credentials of caller.
4122  *              ct      - caller context
4123  *
4124  *      OUT:    uio     - structure to contain the link path.
4125  *
4126  *      RETURN: 0 if success
4127  *              error code if failure
4128  *
4129  * Timestamps:
4130  *      vp - atime updated
4131  */
4132 /* ARGSUSED */
4133 static int
4134 zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr, caller_context_t *ct)
4135 {
4136         znode_t         *zp = VTOZ(vp);
4137         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4138         int             error;
4139
4140         ZFS_ENTER(zfsvfs);
4141         ZFS_VERIFY_ZP(zp);
4142
4143         mutex_enter(&zp->z_lock);
4144         if (zp->z_is_sa)
4145                 error = sa_lookup_uio(zp->z_sa_hdl,
4146                     SA_ZPL_SYMLINK(zfsvfs), uio);
4147         else
4148                 error = zfs_sa_readlink(zp, uio);
4149         mutex_exit(&zp->z_lock);
4150
4151         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4152
4153         ZFS_EXIT(zfsvfs);
4154         return (error);
4155 }
4156
4157 /*
4158  * Insert a new entry into directory tdvp referencing svp.
4159  *
4160  *      IN:     tdvp    - Directory to contain new entry.
4161  *              svp     - vnode of new entry.
4162  *              name    - name of new entry.
4163  *              cr      - credentials of caller.
4164  *              ct      - caller context
4165  *
4166  *      RETURN: 0 if success
4167  *              error code if failure
4168  *
4169  * Timestamps:
4170  *      tdvp - ctime|mtime updated
4171  *       svp - ctime updated
4172  */
4173 /* ARGSUSED */
4174 static int
4175 zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
4176     caller_context_t *ct, int flags)
4177 {
4178         znode_t         *dzp = VTOZ(tdvp);
4179         znode_t         *tzp, *szp;
4180         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
4181         zilog_t         *zilog;
4182         zfs_dirlock_t   *dl;
4183         dmu_tx_t        *tx;
4184         vnode_t         *realvp;
4185         int             error;
4186         int             zf = ZNEW;
4187         uint64_t        parent;
4188         uid_t           owner;
4189
4190         ASSERT(tdvp->v_type == VDIR);
4191
4192         ZFS_ENTER(zfsvfs);
4193         ZFS_VERIFY_ZP(dzp);
4194         zilog = zfsvfs->z_log;
4195
4196         if (VOP_REALVP(svp, &realvp, ct) == 0)
4197                 svp = realvp;
4198
4199         /*
4200          * POSIX dictates that we return EPERM here.
4201          * Better choices include ENOTSUP or EISDIR.
4202          */
4203         if (svp->v_type == VDIR) {
4204                 ZFS_EXIT(zfsvfs);
4205                 return (EPERM);
4206         }
4207
4208         if (svp->v_vfsp != tdvp->v_vfsp || zfsctl_is_node(svp)) {
4209                 ZFS_EXIT(zfsvfs);
4210                 return (EXDEV);
4211         }
4212
4213         szp = VTOZ(svp);
4214         ZFS_VERIFY_ZP(szp);
4215
4216         /* Prevent links to .zfs/shares files */
4217
4218         if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
4219             &parent, sizeof (uint64_t))) != 0) {
4220                 ZFS_EXIT(zfsvfs);
4221                 return (error);
4222         }
4223         if (parent == zfsvfs->z_shares_dir) {
4224                 ZFS_EXIT(zfsvfs);
4225                 return (EPERM);
4226         }
4227
4228         if (zfsvfs->z_utf8 && u8_validate(name,
4229             strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
4230                 ZFS_EXIT(zfsvfs);
4231                 return (EILSEQ);
4232         }
4233         if (flags & FIGNORECASE)
4234                 zf |= ZCILOOK;
4235
4236         /*
4237          * We do not support links between attributes and non-attributes
4238          * because of the potential security risk of creating links
4239          * into "normal" file space in order to circumvent restrictions
4240          * imposed in attribute space.
4241          */
4242         if ((szp->z_pflags & ZFS_XATTR) != (dzp->z_pflags & ZFS_XATTR)) {
4243                 ZFS_EXIT(zfsvfs);
4244                 return (EINVAL);
4245         }
4246
4247
4248         owner = zfs_fuid_map_id(zfsvfs, szp->z_uid, cr, ZFS_OWNER);
4249         if (owner != crgetuid(cr) && secpolicy_basic_link(svp, cr) != 0) {
4250                 ZFS_EXIT(zfsvfs);
4251                 return (EPERM);
4252         }
4253
4254         if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
4255                 ZFS_EXIT(zfsvfs);
4256                 return (error);
4257         }
4258
4259 top:
4260         /*
4261          * Attempt to lock directory; fail if entry already exists.
4262          */
4263         error = zfs_dirent_lock(&dl, dzp, name, &tzp, zf, NULL, NULL);
4264         if (error) {
4265                 ZFS_EXIT(zfsvfs);
4266                 return (error);
4267         }
4268
4269         tx = dmu_tx_create(zfsvfs->z_os);
4270         dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
4271         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
4272         zfs_sa_upgrade_txholds(tx, szp);
4273         zfs_sa_upgrade_txholds(tx, dzp);
4274         error = dmu_tx_assign(tx, TXG_NOWAIT);
4275         if (error) {
4276                 zfs_dirent_unlock(dl);
4277                 if (error == ERESTART) {
4278                         dmu_tx_wait(tx);
4279                         dmu_tx_abort(tx);
4280                         goto top;
4281                 }
4282                 dmu_tx_abort(tx);
4283                 ZFS_EXIT(zfsvfs);
4284                 return (error);
4285         }
4286
4287         error = zfs_link_create(dl, szp, tx, 0);
4288
4289         if (error == 0) {
4290                 uint64_t txtype = TX_LINK;
4291                 if (flags & FIGNORECASE)
4292                         txtype |= TX_CI;
4293                 zfs_log_link(zilog, tx, txtype, dzp, szp, name);
4294         }
4295
4296         dmu_tx_commit(tx);
4297
4298         zfs_dirent_unlock(dl);
4299
4300         if (error == 0) {
4301                 vnevent_link(svp, ct);
4302         }
4303
4304         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4305                 zil_commit(zilog, 0);
4306
4307         ZFS_EXIT(zfsvfs);
4308         return (error);
4309 }
4310
4311 #ifdef sun
4312 /*
4313  * zfs_null_putapage() is used when the file system has been force
4314  * unmounted. It just drops the pages.
4315  */
4316 /* ARGSUSED */
4317 static int
4318 zfs_null_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4319                 size_t *lenp, int flags, cred_t *cr)
4320 {
4321         pvn_write_done(pp, B_INVAL|B_FORCE|B_ERROR);
4322         return (0);
4323 }
4324
4325 /*
4326  * Push a page out to disk, klustering if possible.
4327  *
4328  *      IN:     vp      - file to push page to.
4329  *              pp      - page to push.
4330  *              flags   - additional flags.
4331  *              cr      - credentials of caller.
4332  *
4333  *      OUT:    offp    - start of range pushed.
4334  *              lenp    - len of range pushed.
4335  *
4336  *      RETURN: 0 if success
4337  *              error code if failure
4338  *
4339  * NOTE: callers must have locked the page to be pushed.  On
4340  * exit, the page (and all other pages in the kluster) must be
4341  * unlocked.
4342  */
4343 /* ARGSUSED */
4344 static int
4345 zfs_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
4346                 size_t *lenp, int flags, cred_t *cr)
4347 {
4348         znode_t         *zp = VTOZ(vp);
4349         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4350         dmu_tx_t        *tx;
4351         u_offset_t      off, koff;
4352         size_t          len, klen;
4353         int             err;
4354
4355         off = pp->p_offset;
4356         len = PAGESIZE;
4357         /*
4358          * If our blocksize is bigger than the page size, try to kluster
4359          * multiple pages so that we write a full block (thus avoiding
4360          * a read-modify-write).
4361          */
4362         if (off < zp->z_size && zp->z_blksz > PAGESIZE) {
4363                 klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
4364                 koff = ISP2(klen) ? P2ALIGN(off, (u_offset_t)klen) : 0;
4365                 ASSERT(koff <= zp->z_size);
4366                 if (koff + klen > zp->z_size)
4367                         klen = P2ROUNDUP(zp->z_size - koff, (uint64_t)PAGESIZE);
4368                 pp = pvn_write_kluster(vp, pp, &off, &len, koff, klen, flags);
4369         }
4370         ASSERT3U(btop(len), ==, btopr(len));
4371
4372         /*
4373          * Can't push pages past end-of-file.
4374          */
4375         if (off >= zp->z_size) {
4376                 /* ignore all pages */
4377                 err = 0;
4378                 goto out;
4379         } else if (off + len > zp->z_size) {
4380                 int npages = btopr(zp->z_size - off);
4381                 page_t *trunc;
4382
4383                 page_list_break(&pp, &trunc, npages);
4384                 /* ignore pages past end of file */
4385                 if (trunc)
4386                         pvn_write_done(trunc, flags);
4387                 len = zp->z_size - off;
4388         }
4389
4390         if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
4391             zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
4392                 err = EDQUOT;
4393                 goto out;
4394         }
4395 top:
4396         tx = dmu_tx_create(zfsvfs->z_os);
4397         dmu_tx_hold_write(tx, zp->z_id, off, len);
4398
4399         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4400         zfs_sa_upgrade_txholds(tx, zp);
4401         err = dmu_tx_assign(tx, TXG_NOWAIT);
4402         if (err != 0) {
4403                 if (err == ERESTART) {
4404                         dmu_tx_wait(tx);
4405                         dmu_tx_abort(tx);
4406                         goto top;
4407                 }
4408                 dmu_tx_abort(tx);
4409                 goto out;
4410         }
4411
4412         if (zp->z_blksz <= PAGESIZE) {
4413                 caddr_t va = zfs_map_page(pp, S_READ);
4414                 ASSERT3U(len, <=, PAGESIZE);
4415                 dmu_write(zfsvfs->z_os, zp->z_id, off, len, va, tx);
4416                 zfs_unmap_page(pp, va);
4417         } else {
4418                 err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, pp, tx);
4419         }
4420
4421         if (err == 0) {
4422                 uint64_t mtime[2], ctime[2];
4423                 sa_bulk_attr_t bulk[3];
4424                 int count = 0;
4425
4426                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
4427                     &mtime, 16);
4428                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
4429                     &ctime, 16);
4430                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
4431                     &zp->z_pflags, 8);
4432                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
4433                     B_TRUE);
4434                 zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len, 0);
4435         }
4436         dmu_tx_commit(tx);
4437
4438 out:
4439         pvn_write_done(pp, (err ? B_ERROR : 0) | flags);
4440         if (offp)
4441                 *offp = off;
4442         if (lenp)
4443                 *lenp = len;
4444
4445         return (err);
4446 }
4447
4448 /*
4449  * Copy the portion of the file indicated from pages into the file.
4450  * The pages are stored in a page list attached to the files vnode.
4451  *
4452  *      IN:     vp      - vnode of file to push page data to.
4453  *              off     - position in file to put data.
4454  *              len     - amount of data to write.
4455  *              flags   - flags to control the operation.
4456  *              cr      - credentials of caller.
4457  *              ct      - caller context.
4458  *
4459  *      RETURN: 0 if success
4460  *              error code if failure
4461  *
4462  * Timestamps:
4463  *      vp - ctime|mtime updated
4464  */
4465 /*ARGSUSED*/
4466 static int
4467 zfs_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
4468     caller_context_t *ct)
4469 {
4470         znode_t         *zp = VTOZ(vp);
4471         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4472         page_t          *pp;
4473         size_t          io_len;
4474         u_offset_t      io_off;
4475         uint_t          blksz;
4476         rl_t            *rl;
4477         int             error = 0;
4478
4479         ZFS_ENTER(zfsvfs);
4480         ZFS_VERIFY_ZP(zp);
4481
4482         /*
4483          * Align this request to the file block size in case we kluster.
4484          * XXX - this can result in pretty aggresive locking, which can
4485          * impact simultanious read/write access.  One option might be
4486          * to break up long requests (len == 0) into block-by-block
4487          * operations to get narrower locking.
4488          */
4489         blksz = zp->z_blksz;
4490         if (ISP2(blksz))
4491                 io_off = P2ALIGN_TYPED(off, blksz, u_offset_t);
4492         else
4493                 io_off = 0;
4494         if (len > 0 && ISP2(blksz))
4495                 io_len = P2ROUNDUP_TYPED(len + (off - io_off), blksz, size_t);
4496         else
4497                 io_len = 0;
4498
4499         if (io_len == 0) {
4500                 /*
4501                  * Search the entire vp list for pages >= io_off.
4502                  */
4503                 rl = zfs_range_lock(zp, io_off, UINT64_MAX, RL_WRITER);
4504                 error = pvn_vplist_dirty(vp, io_off, zfs_putapage, flags, cr);
4505                 goto out;
4506         }
4507         rl = zfs_range_lock(zp, io_off, io_len, RL_WRITER);
4508
4509         if (off > zp->z_size) {
4510                 /* past end of file */
4511                 zfs_range_unlock(rl);
4512                 ZFS_EXIT(zfsvfs);
4513                 return (0);
4514         }
4515
4516         len = MIN(io_len, P2ROUNDUP(zp->z_size, PAGESIZE) - io_off);
4517
4518         for (off = io_off; io_off < off + len; io_off += io_len) {
4519                 if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
4520                         pp = page_lookup(vp, io_off,
4521                             (flags & (B_INVAL | B_FREE)) ? SE_EXCL : SE_SHARED);
4522                 } else {
4523                         pp = page_lookup_nowait(vp, io_off,
4524                             (flags & B_FREE) ? SE_EXCL : SE_SHARED);
4525                 }
4526
4527                 if (pp != NULL && pvn_getdirty(pp, flags)) {
4528                         int err;
4529
4530                         /*
4531                          * Found a dirty page to push
4532                          */
4533                         err = zfs_putapage(vp, pp, &io_off, &io_len, flags, cr);
4534                         if (err)
4535                                 error = err;
4536                 } else {
4537                         io_len = PAGESIZE;
4538                 }
4539         }
4540 out:
4541         zfs_range_unlock(rl);
4542         if ((flags & B_ASYNC) == 0 || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4543                 zil_commit(zfsvfs->z_log, zp->z_id);
4544         ZFS_EXIT(zfsvfs);
4545         return (error);
4546 }
4547 #endif  /* sun */
4548
4549 /*ARGSUSED*/
4550 void
4551 zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4552 {
4553         znode_t *zp = VTOZ(vp);
4554         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4555         int error;
4556
4557         rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
4558         if (zp->z_sa_hdl == NULL) {
4559                 /*
4560                  * The fs has been unmounted, or we did a
4561                  * suspend/resume and this file no longer exists.
4562                  */
4563                 VI_LOCK(vp);
4564                 ASSERT(vp->v_count <= 1);
4565                 vp->v_count = 0;
4566                 VI_UNLOCK(vp);
4567                 vrecycle(vp, curthread);
4568                 rw_exit(&zfsvfs->z_teardown_inactive_lock);
4569                 return;
4570         }
4571
4572         if (zp->z_atime_dirty && zp->z_unlinked == 0) {
4573                 dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
4574
4575                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4576                 zfs_sa_upgrade_txholds(tx, zp);
4577                 error = dmu_tx_assign(tx, TXG_WAIT);
4578                 if (error) {
4579                         dmu_tx_abort(tx);
4580                 } else {
4581                         mutex_enter(&zp->z_lock);
4582                         (void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zfsvfs),
4583                             (void *)&zp->z_atime, sizeof (zp->z_atime), tx);
4584                         zp->z_atime_dirty = 0;
4585                         mutex_exit(&zp->z_lock);
4586                         dmu_tx_commit(tx);
4587                 }
4588         }
4589
4590         zfs_zinactive(zp);
4591         rw_exit(&zfsvfs->z_teardown_inactive_lock);
4592 }
4593
4594 #ifdef sun
4595 /*
4596  * Bounds-check the seek operation.
4597  *
4598  *      IN:     vp      - vnode seeking within
4599  *              ooff    - old file offset
4600  *              noffp   - pointer to new file offset
4601  *              ct      - caller context
4602  *
4603  *      RETURN: 0 if success
4604  *              EINVAL if new offset invalid
4605  */
4606 /* ARGSUSED */
4607 static int
4608 zfs_seek(vnode_t *vp, offset_t ooff, offset_t *noffp,
4609     caller_context_t *ct)
4610 {
4611         if (vp->v_type == VDIR)
4612                 return (0);
4613         return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
4614 }
4615
4616 /*
4617  * Pre-filter the generic locking function to trap attempts to place
4618  * a mandatory lock on a memory mapped file.
4619  */
4620 static int
4621 zfs_frlock(vnode_t *vp, int cmd, flock64_t *bfp, int flag, offset_t offset,
4622     flk_callback_t *flk_cbp, cred_t *cr, caller_context_t *ct)
4623 {
4624         znode_t *zp = VTOZ(vp);
4625         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4626
4627         ZFS_ENTER(zfsvfs);
4628         ZFS_VERIFY_ZP(zp);
4629
4630         /*
4631          * We are following the UFS semantics with respect to mapcnt
4632          * here: If we see that the file is mapped already, then we will
4633          * return an error, but we don't worry about races between this
4634          * function and zfs_map().
4635          */
4636         if (zp->z_mapcnt > 0 && MANDMODE(zp->z_mode)) {
4637                 ZFS_EXIT(zfsvfs);
4638                 return (EAGAIN);
4639         }
4640         ZFS_EXIT(zfsvfs);
4641         return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
4642 }
4643
4644 /*
4645  * If we can't find a page in the cache, we will create a new page
4646  * and fill it with file data.  For efficiency, we may try to fill
4647  * multiple pages at once (klustering) to fill up the supplied page
4648  * list.  Note that the pages to be filled are held with an exclusive
4649  * lock to prevent access by other threads while they are being filled.
4650  */
4651 static int
4652 zfs_fillpage(vnode_t *vp, u_offset_t off, struct seg *seg,
4653     caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw)
4654 {
4655         znode_t *zp = VTOZ(vp);
4656         page_t *pp, *cur_pp;
4657         objset_t *os = zp->z_zfsvfs->z_os;
4658         u_offset_t io_off, total;
4659         size_t io_len;
4660         int err;
4661
4662         if (plsz == PAGESIZE || zp->z_blksz <= PAGESIZE) {
4663                 /*
4664                  * We only have a single page, don't bother klustering
4665                  */
4666                 io_off = off;
4667                 io_len = PAGESIZE;
4668                 pp = page_create_va(vp, io_off, io_len,
4669                     PG_EXCL | PG_WAIT, seg, addr);
4670         } else {
4671                 /*
4672                  * Try to find enough pages to fill the page list
4673                  */
4674                 pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
4675                     &io_len, off, plsz, 0);
4676         }
4677         if (pp == NULL) {
4678                 /*
4679                  * The page already exists, nothing to do here.
4680                  */
4681                 *pl = NULL;
4682                 return (0);
4683         }
4684
4685         /*
4686          * Fill the pages in the kluster.
4687          */
4688         cur_pp = pp;
4689         for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
4690                 caddr_t va;
4691
4692                 ASSERT3U(io_off, ==, cur_pp->p_offset);
4693                 va = zfs_map_page(cur_pp, S_WRITE);
4694                 err = dmu_read(os, zp->z_id, io_off, PAGESIZE, va,
4695                     DMU_READ_PREFETCH);
4696                 zfs_unmap_page(cur_pp, va);
4697                 if (err) {
4698                         /* On error, toss the entire kluster */
4699                         pvn_read_done(pp, B_ERROR);
4700                         /* convert checksum errors into IO errors */
4701                         if (err == ECKSUM)
4702                                 err = EIO;
4703                         return (err);
4704                 }
4705                 cur_pp = cur_pp->p_next;
4706         }
4707
4708         /*
4709          * Fill in the page list array from the kluster starting
4710          * from the desired offset `off'.
4711          * NOTE: the page list will always be null terminated.
4712          */
4713         pvn_plist_init(pp, pl, plsz, off, io_len, rw);
4714         ASSERT(pl == NULL || (*pl)->p_offset == off);
4715
4716         return (0);
4717 }
4718
4719 /*
4720  * Return pointers to the pages for the file region [off, off + len]
4721  * in the pl array.  If plsz is greater than len, this function may
4722  * also return page pointers from after the specified region
4723  * (i.e. the region [off, off + plsz]).  These additional pages are
4724  * only returned if they are already in the cache, or were created as
4725  * part of a klustered read.
4726  *
4727  *      IN:     vp      - vnode of file to get data from.
4728  *              off     - position in file to get data from.
4729  *              len     - amount of data to retrieve.
4730  *              plsz    - length of provided page list.
4731  *              seg     - segment to obtain pages for.
4732  *              addr    - virtual address of fault.
4733  *              rw      - mode of created pages.
4734  *              cr      - credentials of caller.
4735  *              ct      - caller context.
4736  *
4737  *      OUT:    protp   - protection mode of created pages.
4738  *              pl      - list of pages created.
4739  *
4740  *      RETURN: 0 if success
4741  *              error code if failure
4742  *
4743  * Timestamps:
4744  *      vp - atime updated
4745  */
4746 /* ARGSUSED */
4747 static int
4748 zfs_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
4749         page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
4750         enum seg_rw rw, cred_t *cr, caller_context_t *ct)
4751 {
4752         znode_t         *zp = VTOZ(vp);
4753         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4754         page_t          **pl0 = pl;
4755         int             err = 0;
4756
4757         /* we do our own caching, faultahead is unnecessary */
4758         if (pl == NULL)
4759                 return (0);
4760         else if (len > plsz)
4761                 len = plsz;
4762         else
4763                 len = P2ROUNDUP(len, PAGESIZE);
4764         ASSERT(plsz >= len);
4765
4766         ZFS_ENTER(zfsvfs);
4767         ZFS_VERIFY_ZP(zp);
4768
4769         if (protp)
4770                 *protp = PROT_ALL;
4771
4772         /*
4773          * Loop through the requested range [off, off + len) looking
4774          * for pages.  If we don't find a page, we will need to create
4775          * a new page and fill it with data from the file.
4776          */
4777         while (len > 0) {
4778                 if (*pl = page_lookup(vp, off, SE_SHARED))
4779                         *(pl+1) = NULL;
4780                 else if (err = zfs_fillpage(vp, off, seg, addr, pl, plsz, rw))
4781                         goto out;
4782                 while (*pl) {
4783                         ASSERT3U((*pl)->p_offset, ==, off);
4784                         off += PAGESIZE;
4785                         addr += PAGESIZE;
4786                         if (len > 0) {
4787                                 ASSERT3U(len, >=, PAGESIZE);
4788                                 len -= PAGESIZE;
4789                         }
4790                         ASSERT3U(plsz, >=, PAGESIZE);
4791                         plsz -= PAGESIZE;
4792                         pl++;
4793                 }
4794         }
4795
4796         /*
4797          * Fill out the page array with any pages already in the cache.
4798          */
4799         while (plsz > 0 &&
4800             (*pl++ = page_lookup_nowait(vp, off, SE_SHARED))) {
4801                         off += PAGESIZE;
4802                         plsz -= PAGESIZE;
4803         }
4804 out:
4805         if (err) {
4806                 /*
4807                  * Release any pages we have previously locked.
4808                  */
4809                 while (pl > pl0)
4810                         page_unlock(*--pl);
4811         } else {
4812                 ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4813         }
4814
4815         *pl = NULL;
4816
4817         ZFS_EXIT(zfsvfs);
4818         return (err);
4819 }
4820
4821 /*
4822  * Request a memory map for a section of a file.  This code interacts
4823  * with common code and the VM system as follows:
4824  *
4825  *      common code calls mmap(), which ends up in smmap_common()
4826  *
4827  *      this calls VOP_MAP(), which takes you into (say) zfs
4828  *
4829  *      zfs_map() calls as_map(), passing segvn_create() as the callback
4830  *
4831  *      segvn_create() creates the new segment and calls VOP_ADDMAP()
4832  *
4833  *      zfs_addmap() updates z_mapcnt
4834  */
4835 /*ARGSUSED*/
4836 static int
4837 zfs_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
4838     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4839     caller_context_t *ct)
4840 {
4841         znode_t *zp = VTOZ(vp);
4842         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4843         segvn_crargs_t  vn_a;
4844         int             error;
4845
4846         ZFS_ENTER(zfsvfs);
4847         ZFS_VERIFY_ZP(zp);
4848
4849         if ((prot & PROT_WRITE) && (zp->z_pflags &
4850             (ZFS_IMMUTABLE | ZFS_READONLY | ZFS_APPENDONLY))) {
4851                 ZFS_EXIT(zfsvfs);
4852                 return (EPERM);
4853         }
4854
4855         if ((prot & (PROT_READ | PROT_EXEC)) &&
4856             (zp->z_pflags & ZFS_AV_QUARANTINED)) {
4857                 ZFS_EXIT(zfsvfs);
4858                 return (EACCES);
4859         }
4860
4861         if (vp->v_flag & VNOMAP) {
4862                 ZFS_EXIT(zfsvfs);
4863                 return (ENOSYS);
4864         }
4865
4866         if (off < 0 || len > MAXOFFSET_T - off) {
4867                 ZFS_EXIT(zfsvfs);
4868                 return (ENXIO);
4869         }
4870
4871         if (vp->v_type != VREG) {
4872                 ZFS_EXIT(zfsvfs);
4873                 return (ENODEV);
4874         }
4875
4876         /*
4877          * If file is locked, disallow mapping.
4878          */
4879         if (MANDMODE(zp->z_mode) && vn_has_flocks(vp)) {
4880                 ZFS_EXIT(zfsvfs);
4881                 return (EAGAIN);
4882         }
4883
4884         as_rangelock(as);
4885         error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
4886         if (error != 0) {
4887                 as_rangeunlock(as);
4888                 ZFS_EXIT(zfsvfs);
4889                 return (error);
4890         }
4891
4892         vn_a.vp = vp;
4893         vn_a.offset = (u_offset_t)off;
4894         vn_a.type = flags & MAP_TYPE;
4895         vn_a.prot = prot;
4896         vn_a.maxprot = maxprot;
4897         vn_a.cred = cr;
4898         vn_a.amp = NULL;
4899         vn_a.flags = flags & ~MAP_TYPE;
4900         vn_a.szc = 0;
4901         vn_a.lgrp_mem_policy_flags = 0;
4902
4903         error = as_map(as, *addrp, len, segvn_create, &vn_a);
4904
4905         as_rangeunlock(as);
4906         ZFS_EXIT(zfsvfs);
4907         return (error);
4908 }
4909
4910 /* ARGSUSED */
4911 static int
4912 zfs_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4913     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
4914     caller_context_t *ct)
4915 {
4916         uint64_t pages = btopr(len);
4917
4918         atomic_add_64(&VTOZ(vp)->z_mapcnt, pages);
4919         return (0);
4920 }
4921
4922 /*
4923  * The reason we push dirty pages as part of zfs_delmap() is so that we get a
4924  * more accurate mtime for the associated file.  Since we don't have a way of
4925  * detecting when the data was actually modified, we have to resort to
4926  * heuristics.  If an explicit msync() is done, then we mark the mtime when the
4927  * last page is pushed.  The problem occurs when the msync() call is omitted,
4928  * which by far the most common case:
4929  *
4930  *      open()
4931  *      mmap()
4932  *      <modify memory>
4933  *      munmap()
4934  *      close()
4935  *      <time lapse>
4936  *      putpage() via fsflush
4937  *
4938  * If we wait until fsflush to come along, we can have a modification time that
4939  * is some arbitrary point in the future.  In order to prevent this in the
4940  * common case, we flush pages whenever a (MAP_SHARED, PROT_WRITE) mapping is
4941  * torn down.
4942  */
4943 /* ARGSUSED */
4944 static int
4945 zfs_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4946     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
4947     caller_context_t *ct)
4948 {
4949         uint64_t pages = btopr(len);
4950
4951         ASSERT3U(VTOZ(vp)->z_mapcnt, >=, pages);
4952         atomic_add_64(&VTOZ(vp)->z_mapcnt, -pages);
4953
4954         if ((flags & MAP_SHARED) && (prot & PROT_WRITE) &&
4955             vn_has_cached_data(vp))
4956                 (void) VOP_PUTPAGE(vp, off, len, B_ASYNC, cr, ct);
4957
4958         return (0);
4959 }
4960
4961 /*
4962  * Free or allocate space in a file.  Currently, this function only
4963  * supports the `F_FREESP' command.  However, this command is somewhat
4964  * misnamed, as its functionality includes the ability to allocate as
4965  * well as free space.
4966  *
4967  *      IN:     vp      - vnode of file to free data in.
4968  *              cmd     - action to take (only F_FREESP supported).
4969  *              bfp     - section of file to free/alloc.
4970  *              flag    - current file open mode flags.
4971  *              offset  - current file offset.
4972  *              cr      - credentials of caller [UNUSED].
4973  *              ct      - caller context.
4974  *
4975  *      RETURN: 0 if success
4976  *              error code if failure
4977  *
4978  * Timestamps:
4979  *      vp - ctime|mtime updated
4980  */
4981 /* ARGSUSED */
4982 static int
4983 zfs_space(vnode_t *vp, int cmd, flock64_t *bfp, int flag,
4984     offset_t offset, cred_t *cr, caller_context_t *ct)
4985 {
4986         znode_t         *zp = VTOZ(vp);
4987         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4988         uint64_t        off, len;
4989         int             error;
4990
4991         ZFS_ENTER(zfsvfs);
4992         ZFS_VERIFY_ZP(zp);
4993
4994         if (cmd != F_FREESP) {
4995                 ZFS_EXIT(zfsvfs);
4996                 return (EINVAL);
4997         }
4998
4999         if (error = convoff(vp, bfp, 0, offset)) {
5000                 ZFS_EXIT(zfsvfs);
5001                 return (error);
5002         }
5003
5004         if (bfp->l_len < 0) {
5005                 ZFS_EXIT(zfsvfs);
5006                 return (EINVAL);
5007         }
5008
5009         off = bfp->l_start;
5010         len = bfp->l_len; /* 0 means from off to end of file */
5011
5012         error = zfs_freesp(zp, off, len, flag, TRUE);
5013
5014         ZFS_EXIT(zfsvfs);
5015         return (error);
5016 }
5017 #endif  /* sun */
5018
5019 CTASSERT(sizeof(struct zfid_short) <= sizeof(struct fid));
5020 CTASSERT(sizeof(struct zfid_long) <= sizeof(struct fid));
5021
5022 /*ARGSUSED*/
5023 static int
5024 zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
5025 {
5026         znode_t         *zp = VTOZ(vp);
5027         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
5028         uint32_t        gen;
5029         uint64_t        gen64;
5030         uint64_t        object = zp->z_id;
5031         zfid_short_t    *zfid;
5032         int             size, i, error;
5033
5034         ZFS_ENTER(zfsvfs);
5035         ZFS_VERIFY_ZP(zp);
5036
5037         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs),
5038             &gen64, sizeof (uint64_t))) != 0) {
5039                 ZFS_EXIT(zfsvfs);
5040                 return (error);
5041         }
5042
5043         gen = (uint32_t)gen64;
5044
5045         size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
5046         fidp->fid_len = size;
5047
5048         zfid = (zfid_short_t *)fidp;
5049
5050         zfid->zf_len = size;
5051
5052         for (i = 0; i < sizeof (zfid->zf_object); i++)
5053                 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
5054
5055         /* Must have a non-zero generation number to distinguish from .zfs */
5056         if (gen == 0)
5057                 gen = 1;
5058         for (i = 0; i < sizeof (zfid->zf_gen); i++)
5059                 zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
5060
5061         if (size == LONG_FID_LEN) {
5062                 uint64_t        objsetid = dmu_objset_id(zfsvfs->z_os);
5063                 zfid_long_t     *zlfid;
5064
5065                 zlfid = (zfid_long_t *)fidp;
5066
5067                 for (i = 0; i < sizeof (zlfid->zf_setid); i++)
5068                         zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
5069
5070                 /* XXX - this should be the generation number for the objset */
5071                 for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
5072                         zlfid->zf_setgen[i] = 0;
5073         }
5074
5075         ZFS_EXIT(zfsvfs);
5076         return (0);
5077 }
5078
5079 static int
5080 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
5081     caller_context_t *ct)
5082 {
5083         znode_t         *zp, *xzp;
5084         zfsvfs_t        *zfsvfs;
5085         zfs_dirlock_t   *dl;
5086         int             error;
5087
5088         switch (cmd) {
5089         case _PC_LINK_MAX:
5090                 *valp = INT_MAX;
5091                 return (0);
5092
5093         case _PC_FILESIZEBITS:
5094                 *valp = 64;
5095                 return (0);
5096 #ifdef sun
5097         case _PC_XATTR_EXISTS:
5098                 zp = VTOZ(vp);
5099                 zfsvfs = zp->z_zfsvfs;
5100                 ZFS_ENTER(zfsvfs);
5101                 ZFS_VERIFY_ZP(zp);
5102                 *valp = 0;
5103                 error = zfs_dirent_lock(&dl, zp, "", &xzp,
5104                     ZXATTR | ZEXISTS | ZSHARED, NULL, NULL);
5105                 if (error == 0) {
5106                         zfs_dirent_unlock(dl);
5107                         if (!zfs_dirempty(xzp))
5108                                 *valp = 1;
5109                         VN_RELE(ZTOV(xzp));
5110                 } else if (error == ENOENT) {
5111                         /*
5112                          * If there aren't extended attributes, it's the
5113                          * same as having zero of them.
5114                          */
5115                         error = 0;
5116                 }
5117                 ZFS_EXIT(zfsvfs);
5118                 return (error);
5119
5120         case _PC_SATTR_ENABLED:
5121         case _PC_SATTR_EXISTS:
5122                 *valp = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
5123                     (vp->v_type == VREG || vp->v_type == VDIR);
5124                 return (0);
5125
5126         case _PC_ACCESS_FILTERING:
5127                 *valp = vfs_has_feature(vp->v_vfsp, VFSFT_ACCESS_FILTER) &&
5128                     vp->v_type == VDIR;
5129                 return (0);
5130
5131         case _PC_ACL_ENABLED:
5132                 *valp = _ACL_ACE_ENABLED;
5133                 return (0);
5134 #endif  /* sun */
5135         case _PC_MIN_HOLE_SIZE:
5136                 *valp = (int)SPA_MINBLOCKSIZE;
5137                 return (0);
5138 #ifdef sun
5139         case _PC_TIMESTAMP_RESOLUTION:
5140                 /* nanosecond timestamp resolution */
5141                 *valp = 1L;
5142                 return (0);
5143 #endif  /* sun */
5144         case _PC_ACL_EXTENDED:
5145                 *valp = 0;
5146                 return (0);
5147
5148         case _PC_ACL_NFS4:
5149                 *valp = 1;
5150                 return (0);
5151
5152         case _PC_ACL_PATH_MAX:
5153                 *valp = ACL_MAX_ENTRIES;
5154                 return (0);
5155
5156         default:
5157                 return (EOPNOTSUPP);
5158         }
5159 }
5160
5161 /*ARGSUSED*/
5162 static int
5163 zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5164     caller_context_t *ct)
5165 {
5166         znode_t *zp = VTOZ(vp);
5167         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5168         int error;
5169         boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5170
5171         ZFS_ENTER(zfsvfs);
5172         ZFS_VERIFY_ZP(zp);
5173         error = zfs_getacl(zp, vsecp, skipaclchk, cr);
5174         ZFS_EXIT(zfsvfs);
5175
5176         return (error);
5177 }
5178
5179 /*ARGSUSED*/
5180 static int
5181 zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
5182     caller_context_t *ct)
5183 {
5184         znode_t *zp = VTOZ(vp);
5185         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5186         int error;
5187         boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
5188         zilog_t *zilog = zfsvfs->z_log;
5189
5190         ZFS_ENTER(zfsvfs);
5191         ZFS_VERIFY_ZP(zp);
5192
5193         error = zfs_setacl(zp, vsecp, skipaclchk, cr);
5194
5195         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
5196                 zil_commit(zilog, 0);
5197
5198         ZFS_EXIT(zfsvfs);
5199         return (error);
5200 }
5201
5202 #ifdef sun
5203 /*
5204  * Tunable, both must be a power of 2.
5205  *
5206  * zcr_blksz_min: the smallest read we may consider to loan out an arcbuf
5207  * zcr_blksz_max: if set to less than the file block size, allow loaning out of
5208  *                an arcbuf for a partial block read
5209  */
5210 int zcr_blksz_min = (1 << 10);  /* 1K */
5211 int zcr_blksz_max = (1 << 17);  /* 128K */
5212
5213 /*ARGSUSED*/
5214 static int
5215 zfs_reqzcbuf(vnode_t *vp, enum uio_rw ioflag, xuio_t *xuio, cred_t *cr,
5216     caller_context_t *ct)
5217 {
5218         znode_t *zp = VTOZ(vp);
5219         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5220         int max_blksz = zfsvfs->z_max_blksz;
5221         uio_t *uio = &xuio->xu_uio;
5222         ssize_t size = uio->uio_resid;
5223         offset_t offset = uio->uio_loffset;
5224         int blksz;
5225         int fullblk, i;
5226         arc_buf_t *abuf;
5227         ssize_t maxsize;
5228         int preamble, postamble;
5229
5230         if (xuio->xu_type != UIOTYPE_ZEROCOPY)
5231                 return (EINVAL);
5232
5233         ZFS_ENTER(zfsvfs);
5234         ZFS_VERIFY_ZP(zp);
5235         switch (ioflag) {
5236         case UIO_WRITE:
5237                 /*
5238                  * Loan out an arc_buf for write if write size is bigger than
5239                  * max_blksz, and the file's block size is also max_blksz.
5240                  */
5241                 blksz = max_blksz;
5242                 if (size < blksz || zp->z_blksz != blksz) {
5243                         ZFS_EXIT(zfsvfs);
5244                         return (EINVAL);
5245                 }
5246                 /*
5247                  * Caller requests buffers for write before knowing where the
5248                  * write offset might be (e.g. NFS TCP write).
5249                  */
5250                 if (offset == -1) {
5251                         preamble = 0;
5252                 } else {
5253                         preamble = P2PHASE(offset, blksz);
5254                         if (preamble) {
5255                                 preamble = blksz - preamble;
5256                                 size -= preamble;
5257                         }
5258                 }
5259
5260                 postamble = P2PHASE(size, blksz);
5261                 size -= postamble;
5262
5263                 fullblk = size / blksz;
5264                 (void) dmu_xuio_init(xuio,
5265                     (preamble != 0) + fullblk + (postamble != 0));
5266                 DTRACE_PROBE3(zfs_reqzcbuf_align, int, preamble,
5267                     int, postamble, int,
5268                     (preamble != 0) + fullblk + (postamble != 0));
5269
5270                 /*
5271                  * Have to fix iov base/len for partial buffers.  They
5272                  * currently represent full arc_buf's.
5273                  */
5274                 if (preamble) {
5275                         /* data begins in the middle of the arc_buf */
5276                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5277                             blksz);
5278                         ASSERT(abuf);
5279                         (void) dmu_xuio_add(xuio, abuf,
5280                             blksz - preamble, preamble);
5281                 }
5282
5283                 for (i = 0; i < fullblk; i++) {
5284                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5285                             blksz);
5286                         ASSERT(abuf);
5287                         (void) dmu_xuio_add(xuio, abuf, 0, blksz);
5288                 }
5289
5290                 if (postamble) {
5291                         /* data ends in the middle of the arc_buf */
5292                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
5293                             blksz);
5294                         ASSERT(abuf);
5295                         (void) dmu_xuio_add(xuio, abuf, 0, postamble);
5296                 }
5297                 break;
5298         case UIO_READ:
5299                 /*
5300                  * Loan out an arc_buf for read if the read size is larger than
5301                  * the current file block size.  Block alignment is not
5302                  * considered.  Partial arc_buf will be loaned out for read.
5303                  */
5304                 blksz = zp->z_blksz;
5305                 if (blksz < zcr_blksz_min)
5306                         blksz = zcr_blksz_min;
5307                 if (blksz > zcr_blksz_max)
5308                         blksz = zcr_blksz_max;
5309                 /* avoid potential complexity of dealing with it */
5310                 if (blksz > max_blksz) {
5311                         ZFS_EXIT(zfsvfs);
5312                         return (EINVAL);
5313                 }
5314
5315                 maxsize = zp->z_size - uio->uio_loffset;
5316                 if (size > maxsize)
5317                         size = maxsize;
5318
5319                 if (size < blksz || vn_has_cached_data(vp)) {
5320                         ZFS_EXIT(zfsvfs);
5321                         return (EINVAL);
5322                 }
5323                 break;
5324         default:
5325                 ZFS_EXIT(zfsvfs);
5326                 return (EINVAL);
5327         }
5328
5329         uio->uio_extflg = UIO_XUIO;
5330         XUIO_XUZC_RW(xuio) = ioflag;
5331         ZFS_EXIT(zfsvfs);
5332         return (0);
5333 }
5334
5335 /*ARGSUSED*/
5336 static int
5337 zfs_retzcbuf(vnode_t *vp, xuio_t *xuio, cred_t *cr, caller_context_t *ct)
5338 {
5339         int i;
5340         arc_buf_t *abuf;
5341         int ioflag = XUIO_XUZC_RW(xuio);
5342
5343         ASSERT(xuio->xu_type == UIOTYPE_ZEROCOPY);
5344
5345         i = dmu_xuio_cnt(xuio);
5346         while (i-- > 0) {
5347                 abuf = dmu_xuio_arcbuf(xuio, i);
5348                 /*
5349                  * if abuf == NULL, it must be a write buffer
5350                  * that has been returned in zfs_write().
5351                  */
5352                 if (abuf)
5353                         dmu_return_arcbuf(abuf);
5354                 ASSERT(abuf || ioflag == UIO_WRITE);
5355         }
5356
5357         dmu_xuio_fini(xuio);
5358         return (0);
5359 }
5360
5361 /*
5362  * Predeclare these here so that the compiler assumes that
5363  * this is an "old style" function declaration that does
5364  * not include arguments => we won't get type mismatch errors
5365  * in the initializations that follow.
5366  */
5367 static int zfs_inval();
5368 static int zfs_isdir();
5369
5370 static int
5371 zfs_inval()
5372 {
5373         return (EINVAL);
5374 }
5375
5376 static int
5377 zfs_isdir()
5378 {
5379         return (EISDIR);
5380 }
5381 /*
5382  * Directory vnode operations template
5383  */
5384 vnodeops_t *zfs_dvnodeops;
5385 const fs_operation_def_t zfs_dvnodeops_template[] = {
5386         VOPNAME_OPEN,           { .vop_open = zfs_open },
5387         VOPNAME_CLOSE,          { .vop_close = zfs_close },
5388         VOPNAME_READ,           { .error = zfs_isdir },
5389         VOPNAME_WRITE,          { .error = zfs_isdir },
5390         VOPNAME_IOCTL,          { .vop_ioctl = zfs_ioctl },
5391         VOPNAME_GETATTR,        { .vop_getattr = zfs_getattr },
5392         VOPNAME_SETATTR,        { .vop_setattr = zfs_setattr },
5393         VOPNAME_ACCESS,         { .vop_access = zfs_access },
5394         VOPNAME_LOOKUP,         { .vop_lookup = zfs_lookup },
5395         VOPNAME_CREATE,         { .vop_create = zfs_create },
5396         VOPNAME_REMOVE,         { .vop_remove = zfs_remove },
5397         VOPNAME_LINK,           { .vop_link = zfs_link },
5398         VOPNAME_RENAME,         { .vop_rename = zfs_rename },
5399         VOPNAME_MKDIR,          { .vop_mkdir = zfs_mkdir },
5400         VOPNAME_RMDIR,          { .vop_rmdir = zfs_rmdir },
5401         VOPNAME_READDIR,        { .vop_readdir = zfs_readdir },
5402         VOPNAME_SYMLINK,        { .vop_symlink = zfs_symlink },
5403         VOPNAME_FSYNC,          { .vop_fsync = zfs_fsync },
5404         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5405         VOPNAME_FID,            { .vop_fid = zfs_fid },
5406         VOPNAME_SEEK,           { .vop_seek = zfs_seek },
5407         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5408         VOPNAME_GETSECATTR,     { .vop_getsecattr = zfs_getsecattr },
5409         VOPNAME_SETSECATTR,     { .vop_setsecattr = zfs_setsecattr },
5410         VOPNAME_VNEVENT,        { .vop_vnevent = fs_vnevent_support },
5411         NULL,                   NULL
5412 };
5413
5414 /*
5415  * Regular file vnode operations template
5416  */
5417 vnodeops_t *zfs_fvnodeops;
5418 const fs_operation_def_t zfs_fvnodeops_template[] = {
5419         VOPNAME_OPEN,           { .vop_open = zfs_open },
5420         VOPNAME_CLOSE,          { .vop_close = zfs_close },
5421         VOPNAME_READ,           { .vop_read = zfs_read },
5422         VOPNAME_WRITE,          { .vop_write = zfs_write },
5423         VOPNAME_IOCTL,          { .vop_ioctl = zfs_ioctl },
5424         VOPNAME_GETATTR,        { .vop_getattr = zfs_getattr },
5425         VOPNAME_SETATTR,        { .vop_setattr = zfs_setattr },
5426         VOPNAME_ACCESS,         { .vop_access = zfs_access },
5427         VOPNAME_LOOKUP,         { .vop_lookup = zfs_lookup },
5428         VOPNAME_RENAME,         { .vop_rename = zfs_rename },
5429         VOPNAME_FSYNC,          { .vop_fsync = zfs_fsync },
5430         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5431         VOPNAME_FID,            { .vop_fid = zfs_fid },
5432         VOPNAME_SEEK,           { .vop_seek = zfs_seek },
5433         VOPNAME_FRLOCK,         { .vop_frlock = zfs_frlock },
5434         VOPNAME_SPACE,          { .vop_space = zfs_space },
5435         VOPNAME_GETPAGE,        { .vop_getpage = zfs_getpage },
5436         VOPNAME_PUTPAGE,        { .vop_putpage = zfs_putpage },
5437         VOPNAME_MAP,            { .vop_map = zfs_map },
5438         VOPNAME_ADDMAP,         { .vop_addmap = zfs_addmap },
5439         VOPNAME_DELMAP,         { .vop_delmap = zfs_delmap },
5440         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5441         VOPNAME_GETSECATTR,     { .vop_getsecattr = zfs_getsecattr },
5442         VOPNAME_SETSECATTR,     { .vop_setsecattr = zfs_setsecattr },
5443         VOPNAME_VNEVENT,        { .vop_vnevent = fs_vnevent_support },
5444         VOPNAME_REQZCBUF,       { .vop_reqzcbuf = zfs_reqzcbuf },
5445         VOPNAME_RETZCBUF,       { .vop_retzcbuf = zfs_retzcbuf },
5446         NULL,                   NULL
5447 };
5448
5449 /*
5450  * Symbolic link vnode operations template
5451  */
5452 vnodeops_t *zfs_symvnodeops;
5453 const fs_operation_def_t zfs_symvnodeops_template[] = {
5454         VOPNAME_GETATTR,        { .vop_getattr = zfs_getattr },
5455         VOPNAME_SETATTR,        { .vop_setattr = zfs_setattr },
5456         VOPNAME_ACCESS,         { .vop_access = zfs_access },
5457         VOPNAME_RENAME,         { .vop_rename = zfs_rename },
5458         VOPNAME_READLINK,       { .vop_readlink = zfs_readlink },
5459         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5460         VOPNAME_FID,            { .vop_fid = zfs_fid },
5461         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5462         VOPNAME_VNEVENT,        { .vop_vnevent = fs_vnevent_support },
5463         NULL,                   NULL
5464 };
5465
5466 /*
5467  * special share hidden files vnode operations template
5468  */
5469 vnodeops_t *zfs_sharevnodeops;
5470 const fs_operation_def_t zfs_sharevnodeops_template[] = {
5471         VOPNAME_GETATTR,        { .vop_getattr = zfs_getattr },
5472         VOPNAME_ACCESS,         { .vop_access = zfs_access },
5473         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5474         VOPNAME_FID,            { .vop_fid = zfs_fid },
5475         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5476         VOPNAME_GETSECATTR,     { .vop_getsecattr = zfs_getsecattr },
5477         VOPNAME_SETSECATTR,     { .vop_setsecattr = zfs_setsecattr },
5478         VOPNAME_VNEVENT,        { .vop_vnevent = fs_vnevent_support },
5479         NULL,                   NULL
5480 };
5481
5482 /*
5483  * Extended attribute directory vnode operations template
5484  *      This template is identical to the directory vnodes
5485  *      operation template except for restricted operations:
5486  *              VOP_MKDIR()
5487  *              VOP_SYMLINK()
5488  * Note that there are other restrictions embedded in:
5489  *      zfs_create()    - restrict type to VREG
5490  *      zfs_link()      - no links into/out of attribute space
5491  *      zfs_rename()    - no moves into/out of attribute space
5492  */
5493 vnodeops_t *zfs_xdvnodeops;
5494 const fs_operation_def_t zfs_xdvnodeops_template[] = {
5495         VOPNAME_OPEN,           { .vop_open = zfs_open },
5496         VOPNAME_CLOSE,          { .vop_close = zfs_close },
5497         VOPNAME_IOCTL,          { .vop_ioctl = zfs_ioctl },
5498         VOPNAME_GETATTR,        { .vop_getattr = zfs_getattr },
5499         VOPNAME_SETATTR,        { .vop_setattr = zfs_setattr },
5500         VOPNAME_ACCESS,         { .vop_access = zfs_access },
5501         VOPNAME_LOOKUP,         { .vop_lookup = zfs_lookup },
5502         VOPNAME_CREATE,         { .vop_create = zfs_create },
5503         VOPNAME_REMOVE,         { .vop_remove = zfs_remove },
5504         VOPNAME_LINK,           { .vop_link = zfs_link },
5505         VOPNAME_RENAME,         { .vop_rename = zfs_rename },
5506         VOPNAME_MKDIR,          { .error = zfs_inval },
5507         VOPNAME_RMDIR,          { .vop_rmdir = zfs_rmdir },
5508         VOPNAME_READDIR,        { .vop_readdir = zfs_readdir },
5509         VOPNAME_SYMLINK,        { .error = zfs_inval },
5510         VOPNAME_FSYNC,          { .vop_fsync = zfs_fsync },
5511         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5512         VOPNAME_FID,            { .vop_fid = zfs_fid },
5513         VOPNAME_SEEK,           { .vop_seek = zfs_seek },
5514         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5515         VOPNAME_GETSECATTR,     { .vop_getsecattr = zfs_getsecattr },
5516         VOPNAME_SETSECATTR,     { .vop_setsecattr = zfs_setsecattr },
5517         VOPNAME_VNEVENT,        { .vop_vnevent = fs_vnevent_support },
5518         NULL,                   NULL
5519 };
5520
5521 /*
5522  * Error vnode operations template
5523  */
5524 vnodeops_t *zfs_evnodeops;
5525 const fs_operation_def_t zfs_evnodeops_template[] = {
5526         VOPNAME_INACTIVE,       { .vop_inactive = zfs_inactive },
5527         VOPNAME_PATHCONF,       { .vop_pathconf = zfs_pathconf },
5528         NULL,                   NULL
5529 };
5530 #endif  /* sun */
5531
5532 static int
5533 ioflags(int ioflags)
5534 {
5535         int flags = 0;
5536
5537         if (ioflags & IO_APPEND)
5538                 flags |= FAPPEND;
5539         if (ioflags & IO_NDELAY)
5540                 flags |= FNONBLOCK;
5541         if (ioflags & IO_SYNC)
5542                 flags |= (FSYNC | FDSYNC | FRSYNC);
5543
5544         return (flags);
5545 }
5546
5547 static int
5548 zfs_getpages(struct vnode *vp, vm_page_t *m, int count, int reqpage)
5549 {
5550         znode_t *zp = VTOZ(vp);
5551         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5552         objset_t *os = zp->z_zfsvfs->z_os;
5553         vm_page_t mreq;
5554         vm_object_t object;
5555         caddr_t va;
5556         struct sf_buf *sf;
5557         int i, error;
5558         int pcount, size;
5559
5560         ZFS_ENTER(zfsvfs);
5561         ZFS_VERIFY_ZP(zp);
5562
5563         pcount = round_page(count) / PAGE_SIZE;
5564         mreq = m[reqpage];
5565         object = mreq->object;
5566         error = 0;
5567
5568         KASSERT(vp->v_object == object, ("mismatching object"));
5569
5570         VM_OBJECT_LOCK(object);
5571
5572         for (i = 0; i < pcount; i++) {
5573                 if (i != reqpage) {
5574                         vm_page_lock(m[i]);
5575                         vm_page_free(m[i]);
5576                         vm_page_unlock(m[i]);
5577                 }
5578         }
5579
5580         if (mreq->valid) {
5581                 if (mreq->valid != VM_PAGE_BITS_ALL)
5582                         vm_page_zero_invalid(mreq, TRUE);
5583                 VM_OBJECT_UNLOCK(object);
5584                 ZFS_EXIT(zfsvfs);
5585                 return (VM_PAGER_OK);
5586         }
5587
5588         PCPU_INC(cnt.v_vnodein);
5589         PCPU_INC(cnt.v_vnodepgsin);
5590
5591         if (IDX_TO_OFF(mreq->pindex) >= object->un_pager.vnp.vnp_size) {
5592                 VM_OBJECT_UNLOCK(object);
5593                 ZFS_EXIT(zfsvfs);
5594                 return (VM_PAGER_BAD);
5595         }
5596
5597         size = PAGE_SIZE;
5598         if (IDX_TO_OFF(mreq->pindex) + size > object->un_pager.vnp.vnp_size)
5599                 size = object->un_pager.vnp.vnp_size - IDX_TO_OFF(mreq->pindex);
5600
5601         VM_OBJECT_UNLOCK(object);
5602         va = zfs_map_page(mreq, &sf);
5603         error = dmu_read(os, zp->z_id, IDX_TO_OFF(mreq->pindex),
5604             size, va, DMU_READ_PREFETCH);
5605         if (size != PAGE_SIZE)
5606                 bzero(va + size, PAGE_SIZE - size);
5607         zfs_unmap_page(sf);
5608         VM_OBJECT_LOCK(object);
5609
5610         if (!error)
5611                 mreq->valid = VM_PAGE_BITS_ALL;
5612         KASSERT(mreq->dirty == 0, ("zfs_getpages: page %p is dirty", mreq));
5613
5614         VM_OBJECT_UNLOCK(object);
5615
5616         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
5617         ZFS_EXIT(zfsvfs);
5618         return (error ? VM_PAGER_ERROR : VM_PAGER_OK);
5619 }
5620
5621 static int
5622 zfs_freebsd_getpages(ap)
5623         struct vop_getpages_args /* {
5624                 struct vnode *a_vp;
5625                 vm_page_t *a_m;
5626                 int a_count;
5627                 int a_reqpage;
5628                 vm_ooffset_t a_offset;
5629         } */ *ap;
5630 {
5631
5632         return (zfs_getpages(ap->a_vp, ap->a_m, ap->a_count, ap->a_reqpage));
5633 }
5634
5635 static int
5636 zfs_freebsd_open(ap)
5637         struct vop_open_args /* {
5638                 struct vnode *a_vp;
5639                 int a_mode;
5640                 struct ucred *a_cred;
5641                 struct thread *a_td;
5642         } */ *ap;
5643 {
5644         vnode_t *vp = ap->a_vp;
5645         znode_t *zp = VTOZ(vp);
5646         int error;
5647
5648         error = zfs_open(&vp, ap->a_mode, ap->a_cred, NULL);
5649         if (error == 0)
5650                 vnode_create_vobject(vp, zp->z_size, ap->a_td);
5651         return (error);
5652 }
5653
5654 static int
5655 zfs_freebsd_close(ap)
5656         struct vop_close_args /* {
5657                 struct vnode *a_vp;
5658                 int  a_fflag;
5659                 struct ucred *a_cred;
5660                 struct thread *a_td;
5661         } */ *ap;
5662 {
5663
5664         return (zfs_close(ap->a_vp, ap->a_fflag, 0, 0, ap->a_cred, NULL));
5665 }
5666
5667 static int
5668 zfs_freebsd_ioctl(ap)
5669         struct vop_ioctl_args /* {
5670                 struct vnode *a_vp;
5671                 u_long a_command;
5672                 caddr_t a_data;
5673                 int a_fflag;
5674                 struct ucred *cred;
5675                 struct thread *td;
5676         } */ *ap;
5677 {
5678
5679         return (zfs_ioctl(ap->a_vp, ap->a_command, (intptr_t)ap->a_data,
5680             ap->a_fflag, ap->a_cred, NULL, NULL));
5681 }
5682
5683 static int
5684 zfs_freebsd_read(ap)
5685         struct vop_read_args /* {
5686                 struct vnode *a_vp;
5687                 struct uio *a_uio;
5688                 int a_ioflag;
5689                 struct ucred *a_cred;
5690         } */ *ap;
5691 {
5692
5693         return (zfs_read(ap->a_vp, ap->a_uio, ioflags(ap->a_ioflag),
5694             ap->a_cred, NULL));
5695 }
5696
5697 static int
5698 zfs_freebsd_write(ap)
5699         struct vop_write_args /* {
5700                 struct vnode *a_vp;
5701                 struct uio *a_uio;
5702                 int a_ioflag;
5703                 struct ucred *a_cred;
5704         } */ *ap;
5705 {
5706
5707         return (zfs_write(ap->a_vp, ap->a_uio, ioflags(ap->a_ioflag),
5708             ap->a_cred, NULL));
5709 }
5710
5711 static int
5712 zfs_freebsd_access(ap)
5713         struct vop_access_args /* {
5714                 struct vnode *a_vp;
5715                 accmode_t a_accmode;
5716                 struct ucred *a_cred;
5717                 struct thread *a_td;
5718         } */ *ap;
5719 {
5720         vnode_t *vp = ap->a_vp;
5721         znode_t *zp = VTOZ(vp);
5722         accmode_t accmode;
5723         int error = 0;
5724
5725         /*
5726          * ZFS itself only knowns about VREAD, VWRITE, VEXEC and VAPPEND,
5727          */
5728         accmode = ap->a_accmode & (VREAD|VWRITE|VEXEC|VAPPEND);
5729         if (accmode != 0)
5730                 error = zfs_access(ap->a_vp, accmode, 0, ap->a_cred, NULL);
5731
5732         /*
5733          * VADMIN has to be handled by vaccess().
5734          */
5735         if (error == 0) {
5736                 accmode = ap->a_accmode & ~(VREAD|VWRITE|VEXEC|VAPPEND);
5737                 if (accmode != 0) {
5738                         error = vaccess(vp->v_type, zp->z_mode, zp->z_uid,
5739                             zp->z_gid, accmode, ap->a_cred, NULL);
5740                 }
5741         }
5742
5743         /*
5744          * For VEXEC, ensure that at least one execute bit is set for
5745          * non-directories.
5746          */
5747         if (error == 0 && (ap->a_accmode & VEXEC) != 0 && vp->v_type != VDIR &&
5748             (zp->z_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) {
5749                 error = EACCES;
5750         }
5751
5752         return (error);
5753 }
5754
5755 static int
5756 zfs_freebsd_lookup(ap)
5757         struct vop_lookup_args /* {
5758                 struct vnode *a_dvp;
5759                 struct vnode **a_vpp;
5760                 struct componentname *a_cnp;
5761         } */ *ap;
5762 {
5763         struct componentname *cnp = ap->a_cnp;
5764         char nm[NAME_MAX + 1];
5765
5766         ASSERT(cnp->cn_namelen < sizeof(nm));
5767         strlcpy(nm, cnp->cn_nameptr, MIN(cnp->cn_namelen + 1, sizeof(nm)));
5768
5769         return (zfs_lookup(ap->a_dvp, nm, ap->a_vpp, cnp, cnp->cn_nameiop,
5770             cnp->cn_cred, cnp->cn_thread, 0));
5771 }
5772
5773 static int
5774 zfs_freebsd_create(ap)
5775         struct vop_create_args /* {
5776                 struct vnode *a_dvp;
5777                 struct vnode **a_vpp;
5778                 struct componentname *a_cnp;
5779                 struct vattr *a_vap;
5780         } */ *ap;
5781 {
5782         struct componentname *cnp = ap->a_cnp;
5783         vattr_t *vap = ap->a_vap;
5784         int mode;
5785
5786         ASSERT(cnp->cn_flags & SAVENAME);
5787
5788         vattr_init_mask(vap);
5789         mode = vap->va_mode & ALLPERMS;
5790
5791         return (zfs_create(ap->a_dvp, cnp->cn_nameptr, vap, !EXCL, mode,
5792             ap->a_vpp, cnp->cn_cred, cnp->cn_thread));
5793 }
5794
5795 static int
5796 zfs_freebsd_remove(ap)
5797         struct vop_remove_args /* {
5798                 struct vnode *a_dvp;
5799                 struct vnode *a_vp;
5800                 struct componentname *a_cnp;
5801         } */ *ap;
5802 {
5803
5804         ASSERT(ap->a_cnp->cn_flags & SAVENAME);
5805
5806         return (zfs_remove(ap->a_dvp, ap->a_cnp->cn_nameptr,
5807             ap->a_cnp->cn_cred, NULL, 0));
5808 }
5809
5810 static int
5811 zfs_freebsd_mkdir(ap)
5812         struct vop_mkdir_args /* {
5813                 struct vnode *a_dvp;
5814                 struct vnode **a_vpp;
5815                 struct componentname *a_cnp;
5816                 struct vattr *a_vap;
5817         } */ *ap;
5818 {
5819         vattr_t *vap = ap->a_vap;
5820
5821         ASSERT(ap->a_cnp->cn_flags & SAVENAME);
5822
5823         vattr_init_mask(vap);
5824
5825         return (zfs_mkdir(ap->a_dvp, ap->a_cnp->cn_nameptr, vap, ap->a_vpp,
5826             ap->a_cnp->cn_cred, NULL, 0, NULL));
5827 }
5828
5829 static int
5830 zfs_freebsd_rmdir(ap)
5831         struct vop_rmdir_args /* {
5832                 struct vnode *a_dvp;
5833                 struct vnode *a_vp;
5834                 struct componentname *a_cnp;
5835         } */ *ap;
5836 {
5837         struct componentname *cnp = ap->a_cnp;
5838
5839         ASSERT(cnp->cn_flags & SAVENAME);
5840
5841         return (zfs_rmdir(ap->a_dvp, cnp->cn_nameptr, NULL, cnp->cn_cred, NULL, 0));
5842 }
5843
5844 static int
5845 zfs_freebsd_readdir(ap)
5846         struct vop_readdir_args /* {
5847                 struct vnode *a_vp;
5848                 struct uio *a_uio;
5849                 struct ucred *a_cred;
5850                 int *a_eofflag;
5851                 int *a_ncookies;
5852                 u_long **a_cookies;
5853         } */ *ap;
5854 {
5855
5856         return (zfs_readdir(ap->a_vp, ap->a_uio, ap->a_cred, ap->a_eofflag,
5857             ap->a_ncookies, ap->a_cookies));
5858 }
5859
5860 static int
5861 zfs_freebsd_fsync(ap)
5862         struct vop_fsync_args /* {
5863                 struct vnode *a_vp;
5864                 int a_waitfor;
5865                 struct thread *a_td;
5866         } */ *ap;
5867 {
5868
5869         vop_stdfsync(ap);
5870         return (zfs_fsync(ap->a_vp, 0, ap->a_td->td_ucred, NULL));
5871 }
5872
5873 static int
5874 zfs_freebsd_getattr(ap)
5875         struct vop_getattr_args /* {
5876                 struct vnode *a_vp;
5877                 struct vattr *a_vap;
5878                 struct ucred *a_cred;
5879         } */ *ap;
5880 {
5881         vattr_t *vap = ap->a_vap;
5882         xvattr_t xvap;
5883         u_long fflags = 0;
5884         int error;
5885
5886         xva_init(&xvap);
5887         xvap.xva_vattr = *vap;
5888         xvap.xva_vattr.va_mask |= AT_XVATTR;
5889
5890         /* Convert chflags into ZFS-type flags. */
5891         /* XXX: what about SF_SETTABLE?. */
5892         XVA_SET_REQ(&xvap, XAT_IMMUTABLE);
5893         XVA_SET_REQ(&xvap, XAT_APPENDONLY);
5894         XVA_SET_REQ(&xvap, XAT_NOUNLINK);
5895         XVA_SET_REQ(&xvap, XAT_NODUMP);
5896         error = zfs_getattr(ap->a_vp, (vattr_t *)&xvap, 0, ap->a_cred, NULL);
5897         if (error != 0)
5898                 return (error);
5899
5900         /* Convert ZFS xattr into chflags. */
5901 #define FLAG_CHECK(fflag, xflag, xfield)        do {                    \
5902         if (XVA_ISSET_RTN(&xvap, (xflag)) && (xfield) != 0)             \
5903                 fflags |= (fflag);                                      \
5904 } while (0)
5905         FLAG_CHECK(SF_IMMUTABLE, XAT_IMMUTABLE,
5906             xvap.xva_xoptattrs.xoa_immutable);
5907         FLAG_CHECK(SF_APPEND, XAT_APPENDONLY,
5908             xvap.xva_xoptattrs.xoa_appendonly);
5909         FLAG_CHECK(SF_NOUNLINK, XAT_NOUNLINK,
5910             xvap.xva_xoptattrs.xoa_nounlink);
5911         FLAG_CHECK(UF_NODUMP, XAT_NODUMP,
5912             xvap.xva_xoptattrs.xoa_nodump);
5913 #undef  FLAG_CHECK
5914         *vap = xvap.xva_vattr;
5915         vap->va_flags = fflags;
5916         return (0);
5917 }
5918
5919 static int
5920 zfs_freebsd_setattr(ap)
5921         struct vop_setattr_args /* {
5922                 struct vnode *a_vp;
5923                 struct vattr *a_vap;
5924                 struct ucred *a_cred;
5925         } */ *ap;
5926 {
5927         vnode_t *vp = ap->a_vp;
5928         vattr_t *vap = ap->a_vap;
5929         cred_t *cred = ap->a_cred;
5930         xvattr_t xvap;
5931         u_long fflags;
5932         uint64_t zflags;
5933
5934         vattr_init_mask(vap);
5935         vap->va_mask &= ~AT_NOSET;
5936
5937         xva_init(&xvap);
5938         xvap.xva_vattr = *vap;
5939
5940         zflags = VTOZ(vp)->z_pflags;
5941
5942         if (vap->va_flags != VNOVAL) {
5943                 zfsvfs_t *zfsvfs = VTOZ(vp)->z_zfsvfs;
5944                 int error;
5945
5946                 if (zfsvfs->z_use_fuids == B_FALSE)
5947                         return (EOPNOTSUPP);
5948
5949                 fflags = vap->va_flags;
5950                 if ((fflags & ~(SF_IMMUTABLE|SF_APPEND|SF_NOUNLINK|UF_NODUMP)) != 0)
5951                         return (EOPNOTSUPP);
5952                 /*
5953                  * Unprivileged processes are not permitted to unset system
5954                  * flags, or modify flags if any system flags are set.
5955                  * Privileged non-jail processes may not modify system flags
5956                  * if securelevel > 0 and any existing system flags are set.
5957                  * Privileged jail processes behave like privileged non-jail
5958                  * processes if the security.jail.chflags_allowed sysctl is
5959                  * is non-zero; otherwise, they behave like unprivileged
5960                  * processes.
5961                  */
5962                 if (secpolicy_fs_owner(vp->v_mount, cred) == 0 ||
5963                     priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0) == 0) {
5964                         if (zflags &
5965                             (ZFS_IMMUTABLE | ZFS_APPENDONLY | ZFS_NOUNLINK)) {
5966                                 error = securelevel_gt(cred, 0);
5967                                 if (error != 0)
5968                                         return (error);
5969                         }
5970                 } else {
5971                         /*
5972                          * Callers may only modify the file flags on objects they
5973                          * have VADMIN rights for.
5974                          */
5975                         if ((error = VOP_ACCESS(vp, VADMIN, cred, curthread)) != 0)
5976                                 return (error);
5977                         if (zflags &
5978                             (ZFS_IMMUTABLE | ZFS_APPENDONLY | ZFS_NOUNLINK)) {
5979                                 return (EPERM);
5980                         }
5981                         if (fflags &
5982                             (SF_IMMUTABLE | SF_APPEND | SF_NOUNLINK)) {
5983                                 return (EPERM);
5984                         }
5985                 }
5986
5987 #define FLAG_CHANGE(fflag, zflag, xflag, xfield)        do {            \
5988         if (((fflags & (fflag)) && !(zflags & (zflag))) ||              \
5989             ((zflags & (zflag)) && !(fflags & (fflag)))) {              \
5990                 XVA_SET_REQ(&xvap, (xflag));                            \
5991                 (xfield) = ((fflags & (fflag)) != 0);                   \
5992         }                                                               \
5993 } while (0)
5994                 /* Convert chflags into ZFS-type flags. */
5995                 /* XXX: what about SF_SETTABLE?. */
5996                 FLAG_CHANGE(SF_IMMUTABLE, ZFS_IMMUTABLE, XAT_IMMUTABLE,
5997                     xvap.xva_xoptattrs.xoa_immutable);
5998                 FLAG_CHANGE(SF_APPEND, ZFS_APPENDONLY, XAT_APPENDONLY,
5999                     xvap.xva_xoptattrs.xoa_appendonly);
6000                 FLAG_CHANGE(SF_NOUNLINK, ZFS_NOUNLINK, XAT_NOUNLINK,
6001                     xvap.xva_xoptattrs.xoa_nounlink);
6002                 FLAG_CHANGE(UF_NODUMP, ZFS_NODUMP, XAT_NODUMP,
6003                     xvap.xva_xoptattrs.xoa_nodump);
6004 #undef  FLAG_CHANGE
6005         }
6006         return (zfs_setattr(vp, (vattr_t *)&xvap, 0, cred, NULL));
6007 }
6008
6009 static int
6010 zfs_freebsd_rename(ap)
6011         struct vop_rename_args  /* {
6012                 struct vnode *a_fdvp;
6013                 struct vnode *a_fvp;
6014                 struct componentname *a_fcnp;
6015                 struct vnode *a_tdvp;
6016                 struct vnode *a_tvp;
6017                 struct componentname *a_tcnp;
6018         } */ *ap;
6019 {
6020         vnode_t *fdvp = ap->a_fdvp;
6021         vnode_t *fvp = ap->a_fvp;
6022         vnode_t *tdvp = ap->a_tdvp;
6023         vnode_t *tvp = ap->a_tvp;
6024         int error;
6025
6026         ASSERT(ap->a_fcnp->cn_flags & (SAVENAME|SAVESTART));
6027         ASSERT(ap->a_tcnp->cn_flags & (SAVENAME|SAVESTART));
6028
6029         error = zfs_rename(fdvp, ap->a_fcnp->cn_nameptr, tdvp,
6030             ap->a_tcnp->cn_nameptr, ap->a_fcnp->cn_cred, NULL, 0);
6031
6032         if (tdvp == tvp)
6033                 VN_RELE(tdvp);
6034         else
6035                 VN_URELE(tdvp);
6036         if (tvp)
6037                 VN_URELE(tvp);
6038         VN_RELE(fdvp);
6039         VN_RELE(fvp);
6040
6041         return (error);
6042 }
6043
6044 static int
6045 zfs_freebsd_symlink(ap)
6046         struct vop_symlink_args /* {
6047                 struct vnode *a_dvp;
6048                 struct vnode **a_vpp;
6049                 struct componentname *a_cnp;
6050                 struct vattr *a_vap;
6051                 char *a_target;
6052         } */ *ap;
6053 {
6054         struct componentname *cnp = ap->a_cnp;
6055         vattr_t *vap = ap->a_vap;
6056
6057         ASSERT(cnp->cn_flags & SAVENAME);
6058
6059         vap->va_type = VLNK;    /* FreeBSD: Syscall only sets va_mode. */
6060         vattr_init_mask(vap);
6061
6062         return (zfs_symlink(ap->a_dvp, ap->a_vpp, cnp->cn_nameptr, vap,
6063             ap->a_target, cnp->cn_cred, cnp->cn_thread));
6064 }
6065
6066 static int
6067 zfs_freebsd_readlink(ap)
6068         struct vop_readlink_args /* {
6069                 struct vnode *a_vp;
6070                 struct uio *a_uio;
6071                 struct ucred *a_cred;
6072         } */ *ap;
6073 {
6074
6075         return (zfs_readlink(ap->a_vp, ap->a_uio, ap->a_cred, NULL));
6076 }
6077
6078 static int
6079 zfs_freebsd_link(ap)
6080         struct vop_link_args /* {
6081                 struct vnode *a_tdvp;
6082                 struct vnode *a_vp;
6083                 struct componentname *a_cnp;
6084         } */ *ap;
6085 {
6086         struct componentname *cnp = ap->a_cnp;
6087
6088         ASSERT(cnp->cn_flags & SAVENAME);
6089
6090         return (zfs_link(ap->a_tdvp, ap->a_vp, cnp->cn_nameptr, cnp->cn_cred, NULL, 0));
6091 }
6092
6093 static int
6094 zfs_freebsd_inactive(ap)
6095         struct vop_inactive_args /* {
6096                 struct vnode *a_vp;
6097                 struct thread *a_td;
6098         } */ *ap;
6099 {
6100         vnode_t *vp = ap->a_vp;
6101
6102         zfs_inactive(vp, ap->a_td->td_ucred, NULL);
6103         return (0);
6104 }
6105
6106 static void
6107 zfs_reclaim_complete(void *arg, int pending)
6108 {
6109         znode_t *zp = arg;
6110         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
6111
6112         rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
6113         if (zp->z_sa_hdl != NULL) {
6114                 ZFS_OBJ_HOLD_ENTER(zfsvfs, zp->z_id);
6115                 zfs_znode_dmu_fini(zp);
6116                 ZFS_OBJ_HOLD_EXIT(zfsvfs, zp->z_id);
6117         }
6118         zfs_znode_free(zp);
6119         rw_exit(&zfsvfs->z_teardown_inactive_lock);
6120         /*
6121          * If the file system is being unmounted, there is a process waiting
6122          * for us, wake it up.
6123          */
6124         if (zfsvfs->z_unmounted)
6125                 wakeup_one(zfsvfs);
6126 }
6127
6128 static int
6129 zfs_freebsd_reclaim(ap)
6130         struct vop_reclaim_args /* {
6131                 struct vnode *a_vp;
6132                 struct thread *a_td;
6133         } */ *ap;
6134 {
6135         vnode_t *vp = ap->a_vp;
6136         znode_t *zp = VTOZ(vp);
6137         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
6138         boolean_t rlocked;
6139
6140         rlocked = rw_tryenter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
6141
6142         ASSERT(zp != NULL);
6143
6144         /*
6145          * Destroy the vm object and flush associated pages.
6146          */
6147         vnode_destroy_vobject(vp);
6148
6149         mutex_enter(&zp->z_lock);
6150         zp->z_vnode = NULL;
6151         mutex_exit(&zp->z_lock);
6152
6153         if (zp->z_unlinked) {
6154                 ;       /* Do nothing. */
6155         } else if (!rlocked) {
6156                 TASK_INIT(&zp->z_task, 0, zfs_reclaim_complete, zp);
6157                 taskqueue_enqueue(taskqueue_thread, &zp->z_task);
6158         } else if (zp->z_sa_hdl == NULL) {
6159                 zfs_znode_free(zp);
6160         } else /* if (!zp->z_unlinked && zp->z_dbuf != NULL) */ {
6161                 int locked;
6162
6163                 locked = MUTEX_HELD(ZFS_OBJ_MUTEX(zfsvfs, zp->z_id)) ? 2 :
6164                     ZFS_OBJ_HOLD_TRYENTER(zfsvfs, zp->z_id);
6165                 if (locked == 0) {
6166                         /*
6167                          * Lock can't be obtained due to deadlock possibility,
6168                          * so defer znode destruction.
6169                          */
6170                         TASK_INIT(&zp->z_task, 0, zfs_reclaim_complete, zp);
6171                         taskqueue_enqueue(taskqueue_thread, &zp->z_task);
6172                 } else {
6173                         zfs_znode_dmu_fini(zp);
6174                         if (locked == 1)
6175                                 ZFS_OBJ_HOLD_EXIT(zfsvfs, zp->z_id);
6176                         zfs_znode_free(zp);
6177                 }
6178         }
6179         VI_LOCK(vp);
6180         vp->v_data = NULL;
6181         ASSERT(vp->v_holdcnt >= 1);
6182         VI_UNLOCK(vp);
6183         if (rlocked)
6184                 rw_exit(&zfsvfs->z_teardown_inactive_lock);
6185         return (0);
6186 }
6187
6188 static int
6189 zfs_freebsd_fid(ap)
6190         struct vop_fid_args /* {
6191                 struct vnode *a_vp;
6192                 struct fid *a_fid;
6193         } */ *ap;
6194 {
6195
6196         return (zfs_fid(ap->a_vp, (void *)ap->a_fid, NULL));
6197 }
6198
6199 static int
6200 zfs_freebsd_pathconf(ap)
6201         struct vop_pathconf_args /* {
6202                 struct vnode *a_vp;
6203                 int a_name;
6204                 register_t *a_retval;
6205         } */ *ap;
6206 {
6207         ulong_t val;
6208         int error;
6209
6210         error = zfs_pathconf(ap->a_vp, ap->a_name, &val, curthread->td_ucred, NULL);
6211         if (error == 0)
6212                 *ap->a_retval = val;
6213         else if (error == EOPNOTSUPP)
6214                 error = vop_stdpathconf(ap);
6215         return (error);
6216 }
6217
6218 static int
6219 zfs_freebsd_fifo_pathconf(ap)
6220         struct vop_pathconf_args /* {
6221                 struct vnode *a_vp;
6222                 int a_name;
6223                 register_t *a_retval;
6224         } */ *ap;
6225 {
6226
6227         switch (ap->a_name) {
6228         case _PC_ACL_EXTENDED:
6229         case _PC_ACL_NFS4:
6230         case _PC_ACL_PATH_MAX:
6231         case _PC_MAC_PRESENT:
6232                 return (zfs_freebsd_pathconf(ap));
6233         default:
6234                 return (fifo_specops.vop_pathconf(ap));
6235         }
6236 }
6237
6238 /*
6239  * FreeBSD's extended attributes namespace defines file name prefix for ZFS'
6240  * extended attribute name:
6241  *
6242  *      NAMESPACE       PREFIX  
6243  *      system          freebsd:system:
6244  *      user            (none, can be used to access ZFS fsattr(5) attributes
6245  *                      created on Solaris)
6246  */
6247 static int
6248 zfs_create_attrname(int attrnamespace, const char *name, char *attrname,
6249     size_t size)
6250 {
6251         const char *namespace, *prefix, *suffix;
6252
6253         /* We don't allow '/' character in attribute name. */
6254         if (strchr(name, '/') != NULL)
6255                 return (EINVAL);
6256         /* We don't allow attribute names that start with "freebsd:" string. */
6257         if (strncmp(name, "freebsd:", 8) == 0)
6258                 return (EINVAL);
6259
6260         bzero(attrname, size);
6261
6262         switch (attrnamespace) {
6263         case EXTATTR_NAMESPACE_USER:
6264 #if 0
6265                 prefix = "freebsd:";
6266                 namespace = EXTATTR_NAMESPACE_USER_STRING;
6267                 suffix = ":";
6268 #else
6269                 /*
6270                  * This is the default namespace by which we can access all
6271                  * attributes created on Solaris.
6272                  */
6273                 prefix = namespace = suffix = "";
6274 #endif
6275                 break;
6276         case EXTATTR_NAMESPACE_SYSTEM:
6277                 prefix = "freebsd:";
6278                 namespace = EXTATTR_NAMESPACE_SYSTEM_STRING;
6279                 suffix = ":";
6280                 break;
6281         case EXTATTR_NAMESPACE_EMPTY:
6282         default:
6283                 return (EINVAL);
6284         }
6285         if (snprintf(attrname, size, "%s%s%s%s", prefix, namespace, suffix,
6286             name) >= size) {
6287                 return (ENAMETOOLONG);
6288         }
6289         return (0);
6290 }
6291
6292 /*
6293  * Vnode operating to retrieve a named extended attribute.
6294  */
6295 static int
6296 zfs_getextattr(struct vop_getextattr_args *ap)
6297 /*
6298 vop_getextattr {
6299         IN struct vnode *a_vp;
6300         IN int a_attrnamespace;
6301         IN const char *a_name;
6302         INOUT struct uio *a_uio;
6303         OUT size_t *a_size;
6304         IN struct ucred *a_cred;
6305         IN struct thread *a_td;
6306 };
6307 */
6308 {
6309         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
6310         struct thread *td = ap->a_td;
6311         struct nameidata nd;
6312         char attrname[255];
6313         struct vattr va;
6314         vnode_t *xvp = NULL, *vp;
6315         int error, flags;
6316
6317         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6318             ap->a_cred, ap->a_td, VREAD);
6319         if (error != 0)
6320                 return (error);
6321
6322         error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6323             sizeof(attrname));
6324         if (error != 0)
6325                 return (error);
6326
6327         ZFS_ENTER(zfsvfs);
6328
6329         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
6330             LOOKUP_XATTR);
6331         if (error != 0) {
6332                 ZFS_EXIT(zfsvfs);
6333                 return (error);
6334         }
6335
6336         flags = FREAD;
6337         NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, attrname,
6338             xvp, td);
6339         error = vn_open_cred(&nd, &flags, 0, 0, ap->a_cred, NULL);
6340         vp = nd.ni_vp;
6341         NDFREE(&nd, NDF_ONLY_PNBUF);
6342         if (error != 0) {
6343                 ZFS_EXIT(zfsvfs);
6344                 if (error == ENOENT)
6345                         error = ENOATTR;
6346                 return (error);
6347         }
6348
6349         if (ap->a_size != NULL) {
6350                 error = VOP_GETATTR(vp, &va, ap->a_cred);
6351                 if (error == 0)
6352                         *ap->a_size = (size_t)va.va_size;
6353         } else if (ap->a_uio != NULL)
6354                 error = VOP_READ(vp, ap->a_uio, IO_UNIT, ap->a_cred);
6355
6356         VOP_UNLOCK(vp, 0);
6357         vn_close(vp, flags, ap->a_cred, td);
6358         ZFS_EXIT(zfsvfs);
6359
6360         return (error);
6361 }
6362
6363 /*
6364  * Vnode operation to remove a named attribute.
6365  */
6366 int
6367 zfs_deleteextattr(struct vop_deleteextattr_args *ap)
6368 /*
6369 vop_deleteextattr {
6370         IN struct vnode *a_vp;
6371         IN int a_attrnamespace;
6372         IN const char *a_name;
6373         IN struct ucred *a_cred;
6374         IN struct thread *a_td;
6375 };
6376 */
6377 {
6378         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
6379         struct thread *td = ap->a_td;
6380         struct nameidata nd;
6381         char attrname[255];
6382         struct vattr va;
6383         vnode_t *xvp = NULL, *vp;
6384         int error, flags;
6385
6386         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6387             ap->a_cred, ap->a_td, VWRITE);
6388         if (error != 0)
6389                 return (error);
6390
6391         error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6392             sizeof(attrname));
6393         if (error != 0)
6394                 return (error);
6395
6396         ZFS_ENTER(zfsvfs);
6397
6398         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
6399             LOOKUP_XATTR);
6400         if (error != 0) {
6401                 ZFS_EXIT(zfsvfs);
6402                 return (error);
6403         }
6404
6405         NDINIT_ATVP(&nd, DELETE, NOFOLLOW | LOCKPARENT | LOCKLEAF | MPSAFE,
6406             UIO_SYSSPACE, attrname, xvp, td);
6407         error = namei(&nd);
6408         vp = nd.ni_vp;
6409         NDFREE(&nd, NDF_ONLY_PNBUF);
6410         if (error != 0) {
6411                 ZFS_EXIT(zfsvfs);
6412                 if (error == ENOENT)
6413                         error = ENOATTR;
6414                 return (error);
6415         }
6416         error = VOP_REMOVE(nd.ni_dvp, vp, &nd.ni_cnd);
6417
6418         vput(nd.ni_dvp);
6419         if (vp == nd.ni_dvp)
6420                 vrele(vp);
6421         else
6422                 vput(vp);
6423         ZFS_EXIT(zfsvfs);
6424
6425         return (error);
6426 }
6427
6428 /*
6429  * Vnode operation to set a named attribute.
6430  */
6431 static int
6432 zfs_setextattr(struct vop_setextattr_args *ap)
6433 /*
6434 vop_setextattr {
6435         IN struct vnode *a_vp;
6436         IN int a_attrnamespace;
6437         IN const char *a_name;
6438         INOUT struct uio *a_uio;
6439         IN struct ucred *a_cred;
6440         IN struct thread *a_td;
6441 };
6442 */
6443 {
6444         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
6445         struct thread *td = ap->a_td;
6446         struct nameidata nd;
6447         char attrname[255];
6448         struct vattr va;
6449         vnode_t *xvp = NULL, *vp;
6450         int error, flags;
6451
6452         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6453             ap->a_cred, ap->a_td, VWRITE);
6454         if (error != 0)
6455                 return (error);
6456
6457         error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6458             sizeof(attrname));
6459         if (error != 0)
6460                 return (error);
6461
6462         ZFS_ENTER(zfsvfs);
6463
6464         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
6465             LOOKUP_XATTR | CREATE_XATTR_DIR);
6466         if (error != 0) {
6467                 ZFS_EXIT(zfsvfs);
6468                 return (error);
6469         }
6470
6471         flags = FFLAGS(O_WRONLY | O_CREAT);
6472         NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, attrname,
6473             xvp, td);
6474         error = vn_open_cred(&nd, &flags, 0600, 0, ap->a_cred, NULL);
6475         vp = nd.ni_vp;
6476         NDFREE(&nd, NDF_ONLY_PNBUF);
6477         if (error != 0) {
6478                 ZFS_EXIT(zfsvfs);
6479                 return (error);
6480         }
6481
6482         VATTR_NULL(&va);
6483         va.va_size = 0;
6484         error = VOP_SETATTR(vp, &va, ap->a_cred);
6485         if (error == 0)
6486                 VOP_WRITE(vp, ap->a_uio, IO_UNIT | IO_SYNC, ap->a_cred);
6487
6488         VOP_UNLOCK(vp, 0);
6489         vn_close(vp, flags, ap->a_cred, td);
6490         ZFS_EXIT(zfsvfs);
6491
6492         return (error);
6493 }
6494
6495 /*
6496  * Vnode operation to retrieve extended attributes on a vnode.
6497  */
6498 static int
6499 zfs_listextattr(struct vop_listextattr_args *ap)
6500 /*
6501 vop_listextattr {
6502         IN struct vnode *a_vp;
6503         IN int a_attrnamespace;
6504         INOUT struct uio *a_uio;
6505         OUT size_t *a_size;
6506         IN struct ucred *a_cred;
6507         IN struct thread *a_td;
6508 };
6509 */
6510 {
6511         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
6512         struct thread *td = ap->a_td;
6513         struct nameidata nd;
6514         char attrprefix[16];
6515         u_char dirbuf[sizeof(struct dirent)];
6516         struct dirent *dp;
6517         struct iovec aiov;
6518         struct uio auio, *uio = ap->a_uio;
6519         size_t *sizep = ap->a_size;
6520         size_t plen;
6521         vnode_t *xvp = NULL, *vp;
6522         int done, error, eof, pos;
6523
6524         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6525             ap->a_cred, ap->a_td, VREAD);
6526         if (error != 0)
6527                 return (error);
6528
6529         error = zfs_create_attrname(ap->a_attrnamespace, "", attrprefix,
6530             sizeof(attrprefix));
6531         if (error != 0)
6532                 return (error);
6533         plen = strlen(attrprefix);
6534
6535         ZFS_ENTER(zfsvfs);
6536
6537         if (sizep != NULL)
6538                 *sizep = 0;
6539
6540         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
6541             LOOKUP_XATTR);
6542         if (error != 0) {
6543                 ZFS_EXIT(zfsvfs);
6544                 /*
6545                  * ENOATTR means that the EA directory does not yet exist,
6546                  * i.e. there are no extended attributes there.
6547                  */
6548                 if (error == ENOATTR)
6549                         error = 0;
6550                 return (error);
6551         }
6552
6553         NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | LOCKLEAF | LOCKSHARED | MPSAFE,
6554             UIO_SYSSPACE, ".", xvp, td);
6555         error = namei(&nd);
6556         vp = nd.ni_vp;
6557         NDFREE(&nd, NDF_ONLY_PNBUF);
6558         if (error != 0) {
6559                 ZFS_EXIT(zfsvfs);
6560                 return (error);
6561         }
6562
6563         auio.uio_iov = &aiov;
6564         auio.uio_iovcnt = 1;
6565         auio.uio_segflg = UIO_SYSSPACE;
6566         auio.uio_td = td;
6567         auio.uio_rw = UIO_READ;
6568         auio.uio_offset = 0;
6569
6570         do {
6571                 u_char nlen;
6572
6573                 aiov.iov_base = (void *)dirbuf;
6574                 aiov.iov_len = sizeof(dirbuf);
6575                 auio.uio_resid = sizeof(dirbuf);
6576                 error = VOP_READDIR(vp, &auio, ap->a_cred, &eof, NULL, NULL);
6577                 done = sizeof(dirbuf) - auio.uio_resid;
6578                 if (error != 0)
6579                         break;
6580                 for (pos = 0; pos < done;) {
6581                         dp = (struct dirent *)(dirbuf + pos);
6582                         pos += dp->d_reclen;
6583                         /*
6584                          * XXX: Temporarily we also accept DT_UNKNOWN, as this
6585                          * is what we get when attribute was created on Solaris.
6586                          */
6587                         if (dp->d_type != DT_REG && dp->d_type != DT_UNKNOWN)
6588                                 continue;
6589                         if (plen == 0 && strncmp(dp->d_name, "freebsd:", 8) == 0)
6590                                 continue;
6591                         else if (strncmp(dp->d_name, attrprefix, plen) != 0)
6592                                 continue;
6593                         nlen = dp->d_namlen - plen;
6594                         if (sizep != NULL)
6595                                 *sizep += 1 + nlen;
6596                         else if (uio != NULL) {
6597                                 /*
6598                                  * Format of extattr name entry is one byte for
6599                                  * length and the rest for name.
6600                                  */
6601                                 error = uiomove(&nlen, 1, uio->uio_rw, uio);
6602                                 if (error == 0) {
6603                                         error = uiomove(dp->d_name + plen, nlen,
6604                                             uio->uio_rw, uio);
6605                                 }
6606                                 if (error != 0)
6607                                         break;
6608                         }
6609                 }
6610         } while (!eof && error == 0);
6611
6612         vput(vp);
6613         ZFS_EXIT(zfsvfs);
6614
6615         return (error);
6616 }
6617
6618 int
6619 zfs_freebsd_getacl(ap)
6620         struct vop_getacl_args /* {
6621                 struct vnode *vp;
6622                 acl_type_t type;
6623                 struct acl *aclp;
6624                 struct ucred *cred;
6625                 struct thread *td;
6626         } */ *ap;
6627 {
6628         int             error;
6629         vsecattr_t      vsecattr;
6630
6631         if (ap->a_type != ACL_TYPE_NFS4)
6632                 return (EINVAL);
6633
6634         vsecattr.vsa_mask = VSA_ACE | VSA_ACECNT;
6635         if (error = zfs_getsecattr(ap->a_vp, &vsecattr, 0, ap->a_cred, NULL))
6636                 return (error);
6637
6638         error = acl_from_aces(ap->a_aclp, vsecattr.vsa_aclentp, vsecattr.vsa_aclcnt);
6639         if (vsecattr.vsa_aclentp != NULL)
6640                 kmem_free(vsecattr.vsa_aclentp, vsecattr.vsa_aclentsz);
6641
6642         return (error);
6643 }
6644
6645 int
6646 zfs_freebsd_setacl(ap)
6647         struct vop_setacl_args /* {
6648                 struct vnode *vp;
6649                 acl_type_t type;
6650                 struct acl *aclp;
6651                 struct ucred *cred;
6652                 struct thread *td;
6653         } */ *ap;
6654 {
6655         int             error;
6656         vsecattr_t      vsecattr;
6657         int             aclbsize;       /* size of acl list in bytes */
6658         aclent_t        *aaclp;
6659
6660         if (ap->a_type != ACL_TYPE_NFS4)
6661                 return (EINVAL);
6662
6663         if (ap->a_aclp->acl_cnt < 1 || ap->a_aclp->acl_cnt > MAX_ACL_ENTRIES)
6664                 return (EINVAL);
6665
6666         /*
6667          * With NFSv4 ACLs, chmod(2) may need to add additional entries,
6668          * splitting every entry into two and appending "canonical six"
6669          * entries at the end.  Don't allow for setting an ACL that would
6670          * cause chmod(2) to run out of ACL entries.
6671          */
6672         if (ap->a_aclp->acl_cnt * 2 + 6 > ACL_MAX_ENTRIES)
6673                 return (ENOSPC);
6674
6675         error = acl_nfs4_check(ap->a_aclp, ap->a_vp->v_type == VDIR);
6676         if (error != 0)
6677                 return (error);
6678
6679         vsecattr.vsa_mask = VSA_ACE;
6680         aclbsize = ap->a_aclp->acl_cnt * sizeof(ace_t);
6681         vsecattr.vsa_aclentp = kmem_alloc(aclbsize, KM_SLEEP);
6682         aaclp = vsecattr.vsa_aclentp;
6683         vsecattr.vsa_aclentsz = aclbsize;
6684
6685         aces_from_acl(vsecattr.vsa_aclentp, &vsecattr.vsa_aclcnt, ap->a_aclp);
6686         error = zfs_setsecattr(ap->a_vp, &vsecattr, 0, ap->a_cred, NULL);
6687         kmem_free(aaclp, aclbsize);
6688
6689         return (error);
6690 }
6691
6692 int
6693 zfs_freebsd_aclcheck(ap)
6694         struct vop_aclcheck_args /* {
6695                 struct vnode *vp;
6696                 acl_type_t type;
6697                 struct acl *aclp;
6698                 struct ucred *cred;
6699                 struct thread *td;
6700         } */ *ap;
6701 {
6702
6703         return (EOPNOTSUPP);
6704 }
6705
6706 struct vop_vector zfs_vnodeops;
6707 struct vop_vector zfs_fifoops;
6708 struct vop_vector zfs_shareops;
6709
6710 struct vop_vector zfs_vnodeops = {
6711         .vop_default =          &default_vnodeops,
6712         .vop_inactive =         zfs_freebsd_inactive,
6713         .vop_reclaim =          zfs_freebsd_reclaim,
6714         .vop_access =           zfs_freebsd_access,
6715 #ifdef FREEBSD_NAMECACHE
6716         .vop_lookup =           vfs_cache_lookup,
6717         .vop_cachedlookup =     zfs_freebsd_lookup,
6718 #else
6719         .vop_lookup =           zfs_freebsd_lookup,
6720 #endif
6721         .vop_getattr =          zfs_freebsd_getattr,
6722         .vop_setattr =          zfs_freebsd_setattr,
6723         .vop_create =           zfs_freebsd_create,
6724         .vop_mknod =            zfs_freebsd_create,
6725         .vop_mkdir =            zfs_freebsd_mkdir,
6726         .vop_readdir =          zfs_freebsd_readdir,
6727         .vop_fsync =            zfs_freebsd_fsync,
6728         .vop_open =             zfs_freebsd_open,
6729         .vop_close =            zfs_freebsd_close,
6730         .vop_rmdir =            zfs_freebsd_rmdir,
6731         .vop_ioctl =            zfs_freebsd_ioctl,
6732         .vop_link =             zfs_freebsd_link,
6733         .vop_symlink =          zfs_freebsd_symlink,
6734         .vop_readlink =         zfs_freebsd_readlink,
6735         .vop_read =             zfs_freebsd_read,
6736         .vop_write =            zfs_freebsd_write,
6737         .vop_remove =           zfs_freebsd_remove,
6738         .vop_rename =           zfs_freebsd_rename,
6739         .vop_pathconf =         zfs_freebsd_pathconf,
6740         .vop_bmap =             VOP_EOPNOTSUPP,
6741         .vop_fid =              zfs_freebsd_fid,
6742         .vop_getextattr =       zfs_getextattr,
6743         .vop_deleteextattr =    zfs_deleteextattr,
6744         .vop_setextattr =       zfs_setextattr,
6745         .vop_listextattr =      zfs_listextattr,
6746         .vop_getacl =           zfs_freebsd_getacl,
6747         .vop_setacl =           zfs_freebsd_setacl,
6748         .vop_aclcheck =         zfs_freebsd_aclcheck,
6749         .vop_getpages =         zfs_freebsd_getpages,
6750 };
6751
6752 struct vop_vector zfs_fifoops = {
6753         .vop_default =          &fifo_specops,
6754         .vop_fsync =            zfs_freebsd_fsync,
6755         .vop_access =           zfs_freebsd_access,
6756         .vop_getattr =          zfs_freebsd_getattr,
6757         .vop_inactive =         zfs_freebsd_inactive,
6758         .vop_read =             VOP_PANIC,
6759         .vop_reclaim =          zfs_freebsd_reclaim,
6760         .vop_setattr =          zfs_freebsd_setattr,
6761         .vop_write =            VOP_PANIC,
6762         .vop_pathconf =         zfs_freebsd_fifo_pathconf,
6763         .vop_fid =              zfs_freebsd_fid,
6764         .vop_getacl =           zfs_freebsd_getacl,
6765         .vop_setacl =           zfs_freebsd_setacl,
6766         .vop_aclcheck =         zfs_freebsd_aclcheck,
6767 };
6768
6769 /*
6770  * special share hidden files vnode operations template
6771  */
6772 struct vop_vector zfs_shareops = {
6773         .vop_default =          &default_vnodeops,
6774         .vop_access =           zfs_freebsd_access,
6775         .vop_inactive =         zfs_freebsd_inactive,
6776         .vop_reclaim =          zfs_freebsd_reclaim,
6777         .vop_fid =              zfs_freebsd_fid,
6778         .vop_pathconf =         zfs_freebsd_pathconf,
6779 };