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