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