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