]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/os/freebsd/zfs/zfs_vnops_os.c
Extending FreeBSD UIO Struct
[FreeBSD/FreeBSD.git] / module / os / freebsd / zfs / zfs_vnops_os.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 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2015 by Delphix. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  * Copyright 2017 Nexenta Systems, Inc.
27  */
28
29 /* Portions Copyright 2007 Jeremy Teo */
30 /* Portions Copyright 2010 Robert Milkowski */
31
32
33 #include <sys/types.h>
34 #include <sys/param.h>
35 #include <sys/time.h>
36 #include <sys/systm.h>
37 #include <sys/sysmacros.h>
38 #include <sys/resource.h>
39 #include <sys/vfs.h>
40 #include <sys/endian.h>
41 #include <sys/vm.h>
42 #include <sys/vnode.h>
43 #if __FreeBSD_version >= 1300102
44 #include <sys/smr.h>
45 #endif
46 #include <sys/dirent.h>
47 #include <sys/file.h>
48 #include <sys/stat.h>
49 #include <sys/kmem.h>
50 #include <sys/taskq.h>
51 #include <sys/uio.h>
52 #include <sys/atomic.h>
53 #include <sys/namei.h>
54 #include <sys/mman.h>
55 #include <sys/cmn_err.h>
56 #include <sys/kdb.h>
57 #include <sys/sysproto.h>
58 #include <sys/errno.h>
59 #include <sys/unistd.h>
60 #include <sys/zfs_dir.h>
61 #include <sys/zfs_ioctl.h>
62 #include <sys/fs/zfs.h>
63 #include <sys/dmu.h>
64 #include <sys/dmu_objset.h>
65 #include <sys/spa.h>
66 #include <sys/txg.h>
67 #include <sys/dbuf.h>
68 #include <sys/zap.h>
69 #include <sys/sa.h>
70 #include <sys/policy.h>
71 #include <sys/sunddi.h>
72 #include <sys/filio.h>
73 #include <sys/sid.h>
74 #include <sys/zfs_ctldir.h>
75 #include <sys/zfs_fuid.h>
76 #include <sys/zfs_quota.h>
77 #include <sys/zfs_sa.h>
78 #include <sys/zfs_rlock.h>
79 #include <sys/extdirent.h>
80 #include <sys/bio.h>
81 #include <sys/buf.h>
82 #include <sys/sched.h>
83 #include <sys/acl.h>
84 #include <sys/vmmeter.h>
85 #include <vm/vm_param.h>
86 #include <sys/zil.h>
87 #include <sys/zfs_vnops.h>
88
89 #include <vm/vm_object.h>
90
91 #include <sys/extattr.h>
92 #include <sys/priv.h>
93
94 #ifndef VN_OPEN_INVFS
95 #define VN_OPEN_INVFS   0x0
96 #endif
97
98 VFS_SMR_DECLARE;
99
100 #if __FreeBSD_version >= 1300047
101 #define vm_page_wire_lock(pp)
102 #define vm_page_wire_unlock(pp)
103 #else
104 #define vm_page_wire_lock(pp) vm_page_lock(pp)
105 #define vm_page_wire_unlock(pp) vm_page_unlock(pp)
106 #endif
107
108 #ifdef DEBUG_VFS_LOCKS
109 #define VNCHECKREF(vp)                            \
110         VNASSERT((vp)->v_holdcnt > 0 && (vp)->v_usecount > 0, vp,       \
111             ("%s: wrong ref counts", __func__));
112 #else
113 #define VNCHECKREF(vp)
114 #endif
115
116 /*
117  * Programming rules.
118  *
119  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
120  * properly lock its in-core state, create a DMU transaction, do the work,
121  * record this work in the intent log (ZIL), commit the DMU transaction,
122  * and wait for the intent log to commit if it is a synchronous operation.
123  * Moreover, the vnode ops must work in both normal and log replay context.
124  * The ordering of events is important to avoid deadlocks and references
125  * to freed memory.  The example below illustrates the following Big Rules:
126  *
127  *  (1) A check must be made in each zfs thread for a mounted file system.
128  *      This is done avoiding races using ZFS_ENTER(zfsvfs).
129  *      A ZFS_EXIT(zfsvfs) is needed before all returns.  Any znodes
130  *      must be checked with ZFS_VERIFY_ZP(zp).  Both of these macros
131  *      can return EIO from the calling function.
132  *
133  *  (2) VN_RELE() should always be the last thing except for zil_commit()
134  *      (if necessary) and ZFS_EXIT(). This is for 3 reasons:
135  *      First, if it's the last reference, the vnode/znode
136  *      can be freed, so the zp may point to freed memory.  Second, the last
137  *      reference will call zfs_zinactive(), which may induce a lot of work --
138  *      pushing cached pages (which acquires range locks) and syncing out
139  *      cached atime changes.  Third, zfs_zinactive() may require a new tx,
140  *      which could deadlock the system if you were already holding one.
141  *      If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
142  *
143  *  (3) All range locks must be grabbed before calling dmu_tx_assign(),
144  *      as they can span dmu_tx_assign() calls.
145  *
146  *  (4) If ZPL locks are held, pass TXG_NOWAIT as the second argument to
147  *      dmu_tx_assign().  This is critical because we don't want to block
148  *      while holding locks.
149  *
150  *      If no ZPL locks are held (aside from ZFS_ENTER()), use TXG_WAIT.  This
151  *      reduces lock contention and CPU usage when we must wait (note that if
152  *      throughput is constrained by the storage, nearly every transaction
153  *      must wait).
154  *
155  *      Note, in particular, that if a lock is sometimes acquired before
156  *      the tx assigns, and sometimes after (e.g. z_lock), then failing
157  *      to use a non-blocking assign can deadlock the system.  The scenario:
158  *
159  *      Thread A has grabbed a lock before calling dmu_tx_assign().
160  *      Thread B is in an already-assigned tx, and blocks for this lock.
161  *      Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
162  *      forever, because the previous txg can't quiesce until B's tx commits.
163  *
164  *      If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
165  *      then drop all locks, call dmu_tx_wait(), and try again.  On subsequent
166  *      calls to dmu_tx_assign(), pass TXG_NOTHROTTLE in addition to TXG_NOWAIT,
167  *      to indicate that this operation has already called dmu_tx_wait().
168  *      This will ensure that we don't retry forever, waiting a short bit
169  *      each time.
170  *
171  *  (5) If the operation succeeded, generate the intent log entry for it
172  *      before dropping locks.  This ensures that the ordering of events
173  *      in the intent log matches the order in which they actually occurred.
174  *      During ZIL replay the zfs_log_* functions will update the sequence
175  *      number to indicate the zil transaction has replayed.
176  *
177  *  (6) At the end of each vnode op, the DMU tx must always commit,
178  *      regardless of whether there were any errors.
179  *
180  *  (7) After dropping all locks, invoke zil_commit(zilog, foid)
181  *      to ensure that synchronous semantics are provided when necessary.
182  *
183  * In general, this is how things should be ordered in each vnode op:
184  *
185  *      ZFS_ENTER(zfsvfs);              // exit if unmounted
186  * top:
187  *      zfs_dirent_lookup(&dl, ...)     // lock directory entry (may VN_HOLD())
188  *      rw_enter(...);                  // grab any other locks you need
189  *      tx = dmu_tx_create(...);        // get DMU tx
190  *      dmu_tx_hold_*();                // hold each object you might modify
191  *      error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
192  *      if (error) {
193  *              rw_exit(...);           // drop locks
194  *              zfs_dirent_unlock(dl);  // unlock directory entry
195  *              VN_RELE(...);           // release held vnodes
196  *              if (error == ERESTART) {
197  *                      waited = B_TRUE;
198  *                      dmu_tx_wait(tx);
199  *                      dmu_tx_abort(tx);
200  *                      goto top;
201  *              }
202  *              dmu_tx_abort(tx);       // abort DMU tx
203  *              ZFS_EXIT(zfsvfs);       // finished in zfs
204  *              return (error);         // really out of space
205  *      }
206  *      error = do_real_work();         // do whatever this VOP does
207  *      if (error == 0)
208  *              zfs_log_*(...);         // on success, make ZIL entry
209  *      dmu_tx_commit(tx);              // commit DMU tx -- error or not
210  *      rw_exit(...);                   // drop locks
211  *      zfs_dirent_unlock(dl);          // unlock directory entry
212  *      VN_RELE(...);                   // release held vnodes
213  *      zil_commit(zilog, foid);        // synchronous when necessary
214  *      ZFS_EXIT(zfsvfs);               // finished in zfs
215  *      return (error);                 // done, report error
216  */
217
218 /* ARGSUSED */
219 static int
220 zfs_open(vnode_t **vpp, int flag, cred_t *cr)
221 {
222         znode_t *zp = VTOZ(*vpp);
223         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
224
225         ZFS_ENTER(zfsvfs);
226         ZFS_VERIFY_ZP(zp);
227
228         if ((flag & FWRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
229             ((flag & FAPPEND) == 0)) {
230                 ZFS_EXIT(zfsvfs);
231                 return (SET_ERROR(EPERM));
232         }
233
234         if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
235             ZTOV(zp)->v_type == VREG &&
236             !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0) {
237                 if (fs_vscan(*vpp, cr, 0) != 0) {
238                         ZFS_EXIT(zfsvfs);
239                         return (SET_ERROR(EACCES));
240                 }
241         }
242
243         /* Keep a count of the synchronous opens in the znode */
244         if (flag & (FSYNC | FDSYNC))
245                 atomic_inc_32(&zp->z_sync_cnt);
246
247         ZFS_EXIT(zfsvfs);
248         return (0);
249 }
250
251 /* ARGSUSED */
252 static int
253 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr)
254 {
255         znode_t *zp = VTOZ(vp);
256         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
257
258         ZFS_ENTER(zfsvfs);
259         ZFS_VERIFY_ZP(zp);
260
261         /* Decrement the synchronous opens in the znode */
262         if ((flag & (FSYNC | FDSYNC)) && (count == 1))
263                 atomic_dec_32(&zp->z_sync_cnt);
264
265         if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
266             ZTOV(zp)->v_type == VREG &&
267             !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0)
268                 VERIFY(fs_vscan(vp, cr, 1) == 0);
269
270         ZFS_EXIT(zfsvfs);
271         return (0);
272 }
273
274 /* ARGSUSED */
275 static int
276 zfs_ioctl(vnode_t *vp, ulong_t com, intptr_t data, int flag, cred_t *cred,
277     int *rvalp)
278 {
279         loff_t off;
280         int error;
281
282         switch (com) {
283         case _FIOFFS:
284         {
285                 return (0);
286
287                 /*
288                  * The following two ioctls are used by bfu.  Faking out,
289                  * necessary to avoid bfu errors.
290                  */
291         }
292         case _FIOGDIO:
293         case _FIOSDIO:
294         {
295                 return (0);
296         }
297
298         case F_SEEK_DATA:
299         case F_SEEK_HOLE:
300         {
301                 off = *(offset_t *)data;
302                 /* offset parameter is in/out */
303                 error = zfs_holey(VTOZ(vp), com, &off);
304                 if (error)
305                         return (error);
306                 *(offset_t *)data = off;
307                 return (0);
308         }
309         }
310         return (SET_ERROR(ENOTTY));
311 }
312
313 static vm_page_t
314 page_busy(vnode_t *vp, int64_t start, int64_t off, int64_t nbytes)
315 {
316         vm_object_t obj;
317         vm_page_t pp;
318         int64_t end;
319
320         /*
321          * At present vm_page_clear_dirty extends the cleared range to DEV_BSIZE
322          * aligned boundaries, if the range is not aligned.  As a result a
323          * DEV_BSIZE subrange with partially dirty data may get marked as clean.
324          * It may happen that all DEV_BSIZE subranges are marked clean and thus
325          * the whole page would be considered clean despite have some
326          * dirty data.
327          * For this reason we should shrink the range to DEV_BSIZE aligned
328          * boundaries before calling vm_page_clear_dirty.
329          */
330         end = rounddown2(off + nbytes, DEV_BSIZE);
331         off = roundup2(off, DEV_BSIZE);
332         nbytes = end - off;
333
334         obj = vp->v_object;
335         zfs_vmobject_assert_wlocked_12(obj);
336 #if __FreeBSD_version < 1300050
337         for (;;) {
338                 if ((pp = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
339                     pp->valid) {
340                         if (vm_page_xbusied(pp)) {
341                                 /*
342                                  * Reference the page before unlocking and
343                                  * sleeping so that the page daemon is less
344                                  * likely to reclaim it.
345                                  */
346                                 vm_page_reference(pp);
347                                 vm_page_lock(pp);
348                                 zfs_vmobject_wunlock(obj);
349                                 vm_page_busy_sleep(pp, "zfsmwb", true);
350                                 zfs_vmobject_wlock(obj);
351                                 continue;
352                         }
353                         vm_page_sbusy(pp);
354                 } else if (pp != NULL) {
355                         ASSERT(!pp->valid);
356                         pp = NULL;
357                 }
358                 if (pp != NULL) {
359                         ASSERT3U(pp->valid, ==, VM_PAGE_BITS_ALL);
360                         vm_object_pip_add(obj, 1);
361                         pmap_remove_write(pp);
362                         if (nbytes != 0)
363                                 vm_page_clear_dirty(pp, off, nbytes);
364                 }
365                 break;
366         }
367 #else
368         vm_page_grab_valid_unlocked(&pp, obj, OFF_TO_IDX(start),
369             VM_ALLOC_NOCREAT | VM_ALLOC_SBUSY | VM_ALLOC_NORMAL |
370             VM_ALLOC_IGN_SBUSY);
371         if (pp != NULL) {
372                 ASSERT3U(pp->valid, ==, VM_PAGE_BITS_ALL);
373                 vm_object_pip_add(obj, 1);
374                 pmap_remove_write(pp);
375                 if (nbytes != 0)
376                         vm_page_clear_dirty(pp, off, nbytes);
377         }
378 #endif
379         return (pp);
380 }
381
382 static void
383 page_unbusy(vm_page_t pp)
384 {
385
386         vm_page_sunbusy(pp);
387 #if __FreeBSD_version >= 1300041
388         vm_object_pip_wakeup(pp->object);
389 #else
390         vm_object_pip_subtract(pp->object, 1);
391 #endif
392 }
393
394 #if __FreeBSD_version > 1300051
395 static vm_page_t
396 page_hold(vnode_t *vp, int64_t start)
397 {
398         vm_object_t obj;
399         vm_page_t m;
400
401         obj = vp->v_object;
402         vm_page_grab_valid_unlocked(&m, obj, OFF_TO_IDX(start),
403             VM_ALLOC_NOCREAT | VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY |
404             VM_ALLOC_NOBUSY);
405         return (m);
406 }
407 #else
408 static vm_page_t
409 page_hold(vnode_t *vp, int64_t start)
410 {
411         vm_object_t obj;
412         vm_page_t pp;
413
414         obj = vp->v_object;
415         zfs_vmobject_assert_wlocked(obj);
416
417         for (;;) {
418                 if ((pp = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
419                     pp->valid) {
420                         if (vm_page_xbusied(pp)) {
421                                 /*
422                                  * Reference the page before unlocking and
423                                  * sleeping so that the page daemon is less
424                                  * likely to reclaim it.
425                                  */
426                                 vm_page_reference(pp);
427                                 vm_page_lock(pp);
428                                 zfs_vmobject_wunlock(obj);
429                                 vm_page_busy_sleep(pp, "zfsmwb", true);
430                                 zfs_vmobject_wlock(obj);
431                                 continue;
432                         }
433
434                         ASSERT3U(pp->valid, ==, VM_PAGE_BITS_ALL);
435                         vm_page_wire_lock(pp);
436                         vm_page_hold(pp);
437                         vm_page_wire_unlock(pp);
438
439                 } else
440                         pp = NULL;
441                 break;
442         }
443         return (pp);
444 }
445 #endif
446
447 static void
448 page_unhold(vm_page_t pp)
449 {
450
451         vm_page_wire_lock(pp);
452 #if __FreeBSD_version >= 1300035
453         vm_page_unwire(pp, PQ_ACTIVE);
454 #else
455         vm_page_unhold(pp);
456 #endif
457         vm_page_wire_unlock(pp);
458 }
459
460 /*
461  * When a file is memory mapped, we must keep the IO data synchronized
462  * between the DMU cache and the memory mapped pages.  What this means:
463  *
464  * On Write:    If we find a memory mapped page, we write to *both*
465  *              the page and the dmu buffer.
466  */
467 void
468 update_pages(znode_t *zp, int64_t start, int len, objset_t *os)
469 {
470         vm_object_t obj;
471         struct sf_buf *sf;
472         vnode_t *vp = ZTOV(zp);
473         caddr_t va;
474         int off;
475
476         ASSERT(vp->v_mount != NULL);
477         obj = vp->v_object;
478         ASSERT(obj != NULL);
479
480         off = start & PAGEOFFSET;
481         zfs_vmobject_wlock_12(obj);
482 #if __FreeBSD_version >= 1300041
483         vm_object_pip_add(obj, 1);
484 #endif
485         for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
486                 vm_page_t pp;
487                 int nbytes = imin(PAGESIZE - off, len);
488
489                 if ((pp = page_busy(vp, start, off, nbytes)) != NULL) {
490                         zfs_vmobject_wunlock_12(obj);
491
492                         va = zfs_map_page(pp, &sf);
493                         (void) dmu_read(os, zp->z_id, start + off, nbytes,
494                             va + off, DMU_READ_PREFETCH);
495                         zfs_unmap_page(sf);
496
497                         zfs_vmobject_wlock_12(obj);
498                         page_unbusy(pp);
499                 }
500                 len -= nbytes;
501                 off = 0;
502         }
503 #if __FreeBSD_version >= 1300041
504         vm_object_pip_wakeup(obj);
505 #else
506         vm_object_pip_wakeupn(obj, 0);
507 #endif
508         zfs_vmobject_wunlock_12(obj);
509 }
510
511 /*
512  * Read with UIO_NOCOPY flag means that sendfile(2) requests
513  * ZFS to populate a range of page cache pages with data.
514  *
515  * NOTE: this function could be optimized to pre-allocate
516  * all pages in advance, drain exclusive busy on all of them,
517  * map them into contiguous KVA region and populate them
518  * in one single dmu_read() call.
519  */
520 int
521 mappedread_sf(znode_t *zp, int nbytes, zfs_uio_t *uio)
522 {
523         vnode_t *vp = ZTOV(zp);
524         objset_t *os = zp->z_zfsvfs->z_os;
525         struct sf_buf *sf;
526         vm_object_t obj;
527         vm_page_t pp;
528         int64_t start;
529         caddr_t va;
530         int len = nbytes;
531         int error = 0;
532
533         ASSERT(zfs_uio_segflg(uio) == UIO_NOCOPY);
534         ASSERT(vp->v_mount != NULL);
535         obj = vp->v_object;
536         ASSERT(obj != NULL);
537         ASSERT((zfs_uio_offset(uio) & PAGEOFFSET) == 0);
538
539         zfs_vmobject_wlock_12(obj);
540         for (start = zfs_uio_offset(uio); len > 0; start += PAGESIZE) {
541                 int bytes = MIN(PAGESIZE, len);
542
543                 pp = vm_page_grab_unlocked(obj, OFF_TO_IDX(start),
544                     VM_ALLOC_SBUSY | VM_ALLOC_NORMAL | VM_ALLOC_IGN_SBUSY);
545                 if (vm_page_none_valid(pp)) {
546                         zfs_vmobject_wunlock_12(obj);
547                         va = zfs_map_page(pp, &sf);
548                         error = dmu_read(os, zp->z_id, start, bytes, va,
549                             DMU_READ_PREFETCH);
550                         if (bytes != PAGESIZE && error == 0)
551                                 bzero(va + bytes, PAGESIZE - bytes);
552                         zfs_unmap_page(sf);
553                         zfs_vmobject_wlock_12(obj);
554 #if  __FreeBSD_version >= 1300081
555                         if (error == 0) {
556                                 vm_page_valid(pp);
557                                 vm_page_activate(pp);
558                                 vm_page_do_sunbusy(pp);
559                         } else {
560                                 zfs_vmobject_wlock(obj);
561                                 if (!vm_page_wired(pp) && pp->valid == 0 &&
562                                     vm_page_busy_tryupgrade(pp))
563                                         vm_page_free(pp);
564                                 else
565                                         vm_page_sunbusy(pp);
566                                 zfs_vmobject_wunlock(obj);
567                         }
568 #else
569                         vm_page_do_sunbusy(pp);
570                         vm_page_lock(pp);
571                         if (error) {
572                                 if (pp->wire_count == 0 && pp->valid == 0 &&
573                                     !vm_page_busied(pp))
574                                         vm_page_free(pp);
575                         } else {
576                                 pp->valid = VM_PAGE_BITS_ALL;
577                                 vm_page_activate(pp);
578                         }
579                         vm_page_unlock(pp);
580 #endif
581                 } else {
582                         ASSERT3U(pp->valid, ==, VM_PAGE_BITS_ALL);
583                         vm_page_do_sunbusy(pp);
584                 }
585                 if (error)
586                         break;
587                 zfs_uio_advance(uio, bytes);
588                 len -= bytes;
589         }
590         zfs_vmobject_wunlock_12(obj);
591         return (error);
592 }
593
594 /*
595  * When a file is memory mapped, we must keep the IO data synchronized
596  * between the DMU cache and the memory mapped pages.  What this means:
597  *
598  * On Read:     We "read" preferentially from memory mapped pages,
599  *              else we default from the dmu buffer.
600  *
601  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
602  *       the file is memory mapped.
603  */
604 int
605 mappedread(znode_t *zp, int nbytes, zfs_uio_t *uio)
606 {
607         vnode_t *vp = ZTOV(zp);
608         vm_object_t obj;
609         int64_t start;
610         int len = nbytes;
611         int off;
612         int error = 0;
613
614         ASSERT(vp->v_mount != NULL);
615         obj = vp->v_object;
616         ASSERT(obj != NULL);
617
618         start = zfs_uio_offset(uio);
619         off = start & PAGEOFFSET;
620         zfs_vmobject_wlock_12(obj);
621         for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
622                 vm_page_t pp;
623                 uint64_t bytes = MIN(PAGESIZE - off, len);
624
625                 if ((pp = page_hold(vp, start))) {
626                         struct sf_buf *sf;
627                         caddr_t va;
628
629                         zfs_vmobject_wunlock_12(obj);
630                         va = zfs_map_page(pp, &sf);
631                         error = vn_io_fault_uiomove(va + off, bytes,
632                             GET_UIO_STRUCT(uio));
633                         zfs_unmap_page(sf);
634                         zfs_vmobject_wlock_12(obj);
635                         page_unhold(pp);
636                 } else {
637                         zfs_vmobject_wunlock_12(obj);
638                         error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
639                             uio, bytes);
640                         zfs_vmobject_wlock_12(obj);
641                 }
642                 len -= bytes;
643                 off = 0;
644                 if (error)
645                         break;
646         }
647         zfs_vmobject_wunlock_12(obj);
648         return (error);
649 }
650
651 int
652 zfs_write_simple(znode_t *zp, const void *data, size_t len,
653     loff_t pos, size_t *presid)
654 {
655         int error = 0;
656         ssize_t resid;
657
658         error = vn_rdwr(UIO_WRITE, ZTOV(zp), __DECONST(void *, data), len, pos,
659             UIO_SYSSPACE, IO_SYNC, kcred, NOCRED, &resid, curthread);
660
661         if (error) {
662                 return (SET_ERROR(error));
663         } else if (presid == NULL) {
664                 if (resid != 0) {
665                         error = SET_ERROR(EIO);
666                 }
667         } else {
668                 *presid = resid;
669         }
670         return (error);
671 }
672
673 void
674 zfs_zrele_async(znode_t *zp)
675 {
676         vnode_t *vp = ZTOV(zp);
677         objset_t *os = ITOZSB(vp)->z_os;
678
679         VN_RELE_ASYNC(vp, dsl_pool_zrele_taskq(dmu_objset_pool(os)));
680 }
681
682 static int
683 zfs_dd_callback(struct mount *mp, void *arg, int lkflags, struct vnode **vpp)
684 {
685         int error;
686
687         *vpp = arg;
688         error = vn_lock(*vpp, lkflags);
689         if (error != 0)
690                 vrele(*vpp);
691         return (error);
692 }
693
694 static int
695 zfs_lookup_lock(vnode_t *dvp, vnode_t *vp, const char *name, int lkflags)
696 {
697         znode_t *zdp = VTOZ(dvp);
698         zfsvfs_t *zfsvfs __unused = zdp->z_zfsvfs;
699         int error;
700         int ltype;
701
702         if (zfsvfs->z_replay == B_FALSE)
703                 ASSERT_VOP_LOCKED(dvp, __func__);
704 #ifdef DIAGNOSTIC
705         if ((zdp->z_pflags & ZFS_XATTR) == 0)
706                 VERIFY(!RRM_LOCK_HELD(&zfsvfs->z_teardown_lock));
707 #endif
708
709         if (name[0] == 0 || (name[0] == '.' && name[1] == 0)) {
710                 ASSERT3P(dvp, ==, vp);
711                 vref(dvp);
712                 ltype = lkflags & LK_TYPE_MASK;
713                 if (ltype != VOP_ISLOCKED(dvp)) {
714                         if (ltype == LK_EXCLUSIVE)
715                                 vn_lock(dvp, LK_UPGRADE | LK_RETRY);
716                         else /* if (ltype == LK_SHARED) */
717                                 vn_lock(dvp, LK_DOWNGRADE | LK_RETRY);
718
719                         /*
720                          * Relock for the "." case could leave us with
721                          * reclaimed vnode.
722                          */
723                         if (VN_IS_DOOMED(dvp)) {
724                                 vrele(dvp);
725                                 return (SET_ERROR(ENOENT));
726                         }
727                 }
728                 return (0);
729         } else if (name[0] == '.' && name[1] == '.' && name[2] == 0) {
730                 /*
731                  * Note that in this case, dvp is the child vnode, and we
732                  * are looking up the parent vnode - exactly reverse from
733                  * normal operation.  Unlocking dvp requires some rather
734                  * tricky unlock/relock dance to prevent mp from being freed;
735                  * use vn_vget_ino_gen() which takes care of all that.
736                  *
737                  * XXX Note that there is a time window when both vnodes are
738                  * unlocked.  It is possible, although highly unlikely, that
739                  * during that window the parent-child relationship between
740                  * the vnodes may change, for example, get reversed.
741                  * In that case we would have a wrong lock order for the vnodes.
742                  * All other filesystems seem to ignore this problem, so we
743                  * do the same here.
744                  * A potential solution could be implemented as follows:
745                  * - using LK_NOWAIT when locking the second vnode and retrying
746                  *   if necessary
747                  * - checking that the parent-child relationship still holds
748                  *   after locking both vnodes and retrying if it doesn't
749                  */
750                 error = vn_vget_ino_gen(dvp, zfs_dd_callback, vp, lkflags, &vp);
751                 return (error);
752         } else {
753                 error = vn_lock(vp, lkflags);
754                 if (error != 0)
755                         vrele(vp);
756                 return (error);
757         }
758 }
759
760 /*
761  * Lookup an entry in a directory, or an extended attribute directory.
762  * If it exists, return a held vnode reference for it.
763  *
764  *      IN:     dvp     - vnode of directory to search.
765  *              nm      - name of entry to lookup.
766  *              pnp     - full pathname to lookup [UNUSED].
767  *              flags   - LOOKUP_XATTR set if looking for an attribute.
768  *              rdir    - root directory vnode [UNUSED].
769  *              cr      - credentials of caller.
770  *              ct      - caller context
771  *
772  *      OUT:    vpp     - vnode of located entry, NULL if not found.
773  *
774  *      RETURN: 0 on success, error code on failure.
775  *
776  * Timestamps:
777  *      NA
778  */
779 /* ARGSUSED */
780 static int
781 zfs_lookup(vnode_t *dvp, const char *nm, vnode_t **vpp,
782     struct componentname *cnp, int nameiop, cred_t *cr, kthread_t *td,
783     int flags, boolean_t cached)
784 {
785         znode_t *zdp = VTOZ(dvp);
786         znode_t *zp;
787         zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
788         int     error = 0;
789
790         /*
791          * Fast path lookup, however we must skip DNLC lookup
792          * for case folding or normalizing lookups because the
793          * DNLC code only stores the passed in name.  This means
794          * creating 'a' and removing 'A' on a case insensitive
795          * file system would work, but DNLC still thinks 'a'
796          * exists and won't let you create it again on the next
797          * pass through fast path.
798          */
799         if (!(flags & LOOKUP_XATTR)) {
800                 if (dvp->v_type != VDIR) {
801                         return (SET_ERROR(ENOTDIR));
802                 } else if (zdp->z_sa_hdl == NULL) {
803                         return (SET_ERROR(EIO));
804                 }
805         }
806
807         DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp,
808             const char *, nm);
809
810         ZFS_ENTER(zfsvfs);
811         ZFS_VERIFY_ZP(zdp);
812
813         *vpp = NULL;
814
815         if (flags & LOOKUP_XATTR) {
816                 /*
817                  * If the xattr property is off, refuse the lookup request.
818                  */
819                 if (!(zfsvfs->z_flags & ZSB_XATTR)) {
820                         ZFS_EXIT(zfsvfs);
821                         return (SET_ERROR(EOPNOTSUPP));
822                 }
823
824                 /*
825                  * We don't allow recursive attributes..
826                  * Maybe someday we will.
827                  */
828                 if (zdp->z_pflags & ZFS_XATTR) {
829                         ZFS_EXIT(zfsvfs);
830                         return (SET_ERROR(EINVAL));
831                 }
832
833                 if ((error = zfs_get_xattrdir(VTOZ(dvp), &zp, cr, flags))) {
834                         ZFS_EXIT(zfsvfs);
835                         return (error);
836                 }
837                 *vpp = ZTOV(zp);
838
839                 /*
840                  * Do we have permission to get into attribute directory?
841                  */
842                 error = zfs_zaccess(zp, ACE_EXECUTE, 0, B_FALSE, cr);
843                 if (error) {
844                         vrele(ZTOV(zp));
845                 }
846
847                 ZFS_EXIT(zfsvfs);
848                 return (error);
849         }
850
851         /*
852          * Check accessibility of directory if we're not coming in via
853          * VOP_CACHEDLOOKUP.
854          */
855         if (!cached) {
856 #ifdef NOEXECCHECK
857                 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
858                         cnp->cn_flags &= ~NOEXECCHECK;
859                 } else
860 #endif
861                 if ((error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr))) {
862                         ZFS_EXIT(zfsvfs);
863                         return (error);
864                 }
865         }
866
867         if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
868             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
869                 ZFS_EXIT(zfsvfs);
870                 return (SET_ERROR(EILSEQ));
871         }
872
873
874         /*
875          * First handle the special cases.
876          */
877         if ((cnp->cn_flags & ISDOTDOT) != 0) {
878                 /*
879                  * If we are a snapshot mounted under .zfs, return
880                  * the vp for the snapshot directory.
881                  */
882                 if (zdp->z_id == zfsvfs->z_root && zfsvfs->z_parent != zfsvfs) {
883                         struct componentname cn;
884                         vnode_t *zfsctl_vp;
885                         int ltype;
886
887                         ZFS_EXIT(zfsvfs);
888                         ltype = VOP_ISLOCKED(dvp);
889                         VOP_UNLOCK1(dvp);
890                         error = zfsctl_root(zfsvfs->z_parent, LK_SHARED,
891                             &zfsctl_vp);
892                         if (error == 0) {
893                                 cn.cn_nameptr = "snapshot";
894                                 cn.cn_namelen = strlen(cn.cn_nameptr);
895                                 cn.cn_nameiop = cnp->cn_nameiop;
896                                 cn.cn_flags = cnp->cn_flags & ~ISDOTDOT;
897                                 cn.cn_lkflags = cnp->cn_lkflags;
898                                 error = VOP_LOOKUP(zfsctl_vp, vpp, &cn);
899                                 vput(zfsctl_vp);
900                         }
901                         vn_lock(dvp, ltype | LK_RETRY);
902                         return (error);
903                 }
904         }
905         if (zfs_has_ctldir(zdp) && strcmp(nm, ZFS_CTLDIR_NAME) == 0) {
906                 ZFS_EXIT(zfsvfs);
907                 if ((cnp->cn_flags & ISLASTCN) != 0 && nameiop != LOOKUP)
908                         return (SET_ERROR(ENOTSUP));
909                 error = zfsctl_root(zfsvfs, cnp->cn_lkflags, vpp);
910                 return (error);
911         }
912
913         /*
914          * The loop is retry the lookup if the parent-child relationship
915          * changes during the dot-dot locking complexities.
916          */
917         for (;;) {
918                 uint64_t parent;
919
920                 error = zfs_dirlook(zdp, nm, &zp);
921                 if (error == 0)
922                         *vpp = ZTOV(zp);
923
924                 ZFS_EXIT(zfsvfs);
925                 if (error != 0)
926                         break;
927
928                 error = zfs_lookup_lock(dvp, *vpp, nm, cnp->cn_lkflags);
929                 if (error != 0) {
930                         /*
931                          * If we've got a locking error, then the vnode
932                          * got reclaimed because of a force unmount.
933                          * We never enter doomed vnodes into the name cache.
934                          */
935                         *vpp = NULL;
936                         return (error);
937                 }
938
939                 if ((cnp->cn_flags & ISDOTDOT) == 0)
940                         break;
941
942                 ZFS_ENTER(zfsvfs);
943                 if (zdp->z_sa_hdl == NULL) {
944                         error = SET_ERROR(EIO);
945                 } else {
946                         error = sa_lookup(zdp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
947                             &parent, sizeof (parent));
948                 }
949                 if (error != 0) {
950                         ZFS_EXIT(zfsvfs);
951                         vput(ZTOV(zp));
952                         break;
953                 }
954                 if (zp->z_id == parent) {
955                         ZFS_EXIT(zfsvfs);
956                         break;
957                 }
958                 vput(ZTOV(zp));
959         }
960
961         if (error != 0)
962                 *vpp = NULL;
963
964         /* Translate errors and add SAVENAME when needed. */
965         if (cnp->cn_flags & ISLASTCN) {
966                 switch (nameiop) {
967                 case CREATE:
968                 case RENAME:
969                         if (error == ENOENT) {
970                                 error = EJUSTRETURN;
971                                 cnp->cn_flags |= SAVENAME;
972                                 break;
973                         }
974                         /* FALLTHROUGH */
975                 case DELETE:
976                         if (error == 0)
977                                 cnp->cn_flags |= SAVENAME;
978                         break;
979                 }
980         }
981
982         /* Insert name into cache (as non-existent) if appropriate. */
983         if (zfsvfs->z_use_namecache && !zfsvfs->z_replay &&
984             error == ENOENT && (cnp->cn_flags & MAKEENTRY) != 0)
985                 cache_enter(dvp, NULL, cnp);
986
987         /* Insert name into cache if appropriate. */
988         if (zfsvfs->z_use_namecache && !zfsvfs->z_replay &&
989             error == 0 && (cnp->cn_flags & MAKEENTRY)) {
990                 if (!(cnp->cn_flags & ISLASTCN) ||
991                     (nameiop != DELETE && nameiop != RENAME)) {
992                         cache_enter(dvp, *vpp, cnp);
993                 }
994         }
995
996         return (error);
997 }
998
999 /*
1000  * Attempt to create a new entry in a directory.  If the entry
1001  * already exists, truncate the file if permissible, else return
1002  * an error.  Return the vp of the created or trunc'd file.
1003  *
1004  *      IN:     dvp     - vnode of directory to put new file entry in.
1005  *              name    - name of new file entry.
1006  *              vap     - attributes of new file.
1007  *              excl    - flag indicating exclusive or non-exclusive mode.
1008  *              mode    - mode to open file with.
1009  *              cr      - credentials of caller.
1010  *              flag    - large file flag [UNUSED].
1011  *              ct      - caller context
1012  *              vsecp   - ACL to be set
1013  *
1014  *      OUT:    vpp     - vnode of created or trunc'd entry.
1015  *
1016  *      RETURN: 0 on success, error code on failure.
1017  *
1018  * Timestamps:
1019  *      dvp - ctime|mtime updated if new entry created
1020  *       vp - ctime|mtime always, atime if new
1021  */
1022
1023 /* ARGSUSED */
1024 int
1025 zfs_create(znode_t *dzp, const char *name, vattr_t *vap, int excl, int mode,
1026     znode_t **zpp, cred_t *cr, int flag, vsecattr_t *vsecp)
1027 {
1028         znode_t         *zp;
1029         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1030         zilog_t         *zilog;
1031         objset_t        *os;
1032         dmu_tx_t        *tx;
1033         int             error;
1034         ksid_t          *ksid;
1035         uid_t           uid;
1036         gid_t           gid = crgetgid(cr);
1037         uint64_t        projid = ZFS_DEFAULT_PROJID;
1038         zfs_acl_ids_t   acl_ids;
1039         boolean_t       fuid_dirtied;
1040         uint64_t        txtype;
1041 #ifdef DEBUG_VFS_LOCKS
1042         vnode_t *dvp = ZTOV(dzp);
1043 #endif
1044
1045         /*
1046          * If we have an ephemeral id, ACL, or XVATTR then
1047          * make sure file system is at proper version
1048          */
1049
1050         ksid = crgetsid(cr, KSID_OWNER);
1051         if (ksid)
1052                 uid = ksid_getid(ksid);
1053         else
1054                 uid = crgetuid(cr);
1055
1056         if (zfsvfs->z_use_fuids == B_FALSE &&
1057             (vsecp || (vap->va_mask & AT_XVATTR) ||
1058             IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1059                 return (SET_ERROR(EINVAL));
1060
1061         ZFS_ENTER(zfsvfs);
1062         ZFS_VERIFY_ZP(dzp);
1063         os = zfsvfs->z_os;
1064         zilog = zfsvfs->z_log;
1065
1066         if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1067             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1068                 ZFS_EXIT(zfsvfs);
1069                 return (SET_ERROR(EILSEQ));
1070         }
1071
1072         if (vap->va_mask & AT_XVATTR) {
1073                 if ((error = secpolicy_xvattr(ZTOV(dzp), (xvattr_t *)vap,
1074                     crgetuid(cr), cr, vap->va_type)) != 0) {
1075                         ZFS_EXIT(zfsvfs);
1076                         return (error);
1077                 }
1078         }
1079
1080         *zpp = NULL;
1081
1082         if ((vap->va_mode & S_ISVTX) && secpolicy_vnode_stky_modify(cr))
1083                 vap->va_mode &= ~S_ISVTX;
1084
1085         error = zfs_dirent_lookup(dzp, name, &zp, ZNEW);
1086         if (error) {
1087                 ZFS_EXIT(zfsvfs);
1088                 return (error);
1089         }
1090         ASSERT3P(zp, ==, NULL);
1091
1092         /*
1093          * Create a new file object and update the directory
1094          * to reference it.
1095          */
1096         if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr))) {
1097                 goto out;
1098         }
1099
1100         /*
1101          * We only support the creation of regular files in
1102          * extended attribute directories.
1103          */
1104
1105         if ((dzp->z_pflags & ZFS_XATTR) &&
1106             (vap->va_type != VREG)) {
1107                 error = SET_ERROR(EINVAL);
1108                 goto out;
1109         }
1110
1111         if ((error = zfs_acl_ids_create(dzp, 0, vap,
1112             cr, vsecp, &acl_ids)) != 0)
1113                 goto out;
1114
1115         if (S_ISREG(vap->va_mode) || S_ISDIR(vap->va_mode))
1116                 projid = zfs_inherit_projid(dzp);
1117         if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, projid)) {
1118                 zfs_acl_ids_free(&acl_ids);
1119                 error = SET_ERROR(EDQUOT);
1120                 goto out;
1121         }
1122
1123         getnewvnode_reserve_();
1124
1125         tx = dmu_tx_create(os);
1126
1127         dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1128             ZFS_SA_BASE_ATTR_SIZE);
1129
1130         fuid_dirtied = zfsvfs->z_fuid_dirty;
1131         if (fuid_dirtied)
1132                 zfs_fuid_txhold(zfsvfs, tx);
1133         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1134         dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
1135         if (!zfsvfs->z_use_sa &&
1136             acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1137                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1138                     0, acl_ids.z_aclp->z_acl_bytes);
1139         }
1140         error = dmu_tx_assign(tx, TXG_WAIT);
1141         if (error) {
1142                 zfs_acl_ids_free(&acl_ids);
1143                 dmu_tx_abort(tx);
1144                 getnewvnode_drop_reserve();
1145                 ZFS_EXIT(zfsvfs);
1146                 return (error);
1147         }
1148         zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1149         if (fuid_dirtied)
1150                 zfs_fuid_sync(zfsvfs, tx);
1151
1152         (void) zfs_link_create(dzp, name, zp, tx, ZNEW);
1153         txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1154         zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1155             vsecp, acl_ids.z_fuidp, vap);
1156         zfs_acl_ids_free(&acl_ids);
1157         dmu_tx_commit(tx);
1158
1159         getnewvnode_drop_reserve();
1160
1161 out:
1162         VNCHECKREF(dvp);
1163         if (error == 0) {
1164                 *zpp = zp;
1165         }
1166
1167         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1168                 zil_commit(zilog, 0);
1169
1170         ZFS_EXIT(zfsvfs);
1171         return (error);
1172 }
1173
1174 /*
1175  * Remove an entry from a directory.
1176  *
1177  *      IN:     dvp     - vnode of directory to remove entry from.
1178  *              name    - name of entry to remove.
1179  *              cr      - credentials of caller.
1180  *              ct      - caller context
1181  *              flags   - case flags
1182  *
1183  *      RETURN: 0 on success, error code on failure.
1184  *
1185  * Timestamps:
1186  *      dvp - ctime|mtime
1187  *       vp - ctime (if nlink > 0)
1188  */
1189
1190 /*ARGSUSED*/
1191 static int
1192 zfs_remove_(vnode_t *dvp, vnode_t *vp, const char *name, cred_t *cr)
1193 {
1194         znode_t         *dzp = VTOZ(dvp);
1195         znode_t         *zp;
1196         znode_t         *xzp;
1197         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1198         zilog_t         *zilog;
1199         uint64_t        xattr_obj;
1200         uint64_t        obj = 0;
1201         dmu_tx_t        *tx;
1202         boolean_t       unlinked;
1203         uint64_t        txtype;
1204         int             error;
1205
1206
1207         ZFS_ENTER(zfsvfs);
1208         ZFS_VERIFY_ZP(dzp);
1209         zp = VTOZ(vp);
1210         ZFS_VERIFY_ZP(zp);
1211         zilog = zfsvfs->z_log;
1212
1213         xattr_obj = 0;
1214         xzp = NULL;
1215
1216         if ((error = zfs_zaccess_delete(dzp, zp, cr))) {
1217                 goto out;
1218         }
1219
1220         /*
1221          * Need to use rmdir for removing directories.
1222          */
1223         if (vp->v_type == VDIR) {
1224                 error = SET_ERROR(EPERM);
1225                 goto out;
1226         }
1227
1228         vnevent_remove(vp, dvp, name, ct);
1229
1230         obj = zp->z_id;
1231
1232         /* are there any extended attributes? */
1233         error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1234             &xattr_obj, sizeof (xattr_obj));
1235         if (error == 0 && xattr_obj) {
1236                 error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1237                 ASSERT0(error);
1238         }
1239
1240         /*
1241          * We may delete the znode now, or we may put it in the unlinked set;
1242          * it depends on whether we're the last link, and on whether there are
1243          * other holds on the vnode.  So we dmu_tx_hold() the right things to
1244          * allow for either case.
1245          */
1246         tx = dmu_tx_create(zfsvfs->z_os);
1247         dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1248         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1249         zfs_sa_upgrade_txholds(tx, zp);
1250         zfs_sa_upgrade_txholds(tx, dzp);
1251
1252         if (xzp) {
1253                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1254                 dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1255         }
1256
1257         /* charge as an update -- would be nice not to charge at all */
1258         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1259
1260         /*
1261          * Mark this transaction as typically resulting in a net free of space
1262          */
1263         dmu_tx_mark_netfree(tx);
1264
1265         error = dmu_tx_assign(tx, TXG_WAIT);
1266         if (error) {
1267                 dmu_tx_abort(tx);
1268                 ZFS_EXIT(zfsvfs);
1269                 return (error);
1270         }
1271
1272         /*
1273          * Remove the directory entry.
1274          */
1275         error = zfs_link_destroy(dzp, name, zp, tx, ZEXISTS, &unlinked);
1276
1277         if (error) {
1278                 dmu_tx_commit(tx);
1279                 goto out;
1280         }
1281
1282         if (unlinked) {
1283                 zfs_unlinked_add(zp, tx);
1284                 vp->v_vflag |= VV_NOSYNC;
1285         }
1286         /* XXX check changes to linux vnops */
1287         txtype = TX_REMOVE;
1288         zfs_log_remove(zilog, tx, txtype, dzp, name, obj, unlinked);
1289
1290         dmu_tx_commit(tx);
1291 out:
1292
1293         if (xzp)
1294                 vrele(ZTOV(xzp));
1295
1296         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1297                 zil_commit(zilog, 0);
1298
1299
1300         ZFS_EXIT(zfsvfs);
1301         return (error);
1302 }
1303
1304
1305 static int
1306 zfs_lookup_internal(znode_t *dzp, const char *name, vnode_t **vpp,
1307     struct componentname *cnp, int nameiop)
1308 {
1309         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1310         int error;
1311
1312         cnp->cn_nameptr = __DECONST(char *, name);
1313         cnp->cn_namelen = strlen(name);
1314         cnp->cn_nameiop = nameiop;
1315         cnp->cn_flags = ISLASTCN | SAVENAME;
1316         cnp->cn_lkflags = LK_EXCLUSIVE | LK_RETRY;
1317         cnp->cn_cred = kcred;
1318         cnp->cn_thread = curthread;
1319
1320         if (zfsvfs->z_use_namecache && !zfsvfs->z_replay) {
1321                 struct vop_lookup_args a;
1322
1323                 a.a_gen.a_desc = &vop_lookup_desc;
1324                 a.a_dvp = ZTOV(dzp);
1325                 a.a_vpp = vpp;
1326                 a.a_cnp = cnp;
1327                 error = vfs_cache_lookup(&a);
1328         } else {
1329                 error = zfs_lookup(ZTOV(dzp), name, vpp, cnp, nameiop, kcred,
1330                     curthread, 0, B_FALSE);
1331         }
1332 #ifdef ZFS_DEBUG
1333         if (error) {
1334                 printf("got error %d on name %s on op %d\n", error, name,
1335                     nameiop);
1336                 kdb_backtrace();
1337         }
1338 #endif
1339         return (error);
1340 }
1341
1342 int
1343 zfs_remove(znode_t *dzp, const char *name, cred_t *cr, int flags)
1344 {
1345         vnode_t *vp;
1346         int error;
1347         struct componentname cn;
1348
1349         if ((error = zfs_lookup_internal(dzp, name, &vp, &cn, DELETE)))
1350                 return (error);
1351
1352         error = zfs_remove_(ZTOV(dzp), vp, name, cr);
1353         vput(vp);
1354         return (error);
1355 }
1356 /*
1357  * Create a new directory and insert it into dvp using the name
1358  * provided.  Return a pointer to the inserted directory.
1359  *
1360  *      IN:     dvp     - vnode of directory to add subdir to.
1361  *              dirname - name of new directory.
1362  *              vap     - attributes of new directory.
1363  *              cr      - credentials of caller.
1364  *              ct      - caller context
1365  *              flags   - case flags
1366  *              vsecp   - ACL to be set
1367  *
1368  *      OUT:    vpp     - vnode of created directory.
1369  *
1370  *      RETURN: 0 on success, error code on failure.
1371  *
1372  * Timestamps:
1373  *      dvp - ctime|mtime updated
1374  *       vp - ctime|mtime|atime updated
1375  */
1376 /*ARGSUSED*/
1377 int
1378 zfs_mkdir(znode_t *dzp, const char *dirname, vattr_t *vap, znode_t **zpp,
1379     cred_t *cr, int flags, vsecattr_t *vsecp)
1380 {
1381         znode_t         *zp;
1382         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1383         zilog_t         *zilog;
1384         uint64_t        txtype;
1385         dmu_tx_t        *tx;
1386         int             error;
1387         ksid_t          *ksid;
1388         uid_t           uid;
1389         gid_t           gid = crgetgid(cr);
1390         zfs_acl_ids_t   acl_ids;
1391         boolean_t       fuid_dirtied;
1392
1393         ASSERT(vap->va_type == VDIR);
1394
1395         /*
1396          * If we have an ephemeral id, ACL, or XVATTR then
1397          * make sure file system is at proper version
1398          */
1399
1400         ksid = crgetsid(cr, KSID_OWNER);
1401         if (ksid)
1402                 uid = ksid_getid(ksid);
1403         else
1404                 uid = crgetuid(cr);
1405         if (zfsvfs->z_use_fuids == B_FALSE &&
1406             ((vap->va_mask & AT_XVATTR) ||
1407             IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1408                 return (SET_ERROR(EINVAL));
1409
1410         ZFS_ENTER(zfsvfs);
1411         ZFS_VERIFY_ZP(dzp);
1412         zilog = zfsvfs->z_log;
1413
1414         if (dzp->z_pflags & ZFS_XATTR) {
1415                 ZFS_EXIT(zfsvfs);
1416                 return (SET_ERROR(EINVAL));
1417         }
1418
1419         if (zfsvfs->z_utf8 && u8_validate(dirname,
1420             strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1421                 ZFS_EXIT(zfsvfs);
1422                 return (SET_ERROR(EILSEQ));
1423         }
1424
1425         if (vap->va_mask & AT_XVATTR) {
1426                 if ((error = secpolicy_xvattr(ZTOV(dzp), (xvattr_t *)vap,
1427                     crgetuid(cr), cr, vap->va_type)) != 0) {
1428                         ZFS_EXIT(zfsvfs);
1429                         return (error);
1430                 }
1431         }
1432
1433         if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
1434             NULL, &acl_ids)) != 0) {
1435                 ZFS_EXIT(zfsvfs);
1436                 return (error);
1437         }
1438
1439         /*
1440          * First make sure the new directory doesn't exist.
1441          *
1442          * Existence is checked first to make sure we don't return
1443          * EACCES instead of EEXIST which can cause some applications
1444          * to fail.
1445          */
1446         *zpp = NULL;
1447
1448         if ((error = zfs_dirent_lookup(dzp, dirname, &zp, ZNEW))) {
1449                 zfs_acl_ids_free(&acl_ids);
1450                 ZFS_EXIT(zfsvfs);
1451                 return (error);
1452         }
1453         ASSERT3P(zp, ==, NULL);
1454
1455         if ((error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr))) {
1456                 zfs_acl_ids_free(&acl_ids);
1457                 ZFS_EXIT(zfsvfs);
1458                 return (error);
1459         }
1460
1461         if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, zfs_inherit_projid(dzp))) {
1462                 zfs_acl_ids_free(&acl_ids);
1463                 ZFS_EXIT(zfsvfs);
1464                 return (SET_ERROR(EDQUOT));
1465         }
1466
1467         /*
1468          * Add a new entry to the directory.
1469          */
1470         getnewvnode_reserve_();
1471         tx = dmu_tx_create(zfsvfs->z_os);
1472         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1473         dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1474         fuid_dirtied = zfsvfs->z_fuid_dirty;
1475         if (fuid_dirtied)
1476                 zfs_fuid_txhold(zfsvfs, tx);
1477         if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1478                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
1479                     acl_ids.z_aclp->z_acl_bytes);
1480         }
1481
1482         dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1483             ZFS_SA_BASE_ATTR_SIZE);
1484
1485         error = dmu_tx_assign(tx, TXG_WAIT);
1486         if (error) {
1487                 zfs_acl_ids_free(&acl_ids);
1488                 dmu_tx_abort(tx);
1489                 getnewvnode_drop_reserve();
1490                 ZFS_EXIT(zfsvfs);
1491                 return (error);
1492         }
1493
1494         /*
1495          * Create new node.
1496          */
1497         zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1498
1499         if (fuid_dirtied)
1500                 zfs_fuid_sync(zfsvfs, tx);
1501
1502         /*
1503          * Now put new name in parent dir.
1504          */
1505         (void) zfs_link_create(dzp, dirname, zp, tx, ZNEW);
1506
1507         *zpp = zp;
1508
1509         txtype = zfs_log_create_txtype(Z_DIR, NULL, vap);
1510         zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, NULL,
1511             acl_ids.z_fuidp, vap);
1512
1513         zfs_acl_ids_free(&acl_ids);
1514
1515         dmu_tx_commit(tx);
1516
1517         getnewvnode_drop_reserve();
1518
1519         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1520                 zil_commit(zilog, 0);
1521
1522         ZFS_EXIT(zfsvfs);
1523         return (0);
1524 }
1525
1526 #if     __FreeBSD_version < 1300124
1527 static void
1528 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
1529 {
1530
1531         cache_purge(dvp);
1532         cache_purge(vp);
1533 }
1534 #endif
1535
1536 /*
1537  * Remove a directory subdir entry.  If the current working
1538  * directory is the same as the subdir to be removed, the
1539  * remove will fail.
1540  *
1541  *      IN:     dvp     - vnode of directory to remove from.
1542  *              name    - name of directory to be removed.
1543  *              cwd     - vnode of current working directory.
1544  *              cr      - credentials of caller.
1545  *              ct      - caller context
1546  *              flags   - case flags
1547  *
1548  *      RETURN: 0 on success, error code on failure.
1549  *
1550  * Timestamps:
1551  *      dvp - ctime|mtime updated
1552  */
1553 /*ARGSUSED*/
1554 static int
1555 zfs_rmdir_(vnode_t *dvp, vnode_t *vp, const char *name, cred_t *cr)
1556 {
1557         znode_t         *dzp = VTOZ(dvp);
1558         znode_t         *zp = VTOZ(vp);
1559         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1560         zilog_t         *zilog;
1561         dmu_tx_t        *tx;
1562         int             error;
1563
1564         ZFS_ENTER(zfsvfs);
1565         ZFS_VERIFY_ZP(dzp);
1566         ZFS_VERIFY_ZP(zp);
1567         zilog = zfsvfs->z_log;
1568
1569
1570         if ((error = zfs_zaccess_delete(dzp, zp, cr))) {
1571                 goto out;
1572         }
1573
1574         if (vp->v_type != VDIR) {
1575                 error = SET_ERROR(ENOTDIR);
1576                 goto out;
1577         }
1578
1579         vnevent_rmdir(vp, dvp, name, ct);
1580
1581         tx = dmu_tx_create(zfsvfs->z_os);
1582         dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1583         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1584         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1585         zfs_sa_upgrade_txholds(tx, zp);
1586         zfs_sa_upgrade_txholds(tx, dzp);
1587         dmu_tx_mark_netfree(tx);
1588         error = dmu_tx_assign(tx, TXG_WAIT);
1589         if (error) {
1590                 dmu_tx_abort(tx);
1591                 ZFS_EXIT(zfsvfs);
1592                 return (error);
1593         }
1594
1595         error = zfs_link_destroy(dzp, name, zp, tx, ZEXISTS, NULL);
1596
1597         if (error == 0) {
1598                 uint64_t txtype = TX_RMDIR;
1599                 zfs_log_remove(zilog, tx, txtype, dzp, name,
1600                     ZFS_NO_OBJECT, B_FALSE);
1601         }
1602
1603         dmu_tx_commit(tx);
1604
1605         cache_vop_rmdir(dvp, vp);
1606 out:
1607         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1608                 zil_commit(zilog, 0);
1609
1610         ZFS_EXIT(zfsvfs);
1611         return (error);
1612 }
1613
1614 int
1615 zfs_rmdir(znode_t *dzp, const char *name, znode_t *cwd, cred_t *cr, int flags)
1616 {
1617         struct componentname cn;
1618         vnode_t *vp;
1619         int error;
1620
1621         if ((error = zfs_lookup_internal(dzp, name, &vp, &cn, DELETE)))
1622                 return (error);
1623
1624         error = zfs_rmdir_(ZTOV(dzp), vp, name, cr);
1625         vput(vp);
1626         return (error);
1627 }
1628
1629 /*
1630  * Read as many directory entries as will fit into the provided
1631  * buffer from the given directory cursor position (specified in
1632  * the uio structure).
1633  *
1634  *      IN:     vp      - vnode of directory to read.
1635  *              uio     - structure supplying read location, range info,
1636  *                        and return buffer.
1637  *              cr      - credentials of caller.
1638  *              ct      - caller context
1639  *              flags   - case flags
1640  *
1641  *      OUT:    uio     - updated offset and range, buffer filled.
1642  *              eofp    - set to true if end-of-file detected.
1643  *
1644  *      RETURN: 0 on success, error code on failure.
1645  *
1646  * Timestamps:
1647  *      vp - atime updated
1648  *
1649  * Note that the low 4 bits of the cookie returned by zap is always zero.
1650  * This allows us to use the low range for "special" directory entries:
1651  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
1652  * we use the offset 2 for the '.zfs' directory.
1653  */
1654 /* ARGSUSED */
1655 static int
1656 zfs_readdir(vnode_t *vp, zfs_uio_t *uio, cred_t *cr, int *eofp,
1657     int *ncookies, ulong_t **cookies)
1658 {
1659         znode_t         *zp = VTOZ(vp);
1660         iovec_t         *iovp;
1661         edirent_t       *eodp;
1662         dirent64_t      *odp;
1663         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
1664         objset_t        *os;
1665         caddr_t         outbuf;
1666         size_t          bufsize;
1667         zap_cursor_t    zc;
1668         zap_attribute_t zap;
1669         uint_t          bytes_wanted;
1670         uint64_t        offset; /* must be unsigned; checks for < 1 */
1671         uint64_t        parent;
1672         int             local_eof;
1673         int             outcount;
1674         int             error;
1675         uint8_t         prefetch;
1676         boolean_t       check_sysattrs;
1677         uint8_t         type;
1678         int             ncooks;
1679         ulong_t         *cooks = NULL;
1680         int             flags = 0;
1681
1682         ZFS_ENTER(zfsvfs);
1683         ZFS_VERIFY_ZP(zp);
1684
1685         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
1686             &parent, sizeof (parent))) != 0) {
1687                 ZFS_EXIT(zfsvfs);
1688                 return (error);
1689         }
1690
1691         /*
1692          * If we are not given an eof variable,
1693          * use a local one.
1694          */
1695         if (eofp == NULL)
1696                 eofp = &local_eof;
1697
1698         /*
1699          * Check for valid iov_len.
1700          */
1701         if (GET_UIO_STRUCT(uio)->uio_iov->iov_len <= 0) {
1702                 ZFS_EXIT(zfsvfs);
1703                 return (SET_ERROR(EINVAL));
1704         }
1705
1706         /*
1707          * Quit if directory has been removed (posix)
1708          */
1709         if ((*eofp = zp->z_unlinked) != 0) {
1710                 ZFS_EXIT(zfsvfs);
1711                 return (0);
1712         }
1713
1714         error = 0;
1715         os = zfsvfs->z_os;
1716         offset = zfs_uio_offset(uio);
1717         prefetch = zp->z_zn_prefetch;
1718
1719         /*
1720          * Initialize the iterator cursor.
1721          */
1722         if (offset <= 3) {
1723                 /*
1724                  * Start iteration from the beginning of the directory.
1725                  */
1726                 zap_cursor_init(&zc, os, zp->z_id);
1727         } else {
1728                 /*
1729                  * The offset is a serialized cursor.
1730                  */
1731                 zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
1732         }
1733
1734         /*
1735          * Get space to change directory entries into fs independent format.
1736          */
1737         iovp = GET_UIO_STRUCT(uio)->uio_iov;
1738         bytes_wanted = iovp->iov_len;
1739         if (zfs_uio_segflg(uio) != UIO_SYSSPACE || zfs_uio_iovcnt(uio) != 1) {
1740                 bufsize = bytes_wanted;
1741                 outbuf = kmem_alloc(bufsize, KM_SLEEP);
1742                 odp = (struct dirent64 *)outbuf;
1743         } else {
1744                 bufsize = bytes_wanted;
1745                 outbuf = NULL;
1746                 odp = (struct dirent64 *)iovp->iov_base;
1747         }
1748         eodp = (struct edirent *)odp;
1749
1750         if (ncookies != NULL) {
1751                 /*
1752                  * Minimum entry size is dirent size and 1 byte for a file name.
1753                  */
1754                 ncooks = zfs_uio_resid(uio) / (sizeof (struct dirent) -
1755                     sizeof (((struct dirent *)NULL)->d_name) + 1);
1756                 cooks = malloc(ncooks * sizeof (ulong_t), M_TEMP, M_WAITOK);
1757                 *cookies = cooks;
1758                 *ncookies = ncooks;
1759         }
1760         /*
1761          * If this VFS supports the system attribute view interface; and
1762          * we're looking at an extended attribute directory; and we care
1763          * about normalization conflicts on this vfs; then we must check
1764          * for normalization conflicts with the sysattr name space.
1765          */
1766 #ifdef TODO
1767         check_sysattrs = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
1768             (vp->v_flag & V_XATTRDIR) && zfsvfs->z_norm &&
1769             (flags & V_RDDIR_ENTFLAGS);
1770 #else
1771         check_sysattrs = 0;
1772 #endif
1773
1774         /*
1775          * Transform to file-system independent format
1776          */
1777         outcount = 0;
1778         while (outcount < bytes_wanted) {
1779                 ino64_t objnum;
1780                 ushort_t reclen;
1781                 off64_t *next = NULL;
1782
1783                 /*
1784                  * Special case `.', `..', and `.zfs'.
1785                  */
1786                 if (offset == 0) {
1787                         (void) strcpy(zap.za_name, ".");
1788                         zap.za_normalization_conflict = 0;
1789                         objnum = zp->z_id;
1790                         type = DT_DIR;
1791                 } else if (offset == 1) {
1792                         (void) strcpy(zap.za_name, "..");
1793                         zap.za_normalization_conflict = 0;
1794                         objnum = parent;
1795                         type = DT_DIR;
1796                 } else if (offset == 2 && zfs_show_ctldir(zp)) {
1797                         (void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
1798                         zap.za_normalization_conflict = 0;
1799                         objnum = ZFSCTL_INO_ROOT;
1800                         type = DT_DIR;
1801                 } else {
1802                         /*
1803                          * Grab next entry.
1804                          */
1805                         if ((error = zap_cursor_retrieve(&zc, &zap))) {
1806                                 if ((*eofp = (error == ENOENT)) != 0)
1807                                         break;
1808                                 else
1809                                         goto update;
1810                         }
1811
1812                         if (zap.za_integer_length != 8 ||
1813                             zap.za_num_integers != 1) {
1814                                 cmn_err(CE_WARN, "zap_readdir: bad directory "
1815                                     "entry, obj = %lld, offset = %lld\n",
1816                                     (u_longlong_t)zp->z_id,
1817                                     (u_longlong_t)offset);
1818                                 error = SET_ERROR(ENXIO);
1819                                 goto update;
1820                         }
1821
1822                         objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
1823                         /*
1824                          * MacOS X can extract the object type here such as:
1825                          * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
1826                          */
1827                         type = ZFS_DIRENT_TYPE(zap.za_first_integer);
1828
1829                         if (check_sysattrs && !zap.za_normalization_conflict) {
1830 #ifdef TODO
1831                                 zap.za_normalization_conflict =
1832                                     xattr_sysattr_casechk(zap.za_name);
1833 #else
1834                                 panic("%s:%u: TODO", __func__, __LINE__);
1835 #endif
1836                         }
1837                 }
1838
1839                 if (flags & V_RDDIR_ACCFILTER) {
1840                         /*
1841                          * If we have no access at all, don't include
1842                          * this entry in the returned information
1843                          */
1844                         znode_t *ezp;
1845                         if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
1846                                 goto skip_entry;
1847                         if (!zfs_has_access(ezp, cr)) {
1848                                 vrele(ZTOV(ezp));
1849                                 goto skip_entry;
1850                         }
1851                         vrele(ZTOV(ezp));
1852                 }
1853
1854                 if (flags & V_RDDIR_ENTFLAGS)
1855                         reclen = EDIRENT_RECLEN(strlen(zap.za_name));
1856                 else
1857                         reclen = DIRENT64_RECLEN(strlen(zap.za_name));
1858
1859                 /*
1860                  * Will this entry fit in the buffer?
1861                  */
1862                 if (outcount + reclen > bufsize) {
1863                         /*
1864                          * Did we manage to fit anything in the buffer?
1865                          */
1866                         if (!outcount) {
1867                                 error = SET_ERROR(EINVAL);
1868                                 goto update;
1869                         }
1870                         break;
1871                 }
1872                 if (flags & V_RDDIR_ENTFLAGS) {
1873                         /*
1874                          * Add extended flag entry:
1875                          */
1876                         eodp->ed_ino = objnum;
1877                         eodp->ed_reclen = reclen;
1878                         /* NOTE: ed_off is the offset for the *next* entry */
1879                         next = &(eodp->ed_off);
1880                         eodp->ed_eflags = zap.za_normalization_conflict ?
1881                             ED_CASE_CONFLICT : 0;
1882                         (void) strncpy(eodp->ed_name, zap.za_name,
1883                             EDIRENT_NAMELEN(reclen));
1884                         eodp = (edirent_t *)((intptr_t)eodp + reclen);
1885                 } else {
1886                         /*
1887                          * Add normal entry:
1888                          */
1889                         odp->d_ino = objnum;
1890                         odp->d_reclen = reclen;
1891                         odp->d_namlen = strlen(zap.za_name);
1892                         /* NOTE: d_off is the offset for the *next* entry. */
1893                         next = &odp->d_off;
1894                         strlcpy(odp->d_name, zap.za_name, odp->d_namlen + 1);
1895                         odp->d_type = type;
1896                         dirent_terminate(odp);
1897                         odp = (dirent64_t *)((intptr_t)odp + reclen);
1898                 }
1899                 outcount += reclen;
1900
1901                 ASSERT(outcount <= bufsize);
1902
1903                 /* Prefetch znode */
1904                 if (prefetch)
1905                         dmu_prefetch(os, objnum, 0, 0, 0,
1906                             ZIO_PRIORITY_SYNC_READ);
1907
1908         skip_entry:
1909                 /*
1910                  * Move to the next entry, fill in the previous offset.
1911                  */
1912                 if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
1913                         zap_cursor_advance(&zc);
1914                         offset = zap_cursor_serialize(&zc);
1915                 } else {
1916                         offset += 1;
1917                 }
1918
1919                 /* Fill the offset right after advancing the cursor. */
1920                 if (next != NULL)
1921                         *next = offset;
1922                 if (cooks != NULL) {
1923                         *cooks++ = offset;
1924                         ncooks--;
1925                         KASSERT(ncooks >= 0, ("ncookies=%d", ncooks));
1926                 }
1927         }
1928         zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
1929
1930         /* Subtract unused cookies */
1931         if (ncookies != NULL)
1932                 *ncookies -= ncooks;
1933
1934         if (zfs_uio_segflg(uio) == UIO_SYSSPACE && zfs_uio_iovcnt(uio) == 1) {
1935                 iovp->iov_base += outcount;
1936                 iovp->iov_len -= outcount;
1937                 zfs_uio_resid(uio) -= outcount;
1938         } else if ((error =
1939             zfs_uiomove(outbuf, (long)outcount, UIO_READ, uio))) {
1940                 /*
1941                  * Reset the pointer.
1942                  */
1943                 offset = zfs_uio_offset(uio);
1944         }
1945
1946 update:
1947         zap_cursor_fini(&zc);
1948         if (zfs_uio_segflg(uio) != UIO_SYSSPACE || zfs_uio_iovcnt(uio) != 1)
1949                 kmem_free(outbuf, bufsize);
1950
1951         if (error == ENOENT)
1952                 error = 0;
1953
1954         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
1955
1956         zfs_uio_setoffset(uio, offset);
1957         ZFS_EXIT(zfsvfs);
1958         if (error != 0 && cookies != NULL) {
1959                 free(*cookies, M_TEMP);
1960                 *cookies = NULL;
1961                 *ncookies = 0;
1962         }
1963         return (error);
1964 }
1965
1966 /*
1967  * Get the requested file attributes and place them in the provided
1968  * vattr structure.
1969  *
1970  *      IN:     vp      - vnode of file.
1971  *              vap     - va_mask identifies requested attributes.
1972  *                        If AT_XVATTR set, then optional attrs are requested
1973  *              flags   - ATTR_NOACLCHECK (CIFS server context)
1974  *              cr      - credentials of caller.
1975  *
1976  *      OUT:    vap     - attribute values.
1977  *
1978  *      RETURN: 0 (always succeeds).
1979  */
1980 /* ARGSUSED */
1981 static int
1982 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr)
1983 {
1984         znode_t *zp = VTOZ(vp);
1985         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1986         int     error = 0;
1987         uint32_t blksize;
1988         u_longlong_t nblocks;
1989         uint64_t mtime[2], ctime[2], crtime[2], rdev;
1990         xvattr_t *xvap = (xvattr_t *)vap;       /* vap may be an xvattr_t * */
1991         xoptattr_t *xoap = NULL;
1992         boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
1993         sa_bulk_attr_t bulk[4];
1994         int count = 0;
1995
1996         ZFS_ENTER(zfsvfs);
1997         ZFS_VERIFY_ZP(zp);
1998
1999         zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
2000
2001         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
2002         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
2003         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, &crtime, 16);
2004         if (vp->v_type == VBLK || vp->v_type == VCHR)
2005                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_RDEV(zfsvfs), NULL,
2006                     &rdev, 8);
2007
2008         if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
2009                 ZFS_EXIT(zfsvfs);
2010                 return (error);
2011         }
2012
2013         /*
2014          * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2015          * Also, if we are the owner don't bother, since owner should
2016          * always be allowed to read basic attributes of file.
2017          */
2018         if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
2019             (vap->va_uid != crgetuid(cr))) {
2020                 if ((error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2021                     skipaclchk, cr))) {
2022                         ZFS_EXIT(zfsvfs);
2023                         return (error);
2024                 }
2025         }
2026
2027         /*
2028          * Return all attributes.  It's cheaper to provide the answer
2029          * than to determine whether we were asked the question.
2030          */
2031
2032         vap->va_type = IFTOVT(zp->z_mode);
2033         vap->va_mode = zp->z_mode & ~S_IFMT;
2034         vn_fsid(vp, vap);
2035         vap->va_nodeid = zp->z_id;
2036         vap->va_nlink = zp->z_links;
2037         if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp) &&
2038             zp->z_links < ZFS_LINK_MAX)
2039                 vap->va_nlink++;
2040         vap->va_size = zp->z_size;
2041         if (vp->v_type == VBLK || vp->v_type == VCHR)
2042                 vap->va_rdev = zfs_cmpldev(rdev);
2043         vap->va_seq = zp->z_seq;
2044         vap->va_flags = 0;      /* FreeBSD: Reset chflags(2) flags. */
2045         vap->va_filerev = zp->z_seq;
2046
2047         /*
2048          * Add in any requested optional attributes and the create time.
2049          * Also set the corresponding bits in the returned attribute bitmap.
2050          */
2051         if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2052                 if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2053                         xoap->xoa_archive =
2054                             ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2055                         XVA_SET_RTN(xvap, XAT_ARCHIVE);
2056                 }
2057
2058                 if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2059                         xoap->xoa_readonly =
2060                             ((zp->z_pflags & ZFS_READONLY) != 0);
2061                         XVA_SET_RTN(xvap, XAT_READONLY);
2062                 }
2063
2064                 if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2065                         xoap->xoa_system =
2066                             ((zp->z_pflags & ZFS_SYSTEM) != 0);
2067                         XVA_SET_RTN(xvap, XAT_SYSTEM);
2068                 }
2069
2070                 if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2071                         xoap->xoa_hidden =
2072                             ((zp->z_pflags & ZFS_HIDDEN) != 0);
2073                         XVA_SET_RTN(xvap, XAT_HIDDEN);
2074                 }
2075
2076                 if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2077                         xoap->xoa_nounlink =
2078                             ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2079                         XVA_SET_RTN(xvap, XAT_NOUNLINK);
2080                 }
2081
2082                 if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2083                         xoap->xoa_immutable =
2084                             ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2085                         XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2086                 }
2087
2088                 if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2089                         xoap->xoa_appendonly =
2090                             ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2091                         XVA_SET_RTN(xvap, XAT_APPENDONLY);
2092                 }
2093
2094                 if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2095                         xoap->xoa_nodump =
2096                             ((zp->z_pflags & ZFS_NODUMP) != 0);
2097                         XVA_SET_RTN(xvap, XAT_NODUMP);
2098                 }
2099
2100                 if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2101                         xoap->xoa_opaque =
2102                             ((zp->z_pflags & ZFS_OPAQUE) != 0);
2103                         XVA_SET_RTN(xvap, XAT_OPAQUE);
2104                 }
2105
2106                 if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2107                         xoap->xoa_av_quarantined =
2108                             ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2109                         XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2110                 }
2111
2112                 if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2113                         xoap->xoa_av_modified =
2114                             ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2115                         XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2116                 }
2117
2118                 if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2119                     vp->v_type == VREG) {
2120                         zfs_sa_get_scanstamp(zp, xvap);
2121                 }
2122
2123                 if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2124                         xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2125                         XVA_SET_RTN(xvap, XAT_REPARSE);
2126                 }
2127                 if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2128                         xoap->xoa_generation = zp->z_gen;
2129                         XVA_SET_RTN(xvap, XAT_GEN);
2130                 }
2131
2132                 if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2133                         xoap->xoa_offline =
2134                             ((zp->z_pflags & ZFS_OFFLINE) != 0);
2135                         XVA_SET_RTN(xvap, XAT_OFFLINE);
2136                 }
2137
2138                 if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2139                         xoap->xoa_sparse =
2140                             ((zp->z_pflags & ZFS_SPARSE) != 0);
2141                         XVA_SET_RTN(xvap, XAT_SPARSE);
2142                 }
2143
2144                 if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
2145                         xoap->xoa_projinherit =
2146                             ((zp->z_pflags & ZFS_PROJINHERIT) != 0);
2147                         XVA_SET_RTN(xvap, XAT_PROJINHERIT);
2148                 }
2149
2150                 if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
2151                         xoap->xoa_projid = zp->z_projid;
2152                         XVA_SET_RTN(xvap, XAT_PROJID);
2153                 }
2154         }
2155
2156         ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2157         ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2158         ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2159         ZFS_TIME_DECODE(&vap->va_birthtime, crtime);
2160
2161
2162         sa_object_size(zp->z_sa_hdl, &blksize, &nblocks);
2163         vap->va_blksize = blksize;
2164         vap->va_bytes = nblocks << 9;   /* nblocks * 512 */
2165
2166         if (zp->z_blksz == 0) {
2167                 /*
2168                  * Block size hasn't been set; suggest maximal I/O transfers.
2169                  */
2170                 vap->va_blksize = zfsvfs->z_max_blksz;
2171         }
2172
2173         ZFS_EXIT(zfsvfs);
2174         return (0);
2175 }
2176
2177 /*
2178  * Set the file attributes to the values contained in the
2179  * vattr structure.
2180  *
2181  *      IN:     zp      - znode of file to be modified.
2182  *              vap     - new attribute values.
2183  *                        If AT_XVATTR set, then optional attrs are being set
2184  *              flags   - ATTR_UTIME set if non-default time values provided.
2185  *                      - ATTR_NOACLCHECK (CIFS context only).
2186  *              cr      - credentials of caller.
2187  *              ct      - caller context
2188  *
2189  *      RETURN: 0 on success, error code on failure.
2190  *
2191  * Timestamps:
2192  *      vp - ctime updated, mtime updated if size changed.
2193  */
2194 /* ARGSUSED */
2195 int
2196 zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr)
2197 {
2198         vnode_t         *vp = ZTOV(zp);
2199         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
2200         objset_t        *os = zfsvfs->z_os;
2201         zilog_t         *zilog;
2202         dmu_tx_t        *tx;
2203         vattr_t         oldva;
2204         xvattr_t        tmpxvattr;
2205         uint_t          mask = vap->va_mask;
2206         uint_t          saved_mask = 0;
2207         uint64_t        saved_mode;
2208         int             trim_mask = 0;
2209         uint64_t        new_mode;
2210         uint64_t        new_uid, new_gid;
2211         uint64_t        xattr_obj;
2212         uint64_t        mtime[2], ctime[2];
2213         uint64_t        projid = ZFS_INVALID_PROJID;
2214         znode_t         *attrzp;
2215         int             need_policy = FALSE;
2216         int             err, err2;
2217         zfs_fuid_info_t *fuidp = NULL;
2218         xvattr_t *xvap = (xvattr_t *)vap;       /* vap may be an xvattr_t * */
2219         xoptattr_t      *xoap;
2220         zfs_acl_t       *aclp;
2221         boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2222         boolean_t       fuid_dirtied = B_FALSE;
2223         sa_bulk_attr_t  bulk[7], xattr_bulk[7];
2224         int             count = 0, xattr_count = 0;
2225
2226         if (mask == 0)
2227                 return (0);
2228
2229         if (mask & AT_NOSET)
2230                 return (SET_ERROR(EINVAL));
2231
2232         ZFS_ENTER(zfsvfs);
2233         ZFS_VERIFY_ZP(zp);
2234
2235         zilog = zfsvfs->z_log;
2236
2237         /*
2238          * Make sure that if we have ephemeral uid/gid or xvattr specified
2239          * that file system is at proper version level
2240          */
2241
2242         if (zfsvfs->z_use_fuids == B_FALSE &&
2243             (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2244             ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2245             (mask & AT_XVATTR))) {
2246                 ZFS_EXIT(zfsvfs);
2247                 return (SET_ERROR(EINVAL));
2248         }
2249
2250         if (mask & AT_SIZE && vp->v_type == VDIR) {
2251                 ZFS_EXIT(zfsvfs);
2252                 return (SET_ERROR(EISDIR));
2253         }
2254
2255         if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2256                 ZFS_EXIT(zfsvfs);
2257                 return (SET_ERROR(EINVAL));
2258         }
2259
2260         /*
2261          * If this is an xvattr_t, then get a pointer to the structure of
2262          * optional attributes.  If this is NULL, then we have a vattr_t.
2263          */
2264         xoap = xva_getxoptattr(xvap);
2265
2266         xva_init(&tmpxvattr);
2267
2268         /*
2269          * Immutable files can only alter immutable bit and atime
2270          */
2271         if ((zp->z_pflags & ZFS_IMMUTABLE) &&
2272             ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2273             ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2274                 ZFS_EXIT(zfsvfs);
2275                 return (SET_ERROR(EPERM));
2276         }
2277
2278         /*
2279          * Note: ZFS_READONLY is handled in zfs_zaccess_common.
2280          */
2281
2282         /*
2283          * Verify timestamps doesn't overflow 32 bits.
2284          * ZFS can handle large timestamps, but 32bit syscalls can't
2285          * handle times greater than 2039.  This check should be removed
2286          * once large timestamps are fully supported.
2287          */
2288         if (mask & (AT_ATIME | AT_MTIME)) {
2289                 if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2290                     ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2291                         ZFS_EXIT(zfsvfs);
2292                         return (SET_ERROR(EOVERFLOW));
2293                 }
2294         }
2295         if (xoap != NULL && (mask & AT_XVATTR)) {
2296                 if (XVA_ISSET_REQ(xvap, XAT_CREATETIME) &&
2297                     TIMESPEC_OVERFLOW(&vap->va_birthtime)) {
2298                         ZFS_EXIT(zfsvfs);
2299                         return (SET_ERROR(EOVERFLOW));
2300                 }
2301
2302                 if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
2303                         if (!dmu_objset_projectquota_enabled(os) ||
2304                             (!S_ISREG(zp->z_mode) && !S_ISDIR(zp->z_mode))) {
2305                                 ZFS_EXIT(zfsvfs);
2306                                 return (SET_ERROR(EOPNOTSUPP));
2307                         }
2308
2309                         projid = xoap->xoa_projid;
2310                         if (unlikely(projid == ZFS_INVALID_PROJID)) {
2311                                 ZFS_EXIT(zfsvfs);
2312                                 return (SET_ERROR(EINVAL));
2313                         }
2314
2315                         if (projid == zp->z_projid && zp->z_pflags & ZFS_PROJID)
2316                                 projid = ZFS_INVALID_PROJID;
2317                         else
2318                                 need_policy = TRUE;
2319                 }
2320
2321                 if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT) &&
2322                     (xoap->xoa_projinherit !=
2323                     ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) &&
2324                     (!dmu_objset_projectquota_enabled(os) ||
2325                     (!S_ISREG(zp->z_mode) && !S_ISDIR(zp->z_mode)))) {
2326                         ZFS_EXIT(zfsvfs);
2327                         return (SET_ERROR(EOPNOTSUPP));
2328                 }
2329         }
2330
2331         attrzp = NULL;
2332         aclp = NULL;
2333
2334         if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2335                 ZFS_EXIT(zfsvfs);
2336                 return (SET_ERROR(EROFS));
2337         }
2338
2339         /*
2340          * First validate permissions
2341          */
2342
2343         if (mask & AT_SIZE) {
2344                 /*
2345                  * XXX - Note, we are not providing any open
2346                  * mode flags here (like FNDELAY), so we may
2347                  * block if there are locks present... this
2348                  * should be addressed in openat().
2349                  */
2350                 /* XXX - would it be OK to generate a log record here? */
2351                 err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2352                 if (err) {
2353                         ZFS_EXIT(zfsvfs);
2354                         return (err);
2355                 }
2356         }
2357
2358         if (mask & (AT_ATIME|AT_MTIME) ||
2359             ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2360             XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2361             XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2362             XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
2363             XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
2364             XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2365             XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
2366                 need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2367                     skipaclchk, cr);
2368         }
2369
2370         if (mask & (AT_UID|AT_GID)) {
2371                 int     idmask = (mask & (AT_UID|AT_GID));
2372                 int     take_owner;
2373                 int     take_group;
2374
2375                 /*
2376                  * NOTE: even if a new mode is being set,
2377                  * we may clear S_ISUID/S_ISGID bits.
2378                  */
2379
2380                 if (!(mask & AT_MODE))
2381                         vap->va_mode = zp->z_mode;
2382
2383                 /*
2384                  * Take ownership or chgrp to group we are a member of
2385                  */
2386
2387                 take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2388                 take_group = (mask & AT_GID) &&
2389                     zfs_groupmember(zfsvfs, vap->va_gid, cr);
2390
2391                 /*
2392                  * If both AT_UID and AT_GID are set then take_owner and
2393                  * take_group must both be set in order to allow taking
2394                  * ownership.
2395                  *
2396                  * Otherwise, send the check through secpolicy_vnode_setattr()
2397                  *
2398                  */
2399
2400                 if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2401                     ((idmask == AT_UID) && take_owner) ||
2402                     ((idmask == AT_GID) && take_group)) {
2403                         if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2404                             skipaclchk, cr) == 0) {
2405                                 /*
2406                                  * Remove setuid/setgid for non-privileged users
2407                                  */
2408                                 secpolicy_setid_clear(vap, vp, cr);
2409                                 trim_mask = (mask & (AT_UID|AT_GID));
2410                         } else {
2411                                 need_policy =  TRUE;
2412                         }
2413                 } else {
2414                         need_policy =  TRUE;
2415                 }
2416         }
2417
2418         oldva.va_mode = zp->z_mode;
2419         zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
2420         if (mask & AT_XVATTR) {
2421                 /*
2422                  * Update xvattr mask to include only those attributes
2423                  * that are actually changing.
2424                  *
2425                  * the bits will be restored prior to actually setting
2426                  * the attributes so the caller thinks they were set.
2427                  */
2428                 if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2429                         if (xoap->xoa_appendonly !=
2430                             ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
2431                                 need_policy = TRUE;
2432                         } else {
2433                                 XVA_CLR_REQ(xvap, XAT_APPENDONLY);
2434                                 XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
2435                         }
2436                 }
2437
2438                 if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
2439                         if (xoap->xoa_projinherit !=
2440                             ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) {
2441                                 need_policy = TRUE;
2442                         } else {
2443                                 XVA_CLR_REQ(xvap, XAT_PROJINHERIT);
2444                                 XVA_SET_REQ(&tmpxvattr, XAT_PROJINHERIT);
2445                         }
2446                 }
2447
2448                 if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2449                         if (xoap->xoa_nounlink !=
2450                             ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
2451                                 need_policy = TRUE;
2452                         } else {
2453                                 XVA_CLR_REQ(xvap, XAT_NOUNLINK);
2454                                 XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
2455                         }
2456                 }
2457
2458                 if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2459                         if (xoap->xoa_immutable !=
2460                             ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
2461                                 need_policy = TRUE;
2462                         } else {
2463                                 XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
2464                                 XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
2465                         }
2466                 }
2467
2468                 if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2469                         if (xoap->xoa_nodump !=
2470                             ((zp->z_pflags & ZFS_NODUMP) != 0)) {
2471                                 need_policy = TRUE;
2472                         } else {
2473                                 XVA_CLR_REQ(xvap, XAT_NODUMP);
2474                                 XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
2475                         }
2476                 }
2477
2478                 if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2479                         if (xoap->xoa_av_modified !=
2480                             ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
2481                                 need_policy = TRUE;
2482                         } else {
2483                                 XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
2484                                 XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
2485                         }
2486                 }
2487
2488                 if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2489                         if ((vp->v_type != VREG &&
2490                             xoap->xoa_av_quarantined) ||
2491                             xoap->xoa_av_quarantined !=
2492                             ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
2493                                 need_policy = TRUE;
2494                         } else {
2495                                 XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
2496                                 XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
2497                         }
2498                 }
2499
2500                 if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2501                         ZFS_EXIT(zfsvfs);
2502                         return (SET_ERROR(EPERM));
2503                 }
2504
2505                 if (need_policy == FALSE &&
2506                     (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
2507                     XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
2508                         need_policy = TRUE;
2509                 }
2510         }
2511
2512         if (mask & AT_MODE) {
2513                 if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
2514                         err = secpolicy_setid_setsticky_clear(vp, vap,
2515                             &oldva, cr);
2516                         if (err) {
2517                                 ZFS_EXIT(zfsvfs);
2518                                 return (err);
2519                         }
2520                         trim_mask |= AT_MODE;
2521                 } else {
2522                         need_policy = TRUE;
2523                 }
2524         }
2525
2526         if (need_policy) {
2527                 /*
2528                  * If trim_mask is set then take ownership
2529                  * has been granted or write_acl is present and user
2530                  * has the ability to modify mode.  In that case remove
2531                  * UID|GID and or MODE from mask so that
2532                  * secpolicy_vnode_setattr() doesn't revoke it.
2533                  */
2534
2535                 if (trim_mask) {
2536                         saved_mask = vap->va_mask;
2537                         vap->va_mask &= ~trim_mask;
2538                         if (trim_mask & AT_MODE) {
2539                                 /*
2540                                  * Save the mode, as secpolicy_vnode_setattr()
2541                                  * will overwrite it with ova.va_mode.
2542                                  */
2543                                 saved_mode = vap->va_mode;
2544                         }
2545                 }
2546                 err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
2547                     (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
2548                 if (err) {
2549                         ZFS_EXIT(zfsvfs);
2550                         return (err);
2551                 }
2552
2553                 if (trim_mask) {
2554                         vap->va_mask |= saved_mask;
2555                         if (trim_mask & AT_MODE) {
2556                                 /*
2557                                  * Recover the mode after
2558                                  * secpolicy_vnode_setattr().
2559                                  */
2560                                 vap->va_mode = saved_mode;
2561                         }
2562                 }
2563         }
2564
2565         /*
2566          * secpolicy_vnode_setattr, or take ownership may have
2567          * changed va_mask
2568          */
2569         mask = vap->va_mask;
2570
2571         if ((mask & (AT_UID | AT_GID)) || projid != ZFS_INVALID_PROJID) {
2572                 err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
2573                     &xattr_obj, sizeof (xattr_obj));
2574
2575                 if (err == 0 && xattr_obj) {
2576                         err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp);
2577                         if (err == 0) {
2578                                 err = vn_lock(ZTOV(attrzp), LK_EXCLUSIVE);
2579                                 if (err != 0)
2580                                         vrele(ZTOV(attrzp));
2581                         }
2582                         if (err)
2583                                 goto out2;
2584                 }
2585                 if (mask & AT_UID) {
2586                         new_uid = zfs_fuid_create(zfsvfs,
2587                             (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
2588                         if (new_uid != zp->z_uid &&
2589                             zfs_id_overquota(zfsvfs, DMU_USERUSED_OBJECT,
2590                             new_uid)) {
2591                                 if (attrzp)
2592                                         vput(ZTOV(attrzp));
2593                                 err = SET_ERROR(EDQUOT);
2594                                 goto out2;
2595                         }
2596                 }
2597
2598                 if (mask & AT_GID) {
2599                         new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
2600                             cr, ZFS_GROUP, &fuidp);
2601                         if (new_gid != zp->z_gid &&
2602                             zfs_id_overquota(zfsvfs, DMU_GROUPUSED_OBJECT,
2603                             new_gid)) {
2604                                 if (attrzp)
2605                                         vput(ZTOV(attrzp));
2606                                 err = SET_ERROR(EDQUOT);
2607                                 goto out2;
2608                         }
2609                 }
2610
2611                 if (projid != ZFS_INVALID_PROJID &&
2612                     zfs_id_overquota(zfsvfs, DMU_PROJECTUSED_OBJECT, projid)) {
2613                         if (attrzp)
2614                                 vput(ZTOV(attrzp));
2615                         err = SET_ERROR(EDQUOT);
2616                         goto out2;
2617                 }
2618         }
2619         tx = dmu_tx_create(os);
2620
2621         if (mask & AT_MODE) {
2622                 uint64_t pmode = zp->z_mode;
2623                 uint64_t acl_obj;
2624                 new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
2625
2626                 if (zp->z_zfsvfs->z_acl_mode == ZFS_ACL_RESTRICTED &&
2627                     !(zp->z_pflags & ZFS_ACL_TRIVIAL)) {
2628                         err = SET_ERROR(EPERM);
2629                         goto out;
2630                 }
2631
2632                 if ((err = zfs_acl_chmod_setattr(zp, &aclp, new_mode)))
2633                         goto out;
2634
2635                 if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
2636                         /*
2637                          * Are we upgrading ACL from old V0 format
2638                          * to V1 format?
2639                          */
2640                         if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
2641                             zfs_znode_acl_version(zp) ==
2642                             ZFS_ACL_VERSION_INITIAL) {
2643                                 dmu_tx_hold_free(tx, acl_obj, 0,
2644                                     DMU_OBJECT_END);
2645                                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2646                                     0, aclp->z_acl_bytes);
2647                         } else {
2648                                 dmu_tx_hold_write(tx, acl_obj, 0,
2649                                     aclp->z_acl_bytes);
2650                         }
2651                 } else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
2652                         dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2653                             0, aclp->z_acl_bytes);
2654                 }
2655                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2656         } else {
2657                 if (((mask & AT_XVATTR) &&
2658                     XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) ||
2659                     (projid != ZFS_INVALID_PROJID &&
2660                     !(zp->z_pflags & ZFS_PROJID)))
2661                         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2662                 else
2663                         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2664         }
2665
2666         if (attrzp) {
2667                 dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, B_FALSE);
2668         }
2669
2670         fuid_dirtied = zfsvfs->z_fuid_dirty;
2671         if (fuid_dirtied)
2672                 zfs_fuid_txhold(zfsvfs, tx);
2673
2674         zfs_sa_upgrade_txholds(tx, zp);
2675
2676         err = dmu_tx_assign(tx, TXG_WAIT);
2677         if (err)
2678                 goto out;
2679
2680         count = 0;
2681         /*
2682          * Set each attribute requested.
2683          * We group settings according to the locks they need to acquire.
2684          *
2685          * Note: you cannot set ctime directly, although it will be
2686          * updated as a side-effect of calling this function.
2687          */
2688
2689         if (projid != ZFS_INVALID_PROJID && !(zp->z_pflags & ZFS_PROJID)) {
2690                 /*
2691                  * For the existed object that is upgraded from old system,
2692                  * its on-disk layout has no slot for the project ID attribute.
2693                  * But quota accounting logic needs to access related slots by
2694                  * offset directly. So we need to adjust old objects' layout
2695                  * to make the project ID to some unified and fixed offset.
2696                  */
2697                 if (attrzp)
2698                         err = sa_add_projid(attrzp->z_sa_hdl, tx, projid);
2699                 if (err == 0)
2700                         err = sa_add_projid(zp->z_sa_hdl, tx, projid);
2701
2702                 if (unlikely(err == EEXIST))
2703                         err = 0;
2704                 else if (err != 0)
2705                         goto out;
2706                 else
2707                         projid = ZFS_INVALID_PROJID;
2708         }
2709
2710         if (mask & (AT_UID|AT_GID|AT_MODE))
2711                 mutex_enter(&zp->z_acl_lock);
2712
2713         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
2714             &zp->z_pflags, sizeof (zp->z_pflags));
2715
2716         if (attrzp) {
2717                 if (mask & (AT_UID|AT_GID|AT_MODE))
2718                         mutex_enter(&attrzp->z_acl_lock);
2719                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2720                     SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
2721                     sizeof (attrzp->z_pflags));
2722                 if (projid != ZFS_INVALID_PROJID) {
2723                         attrzp->z_projid = projid;
2724                         SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2725                             SA_ZPL_PROJID(zfsvfs), NULL, &attrzp->z_projid,
2726                             sizeof (attrzp->z_projid));
2727                 }
2728         }
2729
2730         if (mask & (AT_UID|AT_GID)) {
2731
2732                 if (mask & AT_UID) {
2733                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
2734                             &new_uid, sizeof (new_uid));
2735                         zp->z_uid = new_uid;
2736                         if (attrzp) {
2737                                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2738                                     SA_ZPL_UID(zfsvfs), NULL, &new_uid,
2739                                     sizeof (new_uid));
2740                                 attrzp->z_uid = new_uid;
2741                         }
2742                 }
2743
2744                 if (mask & AT_GID) {
2745                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
2746                             NULL, &new_gid, sizeof (new_gid));
2747                         zp->z_gid = new_gid;
2748                         if (attrzp) {
2749                                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2750                                     SA_ZPL_GID(zfsvfs), NULL, &new_gid,
2751                                     sizeof (new_gid));
2752                                 attrzp->z_gid = new_gid;
2753                         }
2754                 }
2755                 if (!(mask & AT_MODE)) {
2756                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
2757                             NULL, &new_mode, sizeof (new_mode));
2758                         new_mode = zp->z_mode;
2759                 }
2760                 err = zfs_acl_chown_setattr(zp);
2761                 ASSERT(err == 0);
2762                 if (attrzp) {
2763                         err = zfs_acl_chown_setattr(attrzp);
2764                         ASSERT(err == 0);
2765                 }
2766         }
2767
2768         if (mask & AT_MODE) {
2769                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
2770                     &new_mode, sizeof (new_mode));
2771                 zp->z_mode = new_mode;
2772                 ASSERT3U((uintptr_t)aclp, !=, 0);
2773                 err = zfs_aclset_common(zp, aclp, cr, tx);
2774                 ASSERT0(err);
2775                 if (zp->z_acl_cached)
2776                         zfs_acl_free(zp->z_acl_cached);
2777                 zp->z_acl_cached = aclp;
2778                 aclp = NULL;
2779         }
2780
2781
2782         if (mask & AT_ATIME) {
2783                 ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
2784                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
2785                     &zp->z_atime, sizeof (zp->z_atime));
2786         }
2787
2788         if (mask & AT_MTIME) {
2789                 ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
2790                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
2791                     mtime, sizeof (mtime));
2792         }
2793
2794         if (projid != ZFS_INVALID_PROJID) {
2795                 zp->z_projid = projid;
2796                 SA_ADD_BULK_ATTR(bulk, count,
2797                     SA_ZPL_PROJID(zfsvfs), NULL, &zp->z_projid,
2798                     sizeof (zp->z_projid));
2799         }
2800
2801         /* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
2802         if (mask & AT_SIZE && !(mask & AT_MTIME)) {
2803                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
2804                     NULL, mtime, sizeof (mtime));
2805                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
2806                     &ctime, sizeof (ctime));
2807                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
2808         } else if (mask != 0) {
2809                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
2810                     &ctime, sizeof (ctime));
2811                 zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime);
2812                 if (attrzp) {
2813                         SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2814                             SA_ZPL_CTIME(zfsvfs), NULL,
2815                             &ctime, sizeof (ctime));
2816                         zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
2817                             mtime, ctime);
2818                 }
2819         }
2820
2821         /*
2822          * Do this after setting timestamps to prevent timestamp
2823          * update from toggling bit
2824          */
2825
2826         if (xoap && (mask & AT_XVATTR)) {
2827
2828                 if (XVA_ISSET_REQ(xvap, XAT_CREATETIME))
2829                         xoap->xoa_createtime = vap->va_birthtime;
2830                 /*
2831                  * restore trimmed off masks
2832                  * so that return masks can be set for caller.
2833                  */
2834
2835                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
2836                         XVA_SET_REQ(xvap, XAT_APPENDONLY);
2837                 }
2838                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
2839                         XVA_SET_REQ(xvap, XAT_NOUNLINK);
2840                 }
2841                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
2842                         XVA_SET_REQ(xvap, XAT_IMMUTABLE);
2843                 }
2844                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
2845                         XVA_SET_REQ(xvap, XAT_NODUMP);
2846                 }
2847                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
2848                         XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
2849                 }
2850                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
2851                         XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
2852                 }
2853                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_PROJINHERIT)) {
2854                         XVA_SET_REQ(xvap, XAT_PROJINHERIT);
2855                 }
2856
2857                 if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
2858                         ASSERT(vp->v_type == VREG);
2859
2860                 zfs_xvattr_set(zp, xvap, tx);
2861         }
2862
2863         if (fuid_dirtied)
2864                 zfs_fuid_sync(zfsvfs, tx);
2865
2866         if (mask != 0)
2867                 zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
2868
2869         if (mask & (AT_UID|AT_GID|AT_MODE))
2870                 mutex_exit(&zp->z_acl_lock);
2871
2872         if (attrzp) {
2873                 if (mask & (AT_UID|AT_GID|AT_MODE))
2874                         mutex_exit(&attrzp->z_acl_lock);
2875         }
2876 out:
2877         if (err == 0 && attrzp) {
2878                 err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
2879                     xattr_count, tx);
2880                 ASSERT(err2 == 0);
2881         }
2882
2883         if (attrzp)
2884                 vput(ZTOV(attrzp));
2885
2886         if (aclp)
2887                 zfs_acl_free(aclp);
2888
2889         if (fuidp) {
2890                 zfs_fuid_info_free(fuidp);
2891                 fuidp = NULL;
2892         }
2893
2894         if (err) {
2895                 dmu_tx_abort(tx);
2896         } else {
2897                 err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
2898                 dmu_tx_commit(tx);
2899         }
2900
2901 out2:
2902         if (os->os_sync == ZFS_SYNC_ALWAYS)
2903                 zil_commit(zilog, 0);
2904
2905         ZFS_EXIT(zfsvfs);
2906         return (err);
2907 }
2908
2909 /*
2910  * We acquire all but fdvp locks using non-blocking acquisitions.  If we
2911  * fail to acquire any lock in the path we will drop all held locks,
2912  * acquire the new lock in a blocking fashion, and then release it and
2913  * restart the rename.  This acquire/release step ensures that we do not
2914  * spin on a lock waiting for release.  On error release all vnode locks
2915  * and decrement references the way tmpfs_rename() would do.
2916  */
2917 static int
2918 zfs_rename_relock(struct vnode *sdvp, struct vnode **svpp,
2919     struct vnode *tdvp, struct vnode **tvpp,
2920     const struct componentname *scnp, const struct componentname *tcnp)
2921 {
2922         zfsvfs_t        *zfsvfs;
2923         struct vnode    *nvp, *svp, *tvp;
2924         znode_t         *sdzp, *tdzp, *szp, *tzp;
2925         const char      *snm = scnp->cn_nameptr;
2926         const char      *tnm = tcnp->cn_nameptr;
2927         int error;
2928
2929         VOP_UNLOCK1(tdvp);
2930         if (*tvpp != NULL && *tvpp != tdvp)
2931                 VOP_UNLOCK1(*tvpp);
2932
2933 relock:
2934         error = vn_lock(sdvp, LK_EXCLUSIVE);
2935         if (error)
2936                 goto out;
2937         sdzp = VTOZ(sdvp);
2938
2939         error = vn_lock(tdvp, LK_EXCLUSIVE | LK_NOWAIT);
2940         if (error != 0) {
2941                 VOP_UNLOCK1(sdvp);
2942                 if (error != EBUSY)
2943                         goto out;
2944                 error = vn_lock(tdvp, LK_EXCLUSIVE);
2945                 if (error)
2946                         goto out;
2947                 VOP_UNLOCK1(tdvp);
2948                 goto relock;
2949         }
2950         tdzp = VTOZ(tdvp);
2951
2952         /*
2953          * Before using sdzp and tdzp we must ensure that they are live.
2954          * As a porting legacy from illumos we have two things to worry
2955          * about.  One is typical for FreeBSD and it is that the vnode is
2956          * not reclaimed (doomed).  The other is that the znode is live.
2957          * The current code can invalidate the znode without acquiring the
2958          * corresponding vnode lock if the object represented by the znode
2959          * and vnode is no longer valid after a rollback or receive operation.
2960          * z_teardown_lock hidden behind ZFS_ENTER and ZFS_EXIT is the lock
2961          * that protects the znodes from the invalidation.
2962          */
2963         zfsvfs = sdzp->z_zfsvfs;
2964         ASSERT3P(zfsvfs, ==, tdzp->z_zfsvfs);
2965         ZFS_ENTER(zfsvfs);
2966
2967         /*
2968          * We can not use ZFS_VERIFY_ZP() here because it could directly return
2969          * bypassing the cleanup code in the case of an error.
2970          */
2971         if (tdzp->z_sa_hdl == NULL || sdzp->z_sa_hdl == NULL) {
2972                 ZFS_EXIT(zfsvfs);
2973                 VOP_UNLOCK1(sdvp);
2974                 VOP_UNLOCK1(tdvp);
2975                 error = SET_ERROR(EIO);
2976                 goto out;
2977         }
2978
2979         /*
2980          * Re-resolve svp to be certain it still exists and fetch the
2981          * correct vnode.
2982          */
2983         error = zfs_dirent_lookup(sdzp, snm, &szp, ZEXISTS);
2984         if (error != 0) {
2985                 /* Source entry invalid or not there. */
2986                 ZFS_EXIT(zfsvfs);
2987                 VOP_UNLOCK1(sdvp);
2988                 VOP_UNLOCK1(tdvp);
2989                 if ((scnp->cn_flags & ISDOTDOT) != 0 ||
2990                     (scnp->cn_namelen == 1 && scnp->cn_nameptr[0] == '.'))
2991                         error = SET_ERROR(EINVAL);
2992                 goto out;
2993         }
2994         svp = ZTOV(szp);
2995
2996         /*
2997          * Re-resolve tvp, if it disappeared we just carry on.
2998          */
2999         error = zfs_dirent_lookup(tdzp, tnm, &tzp, 0);
3000         if (error != 0) {
3001                 ZFS_EXIT(zfsvfs);
3002                 VOP_UNLOCK1(sdvp);
3003                 VOP_UNLOCK1(tdvp);
3004                 vrele(svp);
3005                 if ((tcnp->cn_flags & ISDOTDOT) != 0)
3006                         error = SET_ERROR(EINVAL);
3007                 goto out;
3008         }
3009         if (tzp != NULL)
3010                 tvp = ZTOV(tzp);
3011         else
3012                 tvp = NULL;
3013
3014         /*
3015          * At present the vnode locks must be acquired before z_teardown_lock,
3016          * although it would be more logical to use the opposite order.
3017          */
3018         ZFS_EXIT(zfsvfs);
3019
3020         /*
3021          * Now try acquire locks on svp and tvp.
3022          */
3023         nvp = svp;
3024         error = vn_lock(nvp, LK_EXCLUSIVE | LK_NOWAIT);
3025         if (error != 0) {
3026                 VOP_UNLOCK1(sdvp);
3027                 VOP_UNLOCK1(tdvp);
3028                 if (tvp != NULL)
3029                         vrele(tvp);
3030                 if (error != EBUSY) {
3031                         vrele(nvp);
3032                         goto out;
3033                 }
3034                 error = vn_lock(nvp, LK_EXCLUSIVE);
3035                 if (error != 0) {
3036                         vrele(nvp);
3037                         goto out;
3038                 }
3039                 VOP_UNLOCK1(nvp);
3040                 /*
3041                  * Concurrent rename race.
3042                  * XXX ?
3043                  */
3044                 if (nvp == tdvp) {
3045                         vrele(nvp);
3046                         error = SET_ERROR(EINVAL);
3047                         goto out;
3048                 }
3049                 vrele(*svpp);
3050                 *svpp = nvp;
3051                 goto relock;
3052         }
3053         vrele(*svpp);
3054         *svpp = nvp;
3055
3056         if (*tvpp != NULL)
3057                 vrele(*tvpp);
3058         *tvpp = NULL;
3059         if (tvp != NULL) {
3060                 nvp = tvp;
3061                 error = vn_lock(nvp, LK_EXCLUSIVE | LK_NOWAIT);
3062                 if (error != 0) {
3063                         VOP_UNLOCK1(sdvp);
3064                         VOP_UNLOCK1(tdvp);
3065                         VOP_UNLOCK1(*svpp);
3066                         if (error != EBUSY) {
3067                                 vrele(nvp);
3068                                 goto out;
3069                         }
3070                         error = vn_lock(nvp, LK_EXCLUSIVE);
3071                         if (error != 0) {
3072                                 vrele(nvp);
3073                                 goto out;
3074                         }
3075                         vput(nvp);
3076                         goto relock;
3077                 }
3078                 *tvpp = nvp;
3079         }
3080
3081         return (0);
3082
3083 out:
3084         return (error);
3085 }
3086
3087 /*
3088  * Note that we must use VRELE_ASYNC in this function as it walks
3089  * up the directory tree and vrele may need to acquire an exclusive
3090  * lock if a last reference to a vnode is dropped.
3091  */
3092 static int
3093 zfs_rename_check(znode_t *szp, znode_t *sdzp, znode_t *tdzp)
3094 {
3095         zfsvfs_t        *zfsvfs;
3096         znode_t         *zp, *zp1;
3097         uint64_t        parent;
3098         int             error;
3099
3100         zfsvfs = tdzp->z_zfsvfs;
3101         if (tdzp == szp)
3102                 return (SET_ERROR(EINVAL));
3103         if (tdzp == sdzp)
3104                 return (0);
3105         if (tdzp->z_id == zfsvfs->z_root)
3106                 return (0);
3107         zp = tdzp;
3108         for (;;) {
3109                 ASSERT(!zp->z_unlinked);
3110                 if ((error = sa_lookup(zp->z_sa_hdl,
3111                     SA_ZPL_PARENT(zfsvfs), &parent, sizeof (parent))) != 0)
3112                         break;
3113
3114                 if (parent == szp->z_id) {
3115                         error = SET_ERROR(EINVAL);
3116                         break;
3117                 }
3118                 if (parent == zfsvfs->z_root)
3119                         break;
3120                 if (parent == sdzp->z_id)
3121                         break;
3122
3123                 error = zfs_zget(zfsvfs, parent, &zp1);
3124                 if (error != 0)
3125                         break;
3126
3127                 if (zp != tdzp)
3128                         VN_RELE_ASYNC(ZTOV(zp),
3129                             dsl_pool_zrele_taskq(
3130                             dmu_objset_pool(zfsvfs->z_os)));
3131                 zp = zp1;
3132         }
3133
3134         if (error == ENOTDIR)
3135                 panic("checkpath: .. not a directory\n");
3136         if (zp != tdzp)
3137                 VN_RELE_ASYNC(ZTOV(zp),
3138                     dsl_pool_zrele_taskq(dmu_objset_pool(zfsvfs->z_os)));
3139         return (error);
3140 }
3141
3142 #if     __FreeBSD_version < 1300124
3143 static void
3144 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
3145     struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
3146 {
3147
3148         cache_purge(fvp);
3149         if (tvp != NULL)
3150                 cache_purge(tvp);
3151         cache_purge_negative(tdvp);
3152 }
3153 #endif
3154
3155 /*
3156  * Move an entry from the provided source directory to the target
3157  * directory.  Change the entry name as indicated.
3158  *
3159  *      IN:     sdvp    - Source directory containing the "old entry".
3160  *              snm     - Old entry name.
3161  *              tdvp    - Target directory to contain the "new entry".
3162  *              tnm     - New entry name.
3163  *              cr      - credentials of caller.
3164  *              ct      - caller context
3165  *              flags   - case flags
3166  *
3167  *      RETURN: 0 on success, error code on failure.
3168  *
3169  * Timestamps:
3170  *      sdvp,tdvp - ctime|mtime updated
3171  */
3172 /*ARGSUSED*/
3173 static int
3174 zfs_rename_(vnode_t *sdvp, vnode_t **svpp, struct componentname *scnp,
3175     vnode_t *tdvp, vnode_t **tvpp, struct componentname *tcnp,
3176     cred_t *cr, int log)
3177 {
3178         zfsvfs_t        *zfsvfs;
3179         znode_t         *sdzp, *tdzp, *szp, *tzp;
3180         zilog_t         *zilog = NULL;
3181         dmu_tx_t        *tx;
3182         const char      *snm = scnp->cn_nameptr;
3183         const char      *tnm = tcnp->cn_nameptr;
3184         int             error = 0;
3185         bool    want_seqc_end __maybe_unused = false;
3186
3187         /* Reject renames across filesystems. */
3188         if ((*svpp)->v_mount != tdvp->v_mount ||
3189             ((*tvpp) != NULL && (*svpp)->v_mount != (*tvpp)->v_mount)) {
3190                 error = SET_ERROR(EXDEV);
3191                 goto out;
3192         }
3193
3194         if (zfsctl_is_node(tdvp)) {
3195                 error = SET_ERROR(EXDEV);
3196                 goto out;
3197         }
3198
3199         /*
3200          * Lock all four vnodes to ensure safety and semantics of renaming.
3201          */
3202         error = zfs_rename_relock(sdvp, svpp, tdvp, tvpp, scnp, tcnp);
3203         if (error != 0) {
3204                 /* no vnodes are locked in the case of error here */
3205                 return (error);
3206         }
3207
3208         tdzp = VTOZ(tdvp);
3209         sdzp = VTOZ(sdvp);
3210         zfsvfs = tdzp->z_zfsvfs;
3211         zilog = zfsvfs->z_log;
3212
3213         /*
3214          * After we re-enter ZFS_ENTER() we will have to revalidate all
3215          * znodes involved.
3216          */
3217         ZFS_ENTER(zfsvfs);
3218
3219         if (zfsvfs->z_utf8 && u8_validate(tnm,
3220             strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3221                 error = SET_ERROR(EILSEQ);
3222                 goto unlockout;
3223         }
3224
3225         /* If source and target are the same file, there is nothing to do. */
3226         if ((*svpp) == (*tvpp)) {
3227                 error = 0;
3228                 goto unlockout;
3229         }
3230
3231         if (((*svpp)->v_type == VDIR && (*svpp)->v_mountedhere != NULL) ||
3232             ((*tvpp) != NULL && (*tvpp)->v_type == VDIR &&
3233             (*tvpp)->v_mountedhere != NULL)) {
3234                 error = SET_ERROR(EXDEV);
3235                 goto unlockout;
3236         }
3237
3238         /*
3239          * We can not use ZFS_VERIFY_ZP() here because it could directly return
3240          * bypassing the cleanup code in the case of an error.
3241          */
3242         if (tdzp->z_sa_hdl == NULL || sdzp->z_sa_hdl == NULL) {
3243                 error = SET_ERROR(EIO);
3244                 goto unlockout;
3245         }
3246
3247         szp = VTOZ(*svpp);
3248         tzp = *tvpp == NULL ? NULL : VTOZ(*tvpp);
3249         if (szp->z_sa_hdl == NULL || (tzp != NULL && tzp->z_sa_hdl == NULL)) {
3250                 error = SET_ERROR(EIO);
3251                 goto unlockout;
3252         }
3253
3254         /*
3255          * This is to prevent the creation of links into attribute space
3256          * by renaming a linked file into/outof an attribute directory.
3257          * See the comment in zfs_link() for why this is considered bad.
3258          */
3259         if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3260                 error = SET_ERROR(EINVAL);
3261                 goto unlockout;
3262         }
3263
3264         /*
3265          * If we are using project inheritance, means if the directory has
3266          * ZFS_PROJINHERIT set, then its descendant directories will inherit
3267          * not only the project ID, but also the ZFS_PROJINHERIT flag. Under
3268          * such case, we only allow renames into our tree when the project
3269          * IDs are the same.
3270          */
3271         if (tdzp->z_pflags & ZFS_PROJINHERIT &&
3272             tdzp->z_projid != szp->z_projid) {
3273                 error = SET_ERROR(EXDEV);
3274                 goto unlockout;
3275         }
3276
3277         /*
3278          * Must have write access at the source to remove the old entry
3279          * and write access at the target to create the new entry.
3280          * Note that if target and source are the same, this can be
3281          * done in a single check.
3282          */
3283         if ((error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr)))
3284                 goto unlockout;
3285
3286         if ((*svpp)->v_type == VDIR) {
3287                 /*
3288                  * Avoid ".", "..", and aliases of "." for obvious reasons.
3289                  */
3290                 if ((scnp->cn_namelen == 1 && scnp->cn_nameptr[0] == '.') ||
3291                     sdzp == szp ||
3292                     (scnp->cn_flags | tcnp->cn_flags) & ISDOTDOT) {
3293                         error = EINVAL;
3294                         goto unlockout;
3295                 }
3296
3297                 /*
3298                  * Check to make sure rename is valid.
3299                  * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3300                  */
3301                 if ((error = zfs_rename_check(szp, sdzp, tdzp)))
3302                         goto unlockout;
3303         }
3304
3305         /*
3306          * Does target exist?
3307          */
3308         if (tzp) {
3309                 /*
3310                  * Source and target must be the same type.
3311                  */
3312                 if ((*svpp)->v_type == VDIR) {
3313                         if ((*tvpp)->v_type != VDIR) {
3314                                 error = SET_ERROR(ENOTDIR);
3315                                 goto unlockout;
3316                         } else {
3317                                 cache_purge(tdvp);
3318                                 if (sdvp != tdvp)
3319                                         cache_purge(sdvp);
3320                         }
3321                 } else {
3322                         if ((*tvpp)->v_type == VDIR) {
3323                                 error = SET_ERROR(EISDIR);
3324                                 goto unlockout;
3325                         }
3326                 }
3327         }
3328
3329         vn_seqc_write_begin(*svpp);
3330         vn_seqc_write_begin(sdvp);
3331         if (*tvpp != NULL)
3332                 vn_seqc_write_begin(*tvpp);
3333         if (tdvp != *tvpp)
3334                 vn_seqc_write_begin(tdvp);
3335 #if     __FreeBSD_version >= 1300102
3336         want_seqc_end = true;
3337 #endif
3338         vnevent_rename_src(*svpp, sdvp, scnp->cn_nameptr, ct);
3339         if (tzp)
3340                 vnevent_rename_dest(*tvpp, tdvp, tnm, ct);
3341
3342         /*
3343          * notify the target directory if it is not the same
3344          * as source directory.
3345          */
3346         if (tdvp != sdvp) {
3347                 vnevent_rename_dest_dir(tdvp, ct);
3348         }
3349
3350         tx = dmu_tx_create(zfsvfs->z_os);
3351         dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3352         dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
3353         dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3354         dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3355         if (sdzp != tdzp) {
3356                 dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, B_FALSE);
3357                 zfs_sa_upgrade_txholds(tx, tdzp);
3358         }
3359         if (tzp) {
3360                 dmu_tx_hold_sa(tx, tzp->z_sa_hdl, B_FALSE);
3361                 zfs_sa_upgrade_txholds(tx, tzp);
3362         }
3363
3364         zfs_sa_upgrade_txholds(tx, szp);
3365         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3366         error = dmu_tx_assign(tx, TXG_WAIT);
3367         if (error) {
3368                 dmu_tx_abort(tx);
3369                 goto unlockout;
3370         }
3371
3372
3373         if (tzp)        /* Attempt to remove the existing target */
3374                 error = zfs_link_destroy(tdzp, tnm, tzp, tx, 0, NULL);
3375
3376         if (error == 0) {
3377                 error = zfs_link_create(tdzp, tnm, szp, tx, ZRENAMING);
3378                 if (error == 0) {
3379                         szp->z_pflags |= ZFS_AV_MODIFIED;
3380
3381                         error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
3382                             (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3383                         ASSERT0(error);
3384
3385                         error = zfs_link_destroy(sdzp, snm, szp, tx, ZRENAMING,
3386                             NULL);
3387                         if (error == 0) {
3388                                 zfs_log_rename(zilog, tx, TX_RENAME, sdzp,
3389                                     snm, tdzp, tnm, szp);
3390
3391                                 /*
3392                                  * Update path information for the target vnode
3393                                  */
3394                                 vn_renamepath(tdvp, *svpp, tnm, strlen(tnm));
3395                         } else {
3396                                 /*
3397                                  * At this point, we have successfully created
3398                                  * the target name, but have failed to remove
3399                                  * the source name.  Since the create was done
3400                                  * with the ZRENAMING flag, there are
3401                                  * complications; for one, the link count is
3402                                  * wrong.  The easiest way to deal with this
3403                                  * is to remove the newly created target, and
3404                                  * return the original error.  This must
3405                                  * succeed; fortunately, it is very unlikely to
3406                                  * fail, since we just created it.
3407                                  */
3408                                 VERIFY3U(zfs_link_destroy(tdzp, tnm, szp, tx,
3409                                     ZRENAMING, NULL), ==, 0);
3410                         }
3411                 }
3412                 if (error == 0) {
3413                         cache_vop_rename(sdvp, *svpp, tdvp, *tvpp, scnp, tcnp);
3414                 }
3415         }
3416
3417         dmu_tx_commit(tx);
3418
3419 unlockout:                      /* all 4 vnodes are locked, ZFS_ENTER called */
3420         ZFS_EXIT(zfsvfs);
3421         if (want_seqc_end) {
3422                 vn_seqc_write_end(*svpp);
3423                 vn_seqc_write_end(sdvp);
3424                 if (*tvpp != NULL)
3425                         vn_seqc_write_end(*tvpp);
3426                 if (tdvp != *tvpp)
3427                         vn_seqc_write_end(tdvp);
3428                 want_seqc_end = false;
3429         }
3430         VOP_UNLOCK1(*svpp);
3431         VOP_UNLOCK1(sdvp);
3432
3433 out:                            /* original two vnodes are locked */
3434         MPASS(!want_seqc_end);
3435         if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3436                 zil_commit(zilog, 0);
3437
3438         if (*tvpp != NULL)
3439                 VOP_UNLOCK1(*tvpp);
3440         if (tdvp != *tvpp)
3441                 VOP_UNLOCK1(tdvp);
3442         return (error);
3443 }
3444
3445 int
3446 zfs_rename(znode_t *sdzp, const char *sname, znode_t *tdzp, const char *tname,
3447     cred_t *cr, int flags)
3448 {
3449         struct componentname scn, tcn;
3450         vnode_t *sdvp, *tdvp;
3451         vnode_t *svp, *tvp;
3452         int error;
3453         svp = tvp = NULL;
3454
3455         sdvp = ZTOV(sdzp);
3456         tdvp = ZTOV(tdzp);
3457         error = zfs_lookup_internal(sdzp, sname, &svp, &scn, DELETE);
3458         if (sdzp->z_zfsvfs->z_replay == B_FALSE)
3459                 VOP_UNLOCK1(sdvp);
3460         if (error != 0)
3461                 goto fail;
3462         VOP_UNLOCK1(svp);
3463
3464         vn_lock(tdvp, LK_EXCLUSIVE | LK_RETRY);
3465         error = zfs_lookup_internal(tdzp, tname, &tvp, &tcn, RENAME);
3466         if (error == EJUSTRETURN)
3467                 tvp = NULL;
3468         else if (error != 0) {
3469                 VOP_UNLOCK1(tdvp);
3470                 goto fail;
3471         }
3472
3473         error = zfs_rename_(sdvp, &svp, &scn, tdvp, &tvp, &tcn, cr, 0);
3474 fail:
3475         if (svp != NULL)
3476                 vrele(svp);
3477         if (tvp != NULL)
3478                 vrele(tvp);
3479
3480         return (error);
3481 }
3482
3483 /*
3484  * Insert the indicated symbolic reference entry into the directory.
3485  *
3486  *      IN:     dvp     - Directory to contain new symbolic link.
3487  *              link    - Name for new symlink entry.
3488  *              vap     - Attributes of new entry.
3489  *              cr      - credentials of caller.
3490  *              ct      - caller context
3491  *              flags   - case flags
3492  *
3493  *      RETURN: 0 on success, error code on failure.
3494  *
3495  * Timestamps:
3496  *      dvp - ctime|mtime updated
3497  */
3498 /*ARGSUSED*/
3499 int
3500 zfs_symlink(znode_t *dzp, const char *name, vattr_t *vap,
3501     const char *link, znode_t **zpp, cred_t *cr, int flags)
3502 {
3503         znode_t         *zp;
3504         dmu_tx_t        *tx;
3505         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
3506         zilog_t         *zilog;
3507         uint64_t        len = strlen(link);
3508         int             error;
3509         zfs_acl_ids_t   acl_ids;
3510         boolean_t       fuid_dirtied;
3511         uint64_t        txtype = TX_SYMLINK;
3512
3513         ASSERT(vap->va_type == VLNK);
3514
3515         ZFS_ENTER(zfsvfs);
3516         ZFS_VERIFY_ZP(dzp);
3517         zilog = zfsvfs->z_log;
3518
3519         if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
3520             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3521                 ZFS_EXIT(zfsvfs);
3522                 return (SET_ERROR(EILSEQ));
3523         }
3524
3525         if (len > MAXPATHLEN) {
3526                 ZFS_EXIT(zfsvfs);
3527                 return (SET_ERROR(ENAMETOOLONG));
3528         }
3529
3530         if ((error = zfs_acl_ids_create(dzp, 0,
3531             vap, cr, NULL, &acl_ids)) != 0) {
3532                 ZFS_EXIT(zfsvfs);
3533                 return (error);
3534         }
3535
3536         /*
3537          * Attempt to lock directory; fail if entry already exists.
3538          */
3539         error = zfs_dirent_lookup(dzp, name, &zp, ZNEW);
3540         if (error) {
3541                 zfs_acl_ids_free(&acl_ids);
3542                 ZFS_EXIT(zfsvfs);
3543                 return (error);
3544         }
3545
3546         if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr))) {
3547                 zfs_acl_ids_free(&acl_ids);
3548                 ZFS_EXIT(zfsvfs);
3549                 return (error);
3550         }
3551
3552         if (zfs_acl_ids_overquota(zfsvfs, &acl_ids,
3553             0 /* projid */)) {
3554                 zfs_acl_ids_free(&acl_ids);
3555                 ZFS_EXIT(zfsvfs);
3556                 return (SET_ERROR(EDQUOT));
3557         }
3558
3559         getnewvnode_reserve_();
3560         tx = dmu_tx_create(zfsvfs->z_os);
3561         fuid_dirtied = zfsvfs->z_fuid_dirty;
3562         dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3563         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3564         dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
3565             ZFS_SA_BASE_ATTR_SIZE + len);
3566         dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
3567         if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3568                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3569                     acl_ids.z_aclp->z_acl_bytes);
3570         }
3571         if (fuid_dirtied)
3572                 zfs_fuid_txhold(zfsvfs, tx);
3573         error = dmu_tx_assign(tx, TXG_WAIT);
3574         if (error) {
3575                 zfs_acl_ids_free(&acl_ids);
3576                 dmu_tx_abort(tx);
3577                 getnewvnode_drop_reserve();
3578                 ZFS_EXIT(zfsvfs);
3579                 return (error);
3580         }
3581
3582         /*
3583          * Create a new object for the symlink.
3584          * for version 4 ZPL datsets the symlink will be an SA attribute
3585          */
3586         zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
3587
3588         if (fuid_dirtied)
3589                 zfs_fuid_sync(zfsvfs, tx);
3590
3591         if (zp->z_is_sa)
3592                 error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs),
3593                     __DECONST(void *, link), len, tx);
3594         else
3595                 zfs_sa_symlink(zp, __DECONST(char *, link), len, tx);
3596
3597         zp->z_size = len;
3598         (void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
3599             &zp->z_size, sizeof (zp->z_size), tx);
3600         /*
3601          * Insert the new object into the directory.
3602          */
3603         (void) zfs_link_create(dzp, name, zp, tx, ZNEW);
3604
3605         zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3606         *zpp = zp;
3607
3608         zfs_acl_ids_free(&acl_ids);
3609
3610         dmu_tx_commit(tx);
3611
3612         getnewvnode_drop_reserve();
3613
3614         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3615                 zil_commit(zilog, 0);
3616
3617         ZFS_EXIT(zfsvfs);
3618         return (error);
3619 }
3620
3621 /*
3622  * Return, in the buffer contained in the provided uio structure,
3623  * the symbolic path referred to by vp.
3624  *
3625  *      IN:     vp      - vnode of symbolic link.
3626  *              uio     - structure to contain the link path.
3627  *              cr      - credentials of caller.
3628  *              ct      - caller context
3629  *
3630  *      OUT:    uio     - structure containing the link path.
3631  *
3632  *      RETURN: 0 on success, error code on failure.
3633  *
3634  * Timestamps:
3635  *      vp - atime updated
3636  */
3637 /* ARGSUSED */
3638 static int
3639 zfs_readlink(vnode_t *vp, zfs_uio_t *uio, cred_t *cr, caller_context_t *ct)
3640 {
3641         znode_t         *zp = VTOZ(vp);
3642         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
3643         int             error;
3644
3645         ZFS_ENTER(zfsvfs);
3646         ZFS_VERIFY_ZP(zp);
3647
3648         if (zp->z_is_sa)
3649                 error = sa_lookup_uio(zp->z_sa_hdl,
3650                     SA_ZPL_SYMLINK(zfsvfs), uio);
3651         else
3652                 error = zfs_sa_readlink(zp, uio);
3653
3654         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
3655
3656         ZFS_EXIT(zfsvfs);
3657         return (error);
3658 }
3659
3660 /*
3661  * Insert a new entry into directory tdvp referencing svp.
3662  *
3663  *      IN:     tdvp    - Directory to contain new entry.
3664  *              svp     - vnode of new entry.
3665  *              name    - name of new entry.
3666  *              cr      - credentials of caller.
3667  *
3668  *      RETURN: 0 on success, error code on failure.
3669  *
3670  * Timestamps:
3671  *      tdvp - ctime|mtime updated
3672  *       svp - ctime updated
3673  */
3674 /* ARGSUSED */
3675 int
3676 zfs_link(znode_t *tdzp, znode_t *szp, const char *name, cred_t *cr,
3677     int flags)
3678 {
3679         znode_t         *tzp;
3680         zfsvfs_t        *zfsvfs = tdzp->z_zfsvfs;
3681         zilog_t         *zilog;
3682         dmu_tx_t        *tx;
3683         int             error;
3684         uint64_t        parent;
3685         uid_t           owner;
3686
3687         ASSERT(ZTOV(tdzp)->v_type == VDIR);
3688
3689         ZFS_ENTER(zfsvfs);
3690         ZFS_VERIFY_ZP(tdzp);
3691         zilog = zfsvfs->z_log;
3692
3693         /*
3694          * POSIX dictates that we return EPERM here.
3695          * Better choices include ENOTSUP or EISDIR.
3696          */
3697         if (ZTOV(szp)->v_type == VDIR) {
3698                 ZFS_EXIT(zfsvfs);
3699                 return (SET_ERROR(EPERM));
3700         }
3701
3702         ZFS_VERIFY_ZP(szp);
3703
3704         /*
3705          * If we are using project inheritance, means if the directory has
3706          * ZFS_PROJINHERIT set, then its descendant directories will inherit
3707          * not only the project ID, but also the ZFS_PROJINHERIT flag. Under
3708          * such case, we only allow hard link creation in our tree when the
3709          * project IDs are the same.
3710          */
3711         if (tdzp->z_pflags & ZFS_PROJINHERIT &&
3712             tdzp->z_projid != szp->z_projid) {
3713                 ZFS_EXIT(zfsvfs);
3714                 return (SET_ERROR(EXDEV));
3715         }
3716
3717         if (szp->z_pflags & (ZFS_APPENDONLY |
3718             ZFS_IMMUTABLE | ZFS_READONLY)) {
3719                 ZFS_EXIT(zfsvfs);
3720                 return (SET_ERROR(EPERM));
3721         }
3722
3723         /* Prevent links to .zfs/shares files */
3724
3725         if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
3726             &parent, sizeof (uint64_t))) != 0) {
3727                 ZFS_EXIT(zfsvfs);
3728                 return (error);
3729         }
3730         if (parent == zfsvfs->z_shares_dir) {
3731                 ZFS_EXIT(zfsvfs);
3732                 return (SET_ERROR(EPERM));
3733         }
3734
3735         if (zfsvfs->z_utf8 && u8_validate(name,
3736             strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3737                 ZFS_EXIT(zfsvfs);
3738                 return (SET_ERROR(EILSEQ));
3739         }
3740
3741         /*
3742          * We do not support links between attributes and non-attributes
3743          * because of the potential security risk of creating links
3744          * into "normal" file space in order to circumvent restrictions
3745          * imposed in attribute space.
3746          */
3747         if ((szp->z_pflags & ZFS_XATTR) != (tdzp->z_pflags & ZFS_XATTR)) {
3748                 ZFS_EXIT(zfsvfs);
3749                 return (SET_ERROR(EINVAL));
3750         }
3751
3752
3753         owner = zfs_fuid_map_id(zfsvfs, szp->z_uid, cr, ZFS_OWNER);
3754         if (owner != crgetuid(cr) && secpolicy_basic_link(ZTOV(szp), cr) != 0) {
3755                 ZFS_EXIT(zfsvfs);
3756                 return (SET_ERROR(EPERM));
3757         }
3758
3759         if ((error = zfs_zaccess(tdzp, ACE_ADD_FILE, 0, B_FALSE, cr))) {
3760                 ZFS_EXIT(zfsvfs);
3761                 return (error);
3762         }
3763
3764         /*
3765          * Attempt to lock directory; fail if entry already exists.
3766          */
3767         error = zfs_dirent_lookup(tdzp, name, &tzp, ZNEW);
3768         if (error) {
3769                 ZFS_EXIT(zfsvfs);
3770                 return (error);
3771         }
3772
3773         tx = dmu_tx_create(zfsvfs->z_os);
3774         dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3775         dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, name);
3776         zfs_sa_upgrade_txholds(tx, szp);
3777         zfs_sa_upgrade_txholds(tx, tdzp);
3778         error = dmu_tx_assign(tx, TXG_WAIT);
3779         if (error) {
3780                 dmu_tx_abort(tx);
3781                 ZFS_EXIT(zfsvfs);
3782                 return (error);
3783         }
3784
3785         error = zfs_link_create(tdzp, name, szp, tx, 0);
3786
3787         if (error == 0) {
3788                 uint64_t txtype = TX_LINK;
3789                 zfs_log_link(zilog, tx, txtype, tdzp, szp, name);
3790         }
3791
3792         dmu_tx_commit(tx);
3793
3794         if (error == 0) {
3795                 vnevent_link(ZTOV(szp), ct);
3796         }
3797
3798         if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3799                 zil_commit(zilog, 0);
3800
3801         ZFS_EXIT(zfsvfs);
3802         return (error);
3803 }
3804
3805 /*
3806  * Free or allocate space in a file.  Currently, this function only
3807  * supports the `F_FREESP' command.  However, this command is somewhat
3808  * misnamed, as its functionality includes the ability to allocate as
3809  * well as free space.
3810  *
3811  *      IN:     ip      - inode of file to free data in.
3812  *              cmd     - action to take (only F_FREESP supported).
3813  *              bfp     - section of file to free/alloc.
3814  *              flag    - current file open mode flags.
3815  *              offset  - current file offset.
3816  *              cr      - credentials of caller.
3817  *
3818  *      RETURN: 0 on success, error code on failure.
3819  *
3820  * Timestamps:
3821  *      ip - ctime|mtime updated
3822  */
3823 /* ARGSUSED */
3824 int
3825 zfs_space(znode_t *zp, int cmd, flock64_t *bfp, int flag,
3826     offset_t offset, cred_t *cr)
3827 {
3828         zfsvfs_t        *zfsvfs = ZTOZSB(zp);
3829         uint64_t        off, len;
3830         int             error;
3831
3832         ZFS_ENTER(zfsvfs);
3833         ZFS_VERIFY_ZP(zp);
3834
3835         if (cmd != F_FREESP) {
3836                 ZFS_EXIT(zfsvfs);
3837                 return (SET_ERROR(EINVAL));
3838         }
3839
3840         /*
3841          * Callers might not be able to detect properly that we are read-only,
3842          * so check it explicitly here.
3843          */
3844         if (zfs_is_readonly(zfsvfs)) {
3845                 ZFS_EXIT(zfsvfs);
3846                 return (SET_ERROR(EROFS));
3847         }
3848
3849         if (bfp->l_len < 0) {
3850                 ZFS_EXIT(zfsvfs);
3851                 return (SET_ERROR(EINVAL));
3852         }
3853
3854         /*
3855          * Permissions aren't checked on Solaris because on this OS
3856          * zfs_space() can only be called with an opened file handle.
3857          * On Linux we can get here through truncate_range() which
3858          * operates directly on inodes, so we need to check access rights.
3859          */
3860         if ((error = zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr))) {
3861                 ZFS_EXIT(zfsvfs);
3862                 return (error);
3863         }
3864
3865         off = bfp->l_start;
3866         len = bfp->l_len; /* 0 means from off to end of file */
3867
3868         error = zfs_freesp(zp, off, len, flag, TRUE);
3869
3870         ZFS_EXIT(zfsvfs);
3871         return (error);
3872 }
3873
3874 /*ARGSUSED*/
3875 static void
3876 zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
3877 {
3878         znode_t *zp = VTOZ(vp);
3879         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3880         int error;
3881
3882         ZFS_RLOCK_TEARDOWN_INACTIVE(zfsvfs);
3883         if (zp->z_sa_hdl == NULL) {
3884                 /*
3885                  * The fs has been unmounted, or we did a
3886                  * suspend/resume and this file no longer exists.
3887                  */
3888                 ZFS_RUNLOCK_TEARDOWN_INACTIVE(zfsvfs);
3889                 vrecycle(vp);
3890                 return;
3891         }
3892
3893         if (zp->z_unlinked) {
3894                 /*
3895                  * Fast path to recycle a vnode of a removed file.
3896                  */
3897                 ZFS_RUNLOCK_TEARDOWN_INACTIVE(zfsvfs);
3898                 vrecycle(vp);
3899                 return;
3900         }
3901
3902         if (zp->z_atime_dirty && zp->z_unlinked == 0) {
3903                 dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
3904
3905                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3906                 zfs_sa_upgrade_txholds(tx, zp);
3907                 error = dmu_tx_assign(tx, TXG_WAIT);
3908                 if (error) {
3909                         dmu_tx_abort(tx);
3910                 } else {
3911                         (void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zfsvfs),
3912                             (void *)&zp->z_atime, sizeof (zp->z_atime), tx);
3913                         zp->z_atime_dirty = 0;
3914                         dmu_tx_commit(tx);
3915                 }
3916         }
3917         ZFS_RUNLOCK_TEARDOWN_INACTIVE(zfsvfs);
3918 }
3919
3920
3921 CTASSERT(sizeof (struct zfid_short) <= sizeof (struct fid));
3922 CTASSERT(sizeof (struct zfid_long) <= sizeof (struct fid));
3923
3924 /*ARGSUSED*/
3925 static int
3926 zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
3927 {
3928         znode_t         *zp = VTOZ(vp);
3929         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
3930         uint32_t        gen;
3931         uint64_t        gen64;
3932         uint64_t        object = zp->z_id;
3933         zfid_short_t    *zfid;
3934         int             size, i, error;
3935
3936         ZFS_ENTER(zfsvfs);
3937         ZFS_VERIFY_ZP(zp);
3938
3939         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs),
3940             &gen64, sizeof (uint64_t))) != 0) {
3941                 ZFS_EXIT(zfsvfs);
3942                 return (error);
3943         }
3944
3945         gen = (uint32_t)gen64;
3946
3947         size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
3948         fidp->fid_len = size;
3949
3950         zfid = (zfid_short_t *)fidp;
3951
3952         zfid->zf_len = size;
3953
3954         for (i = 0; i < sizeof (zfid->zf_object); i++)
3955                 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
3956
3957         /* Must have a non-zero generation number to distinguish from .zfs */
3958         if (gen == 0)
3959                 gen = 1;
3960         for (i = 0; i < sizeof (zfid->zf_gen); i++)
3961                 zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
3962
3963         if (size == LONG_FID_LEN) {
3964                 uint64_t        objsetid = dmu_objset_id(zfsvfs->z_os);
3965                 zfid_long_t     *zlfid;
3966
3967                 zlfid = (zfid_long_t *)fidp;
3968
3969                 for (i = 0; i < sizeof (zlfid->zf_setid); i++)
3970                         zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
3971
3972                 /* XXX - this should be the generation number for the objset */
3973                 for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
3974                         zlfid->zf_setgen[i] = 0;
3975         }
3976
3977         ZFS_EXIT(zfsvfs);
3978         return (0);
3979 }
3980
3981 static int
3982 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
3983     caller_context_t *ct)
3984 {
3985         znode_t *zp;
3986         zfsvfs_t *zfsvfs;
3987
3988         switch (cmd) {
3989         case _PC_LINK_MAX:
3990                 *valp = MIN(LONG_MAX, ZFS_LINK_MAX);
3991                 return (0);
3992
3993         case _PC_FILESIZEBITS:
3994                 *valp = 64;
3995                 return (0);
3996         case _PC_MIN_HOLE_SIZE:
3997                 *valp = (int)SPA_MINBLOCKSIZE;
3998                 return (0);
3999         case _PC_ACL_EXTENDED:
4000 #if 0           /* POSIX ACLs are not implemented for ZFS on FreeBSD yet. */
4001                 zp = VTOZ(vp);
4002                 zfsvfs = zp->z_zfsvfs;
4003                 ZFS_ENTER(zfsvfs);
4004                 ZFS_VERIFY_ZP(zp);
4005                 *valp = zfsvfs->z_acl_type == ZFSACLTYPE_POSIX ? 1 : 0;
4006                 ZFS_EXIT(zfsvfs);
4007 #else
4008                 *valp = 0;
4009 #endif
4010                 return (0);
4011
4012         case _PC_ACL_NFS4:
4013                 zp = VTOZ(vp);
4014                 zfsvfs = zp->z_zfsvfs;
4015                 ZFS_ENTER(zfsvfs);
4016                 ZFS_VERIFY_ZP(zp);
4017                 *valp = zfsvfs->z_acl_type == ZFS_ACLTYPE_NFSV4 ? 1 : 0;
4018                 ZFS_EXIT(zfsvfs);
4019                 return (0);
4020
4021         case _PC_ACL_PATH_MAX:
4022                 *valp = ACL_MAX_ENTRIES;
4023                 return (0);
4024
4025         default:
4026                 return (EOPNOTSUPP);
4027         }
4028 }
4029
4030 static int
4031 zfs_getpages(struct vnode *vp, vm_page_t *ma, int count, int *rbehind,
4032     int *rahead)
4033 {
4034         znode_t *zp = VTOZ(vp);
4035         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4036         objset_t *os = zp->z_zfsvfs->z_os;
4037         zfs_locked_range_t *lr;
4038         vm_object_t object;
4039         off_t start, end, obj_size;
4040         uint_t blksz;
4041         int pgsin_b, pgsin_a;
4042         int error;
4043
4044         ZFS_ENTER(zfsvfs);
4045         ZFS_VERIFY_ZP(zp);
4046
4047         start = IDX_TO_OFF(ma[0]->pindex);
4048         end = IDX_TO_OFF(ma[count - 1]->pindex + 1);
4049
4050         /*
4051          * Lock a range covering all required and optional pages.
4052          * Note that we need to handle the case of the block size growing.
4053          */
4054         for (;;) {
4055                 blksz = zp->z_blksz;
4056                 lr = zfs_rangelock_tryenter(&zp->z_rangelock,
4057                     rounddown(start, blksz),
4058                     roundup(end, blksz) - rounddown(start, blksz), RL_READER);
4059                 if (lr == NULL) {
4060                         if (rahead != NULL) {
4061                                 *rahead = 0;
4062                                 rahead = NULL;
4063                         }
4064                         if (rbehind != NULL) {
4065                                 *rbehind = 0;
4066                                 rbehind = NULL;
4067                         }
4068                         break;
4069                 }
4070                 if (blksz == zp->z_blksz)
4071                         break;
4072                 zfs_rangelock_exit(lr);
4073         }
4074
4075         object = ma[0]->object;
4076         zfs_vmobject_wlock(object);
4077         obj_size = object->un_pager.vnp.vnp_size;
4078         zfs_vmobject_wunlock(object);
4079         if (IDX_TO_OFF(ma[count - 1]->pindex) >= obj_size) {
4080                 if (lr != NULL)
4081                         zfs_rangelock_exit(lr);
4082                 ZFS_EXIT(zfsvfs);
4083                 return (zfs_vm_pagerret_bad);
4084         }
4085
4086         pgsin_b = 0;
4087         if (rbehind != NULL) {
4088                 pgsin_b = OFF_TO_IDX(start - rounddown(start, blksz));
4089                 pgsin_b = MIN(*rbehind, pgsin_b);
4090         }
4091
4092         pgsin_a = 0;
4093         if (rahead != NULL) {
4094                 pgsin_a = OFF_TO_IDX(roundup(end, blksz) - end);
4095                 if (end + IDX_TO_OFF(pgsin_a) >= obj_size)
4096                         pgsin_a = OFF_TO_IDX(round_page(obj_size) - end);
4097                 pgsin_a = MIN(*rahead, pgsin_a);
4098         }
4099
4100         /*
4101          * NB: we need to pass the exact byte size of the data that we expect
4102          * to read after accounting for the file size.  This is required because
4103          * ZFS will panic if we request DMU to read beyond the end of the last
4104          * allocated block.
4105          */
4106         error = dmu_read_pages(os, zp->z_id, ma, count, &pgsin_b, &pgsin_a,
4107             MIN(end, obj_size) - (end - PAGE_SIZE));
4108
4109         if (lr != NULL)
4110                 zfs_rangelock_exit(lr);
4111         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4112         ZFS_EXIT(zfsvfs);
4113
4114         if (error != 0)
4115                 return (zfs_vm_pagerret_error);
4116
4117         VM_CNT_INC(v_vnodein);
4118         VM_CNT_ADD(v_vnodepgsin, count + pgsin_b + pgsin_a);
4119         if (rbehind != NULL)
4120                 *rbehind = pgsin_b;
4121         if (rahead != NULL)
4122                 *rahead = pgsin_a;
4123         return (zfs_vm_pagerret_ok);
4124 }
4125
4126 #ifndef _SYS_SYSPROTO_H_
4127 struct vop_getpages_args {
4128         struct vnode *a_vp;
4129         vm_page_t *a_m;
4130         int a_count;
4131         int *a_rbehind;
4132         int *a_rahead;
4133 };
4134 #endif
4135
4136 static int
4137 zfs_freebsd_getpages(struct vop_getpages_args *ap)
4138 {
4139
4140         return (zfs_getpages(ap->a_vp, ap->a_m, ap->a_count, ap->a_rbehind,
4141             ap->a_rahead));
4142 }
4143
4144 static int
4145 zfs_putpages(struct vnode *vp, vm_page_t *ma, size_t len, int flags,
4146     int *rtvals)
4147 {
4148         znode_t         *zp = VTOZ(vp);
4149         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4150         zfs_locked_range_t              *lr;
4151         dmu_tx_t        *tx;
4152         struct sf_buf   *sf;
4153         vm_object_t     object;
4154         vm_page_t       m;
4155         caddr_t         va;
4156         size_t          tocopy;
4157         size_t          lo_len;
4158         vm_ooffset_t    lo_off;
4159         vm_ooffset_t    off;
4160         uint_t          blksz;
4161         int             ncount;
4162         int             pcount;
4163         int             err;
4164         int             i;
4165
4166         ZFS_ENTER(zfsvfs);
4167         ZFS_VERIFY_ZP(zp);
4168
4169         object = vp->v_object;
4170         pcount = btoc(len);
4171         ncount = pcount;
4172
4173         KASSERT(ma[0]->object == object, ("mismatching object"));
4174         KASSERT(len > 0 && (len & PAGE_MASK) == 0, ("unexpected length"));
4175
4176         for (i = 0; i < pcount; i++)
4177                 rtvals[i] = zfs_vm_pagerret_error;
4178
4179         off = IDX_TO_OFF(ma[0]->pindex);
4180         blksz = zp->z_blksz;
4181         lo_off = rounddown(off, blksz);
4182         lo_len = roundup(len + (off - lo_off), blksz);
4183         lr = zfs_rangelock_enter(&zp->z_rangelock, lo_off, lo_len, RL_WRITER);
4184
4185         zfs_vmobject_wlock(object);
4186         if (len + off > object->un_pager.vnp.vnp_size) {
4187                 if (object->un_pager.vnp.vnp_size > off) {
4188                         int pgoff;
4189
4190                         len = object->un_pager.vnp.vnp_size - off;
4191                         ncount = btoc(len);
4192                         if ((pgoff = (int)len & PAGE_MASK) != 0) {
4193                                 /*
4194                                  * If the object is locked and the following
4195                                  * conditions hold, then the page's dirty
4196                                  * field cannot be concurrently changed by a
4197                                  * pmap operation.
4198                                  */
4199                                 m = ma[ncount - 1];
4200                                 vm_page_assert_sbusied(m);
4201                                 KASSERT(!pmap_page_is_write_mapped(m),
4202                                     ("zfs_putpages: page %p is not read-only",
4203                                     m));
4204                                 vm_page_clear_dirty(m, pgoff, PAGE_SIZE -
4205                                     pgoff);
4206                         }
4207                 } else {
4208                         len = 0;
4209                         ncount = 0;
4210                 }
4211                 if (ncount < pcount) {
4212                         for (i = ncount; i < pcount; i++) {
4213                                 rtvals[i] = zfs_vm_pagerret_bad;
4214                         }
4215                 }
4216         }
4217         zfs_vmobject_wunlock(object);
4218
4219         if (ncount == 0)
4220                 goto out;
4221
4222         if (zfs_id_overblockquota(zfsvfs, DMU_USERUSED_OBJECT, zp->z_uid) ||
4223             zfs_id_overblockquota(zfsvfs, DMU_GROUPUSED_OBJECT, zp->z_gid) ||
4224             (zp->z_projid != ZFS_DEFAULT_PROJID &&
4225             zfs_id_overblockquota(zfsvfs, DMU_PROJECTUSED_OBJECT,
4226             zp->z_projid))) {
4227                 goto out;
4228         }
4229
4230         tx = dmu_tx_create(zfsvfs->z_os);
4231         dmu_tx_hold_write(tx, zp->z_id, off, len);
4232
4233         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4234         zfs_sa_upgrade_txholds(tx, zp);
4235         err = dmu_tx_assign(tx, TXG_WAIT);
4236         if (err != 0) {
4237                 dmu_tx_abort(tx);
4238                 goto out;
4239         }
4240
4241         if (zp->z_blksz < PAGE_SIZE) {
4242                 for (i = 0; len > 0; off += tocopy, len -= tocopy, i++) {
4243                         tocopy = len > PAGE_SIZE ? PAGE_SIZE : len;
4244                         va = zfs_map_page(ma[i], &sf);
4245                         dmu_write(zfsvfs->z_os, zp->z_id, off, tocopy, va, tx);
4246                         zfs_unmap_page(sf);
4247                 }
4248         } else {
4249                 err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, ma, tx);
4250         }
4251
4252         if (err == 0) {
4253                 uint64_t mtime[2], ctime[2];
4254                 sa_bulk_attr_t bulk[3];
4255                 int count = 0;
4256
4257                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
4258                     &mtime, 16);
4259                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
4260                     &ctime, 16);
4261                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
4262                     &zp->z_pflags, 8);
4263                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
4264                 err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
4265                 ASSERT0(err);
4266                 /*
4267                  * XXX we should be passing a callback to undirty
4268                  * but that would make the locking messier
4269                  */
4270                 zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off,
4271                     len, 0, NULL, NULL);
4272
4273                 zfs_vmobject_wlock(object);
4274                 for (i = 0; i < ncount; i++) {
4275                         rtvals[i] = zfs_vm_pagerret_ok;
4276                         vm_page_undirty(ma[i]);
4277                 }
4278                 zfs_vmobject_wunlock(object);
4279                 VM_CNT_INC(v_vnodeout);
4280                 VM_CNT_ADD(v_vnodepgsout, ncount);
4281         }
4282         dmu_tx_commit(tx);
4283
4284 out:
4285         zfs_rangelock_exit(lr);
4286         if ((flags & (zfs_vm_pagerput_sync | zfs_vm_pagerput_inval)) != 0 ||
4287             zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
4288                 zil_commit(zfsvfs->z_log, zp->z_id);
4289         ZFS_EXIT(zfsvfs);
4290         return (rtvals[0]);
4291 }
4292
4293 #ifndef _SYS_SYSPROTO_H_
4294 struct vop_putpages_args {
4295         struct vnode *a_vp;
4296         vm_page_t *a_m;
4297         int a_count;
4298         int a_sync;
4299         int *a_rtvals;
4300 };
4301 #endif
4302
4303 static int
4304 zfs_freebsd_putpages(struct vop_putpages_args *ap)
4305 {
4306
4307         return (zfs_putpages(ap->a_vp, ap->a_m, ap->a_count, ap->a_sync,
4308             ap->a_rtvals));
4309 }
4310
4311 #ifndef _SYS_SYSPROTO_H_
4312 struct vop_bmap_args {
4313         struct vnode *a_vp;
4314         daddr_t  a_bn;
4315         struct bufobj **a_bop;
4316         daddr_t *a_bnp;
4317         int *a_runp;
4318         int *a_runb;
4319 };
4320 #endif
4321
4322 static int
4323 zfs_freebsd_bmap(struct vop_bmap_args *ap)
4324 {
4325
4326         if (ap->a_bop != NULL)
4327                 *ap->a_bop = &ap->a_vp->v_bufobj;
4328         if (ap->a_bnp != NULL)
4329                 *ap->a_bnp = ap->a_bn;
4330         if (ap->a_runp != NULL)
4331                 *ap->a_runp = 0;
4332         if (ap->a_runb != NULL)
4333                 *ap->a_runb = 0;
4334
4335         return (0);
4336 }
4337
4338 #ifndef _SYS_SYSPROTO_H_
4339 struct vop_open_args {
4340         struct vnode *a_vp;
4341         int a_mode;
4342         struct ucred *a_cred;
4343         struct thread *a_td;
4344 };
4345 #endif
4346
4347 static int
4348 zfs_freebsd_open(struct vop_open_args *ap)
4349 {
4350         vnode_t *vp = ap->a_vp;
4351         znode_t *zp = VTOZ(vp);
4352         int error;
4353
4354         error = zfs_open(&vp, ap->a_mode, ap->a_cred);
4355         if (error == 0)
4356                 vnode_create_vobject(vp, zp->z_size, ap->a_td);
4357         return (error);
4358 }
4359
4360 #ifndef _SYS_SYSPROTO_H_
4361 struct vop_close_args {
4362         struct vnode *a_vp;
4363         int  a_fflag;
4364         struct ucred *a_cred;
4365         struct thread *a_td;
4366 };
4367 #endif
4368
4369 static int
4370 zfs_freebsd_close(struct vop_close_args *ap)
4371 {
4372
4373         return (zfs_close(ap->a_vp, ap->a_fflag, 1, 0, ap->a_cred));
4374 }
4375
4376 #ifndef _SYS_SYSPROTO_H_
4377 struct vop_ioctl_args {
4378         struct vnode *a_vp;
4379         ulong_t a_command;
4380         caddr_t a_data;
4381         int a_fflag;
4382         struct ucred *cred;
4383         struct thread *td;
4384 };
4385 #endif
4386
4387 static int
4388 zfs_freebsd_ioctl(struct vop_ioctl_args *ap)
4389 {
4390
4391         return (zfs_ioctl(ap->a_vp, ap->a_command, (intptr_t)ap->a_data,
4392             ap->a_fflag, ap->a_cred, NULL));
4393 }
4394
4395 static int
4396 ioflags(int ioflags)
4397 {
4398         int flags = 0;
4399
4400         if (ioflags & IO_APPEND)
4401                 flags |= FAPPEND;
4402         if (ioflags & IO_NDELAY)
4403                 flags |= FNONBLOCK;
4404         if (ioflags & IO_SYNC)
4405                 flags |= (FSYNC | FDSYNC | FRSYNC);
4406
4407         return (flags);
4408 }
4409
4410 #ifndef _SYS_SYSPROTO_H_
4411 struct vop_read_args {
4412         struct vnode *a_vp;
4413         struct uio *a_uio;
4414         int a_ioflag;
4415         struct ucred *a_cred;
4416 };
4417 #endif
4418
4419 static int
4420 zfs_freebsd_read(struct vop_read_args *ap)
4421 {
4422         zfs_uio_t uio;
4423         zfs_uio_init(&uio, ap->a_uio);
4424         return (zfs_read(VTOZ(ap->a_vp), &uio, ioflags(ap->a_ioflag),
4425             ap->a_cred));
4426 }
4427
4428 #ifndef _SYS_SYSPROTO_H_
4429 struct vop_write_args {
4430         struct vnode *a_vp;
4431         struct uio *a_uio;
4432         int a_ioflag;
4433         struct ucred *a_cred;
4434 };
4435 #endif
4436
4437 static int
4438 zfs_freebsd_write(struct vop_write_args *ap)
4439 {
4440         zfs_uio_t uio;
4441         zfs_uio_init(&uio, ap->a_uio);
4442         return (zfs_write(VTOZ(ap->a_vp), &uio, ioflags(ap->a_ioflag),
4443             ap->a_cred));
4444 }
4445
4446 #if __FreeBSD_version >= 1300102
4447 /*
4448  * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
4449  * the comment above cache_fplookup for details.
4450  */
4451 static int
4452 zfs_freebsd_fplookup_vexec(struct vop_fplookup_vexec_args *v)
4453 {
4454         vnode_t *vp;
4455         znode_t *zp;
4456         uint64_t pflags;
4457
4458         vp = v->a_vp;
4459         zp = VTOZ_SMR(vp);
4460         if (__predict_false(zp == NULL))
4461                 return (EAGAIN);
4462         pflags = atomic_load_64(&zp->z_pflags);
4463         if (pflags & ZFS_AV_QUARANTINED)
4464                 return (EAGAIN);
4465         if (pflags & ZFS_XATTR)
4466                 return (EAGAIN);
4467         if ((pflags & ZFS_NO_EXECS_DENIED) == 0)
4468                 return (EAGAIN);
4469         return (0);
4470 }
4471 #endif
4472
4473 #ifndef _SYS_SYSPROTO_H_
4474 struct vop_access_args {
4475         struct vnode *a_vp;
4476         accmode_t a_accmode;
4477         struct ucred *a_cred;
4478         struct thread *a_td;
4479 };
4480 #endif
4481
4482 static int
4483 zfs_freebsd_access(struct vop_access_args *ap)
4484 {
4485         vnode_t *vp = ap->a_vp;
4486         znode_t *zp = VTOZ(vp);
4487         accmode_t accmode;
4488         int error = 0;
4489
4490
4491         if (ap->a_accmode == VEXEC) {
4492                 if (zfs_fastaccesschk_execute(zp, ap->a_cred) == 0)
4493                         return (0);
4494         }
4495
4496         /*
4497          * ZFS itself only knowns about VREAD, VWRITE, VEXEC and VAPPEND,
4498          */
4499         accmode = ap->a_accmode & (VREAD|VWRITE|VEXEC|VAPPEND);
4500         if (accmode != 0)
4501                 error = zfs_access(zp, accmode, 0, ap->a_cred);
4502
4503         /*
4504          * VADMIN has to be handled by vaccess().
4505          */
4506         if (error == 0) {
4507                 accmode = ap->a_accmode & ~(VREAD|VWRITE|VEXEC|VAPPEND);
4508                 if (accmode != 0) {
4509 #if __FreeBSD_version >= 1300105
4510                         error = vaccess(vp->v_type, zp->z_mode, zp->z_uid,
4511                             zp->z_gid, accmode, ap->a_cred);
4512 #else
4513                         error = vaccess(vp->v_type, zp->z_mode, zp->z_uid,
4514                             zp->z_gid, accmode, ap->a_cred, NULL);
4515 #endif
4516                 }
4517         }
4518
4519         /*
4520          * For VEXEC, ensure that at least one execute bit is set for
4521          * non-directories.
4522          */
4523         if (error == 0 && (ap->a_accmode & VEXEC) != 0 && vp->v_type != VDIR &&
4524             (zp->z_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) {
4525                 error = EACCES;
4526         }
4527
4528         return (error);
4529 }
4530
4531 #ifndef _SYS_SYSPROTO_H_
4532 struct vop_lookup_args {
4533         struct vnode *a_dvp;
4534         struct vnode **a_vpp;
4535         struct componentname *a_cnp;
4536 };
4537 #endif
4538
4539 static int
4540 zfs_freebsd_lookup(struct vop_lookup_args *ap, boolean_t cached)
4541 {
4542         struct componentname *cnp = ap->a_cnp;
4543         char nm[NAME_MAX + 1];
4544
4545         ASSERT(cnp->cn_namelen < sizeof (nm));
4546         strlcpy(nm, cnp->cn_nameptr, MIN(cnp->cn_namelen + 1, sizeof (nm)));
4547
4548         return (zfs_lookup(ap->a_dvp, nm, ap->a_vpp, cnp, cnp->cn_nameiop,
4549             cnp->cn_cred, cnp->cn_thread, 0, cached));
4550 }
4551
4552 static int
4553 zfs_freebsd_cachedlookup(struct vop_cachedlookup_args *ap)
4554 {
4555
4556         return (zfs_freebsd_lookup((struct vop_lookup_args *)ap, B_TRUE));
4557 }
4558
4559 #ifndef _SYS_SYSPROTO_H_
4560 struct vop_lookup_args {
4561         struct vnode *a_dvp;
4562         struct vnode **a_vpp;
4563         struct componentname *a_cnp;
4564 };
4565 #endif
4566
4567 static int
4568 zfs_cache_lookup(struct vop_lookup_args *ap)
4569 {
4570         zfsvfs_t *zfsvfs;
4571
4572         zfsvfs = ap->a_dvp->v_mount->mnt_data;
4573         if (zfsvfs->z_use_namecache)
4574                 return (vfs_cache_lookup(ap));
4575         else
4576                 return (zfs_freebsd_lookup(ap, B_FALSE));
4577 }
4578
4579 #ifndef _SYS_SYSPROTO_H_
4580 struct vop_create_args {
4581         struct vnode *a_dvp;
4582         struct vnode **a_vpp;
4583         struct componentname *a_cnp;
4584         struct vattr *a_vap;
4585 };
4586 #endif
4587
4588 static int
4589 zfs_freebsd_create(struct vop_create_args *ap)
4590 {
4591         zfsvfs_t *zfsvfs;
4592         struct componentname *cnp = ap->a_cnp;
4593         vattr_t *vap = ap->a_vap;
4594         znode_t *zp = NULL;
4595         int rc, mode;
4596
4597         ASSERT(cnp->cn_flags & SAVENAME);
4598
4599         vattr_init_mask(vap);
4600         mode = vap->va_mode & ALLPERMS;
4601         zfsvfs = ap->a_dvp->v_mount->mnt_data;
4602         *ap->a_vpp = NULL;
4603
4604         rc = zfs_create(VTOZ(ap->a_dvp), cnp->cn_nameptr, vap, !EXCL, mode,
4605             &zp, cnp->cn_cred, 0 /* flag */, NULL /* vsecattr */);
4606         if (rc == 0)
4607                 *ap->a_vpp = ZTOV(zp);
4608         if (zfsvfs->z_use_namecache &&
4609             rc == 0 && (cnp->cn_flags & MAKEENTRY) != 0)
4610                 cache_enter(ap->a_dvp, *ap->a_vpp, cnp);
4611
4612         return (rc);
4613 }
4614
4615 #ifndef _SYS_SYSPROTO_H_
4616 struct vop_remove_args {
4617         struct vnode *a_dvp;
4618         struct vnode *a_vp;
4619         struct componentname *a_cnp;
4620 };
4621 #endif
4622
4623 static int
4624 zfs_freebsd_remove(struct vop_remove_args *ap)
4625 {
4626
4627         ASSERT(ap->a_cnp->cn_flags & SAVENAME);
4628
4629         return (zfs_remove_(ap->a_dvp, ap->a_vp, ap->a_cnp->cn_nameptr,
4630             ap->a_cnp->cn_cred));
4631 }
4632
4633 #ifndef _SYS_SYSPROTO_H_
4634 struct vop_mkdir_args {
4635         struct vnode *a_dvp;
4636         struct vnode **a_vpp;
4637         struct componentname *a_cnp;
4638         struct vattr *a_vap;
4639 };
4640 #endif
4641
4642 static int
4643 zfs_freebsd_mkdir(struct vop_mkdir_args *ap)
4644 {
4645         vattr_t *vap = ap->a_vap;
4646         znode_t *zp = NULL;
4647         int rc;
4648
4649         ASSERT(ap->a_cnp->cn_flags & SAVENAME);
4650
4651         vattr_init_mask(vap);
4652         *ap->a_vpp = NULL;
4653
4654         rc = zfs_mkdir(VTOZ(ap->a_dvp), ap->a_cnp->cn_nameptr, vap, &zp,
4655             ap->a_cnp->cn_cred, 0, NULL);
4656
4657         if (rc == 0)
4658                 *ap->a_vpp = ZTOV(zp);
4659         return (rc);
4660 }
4661
4662 #ifndef _SYS_SYSPROTO_H_
4663 struct vop_rmdir_args {
4664         struct vnode *a_dvp;
4665         struct vnode *a_vp;
4666         struct componentname *a_cnp;
4667 };
4668 #endif
4669
4670 static int
4671 zfs_freebsd_rmdir(struct vop_rmdir_args *ap)
4672 {
4673         struct componentname *cnp = ap->a_cnp;
4674
4675         ASSERT(cnp->cn_flags & SAVENAME);
4676
4677         return (zfs_rmdir_(ap->a_dvp, ap->a_vp, cnp->cn_nameptr, cnp->cn_cred));
4678 }
4679
4680 #ifndef _SYS_SYSPROTO_H_
4681 struct vop_readdir_args {
4682         struct vnode *a_vp;
4683         struct uio *a_uio;
4684         struct ucred *a_cred;
4685         int *a_eofflag;
4686         int *a_ncookies;
4687         ulong_t **a_cookies;
4688 };
4689 #endif
4690
4691 static int
4692 zfs_freebsd_readdir(struct vop_readdir_args *ap)
4693 {
4694         zfs_uio_t uio;
4695         zfs_uio_init(&uio, ap->a_uio);
4696         return (zfs_readdir(ap->a_vp, &uio, ap->a_cred, ap->a_eofflag,
4697             ap->a_ncookies, ap->a_cookies));
4698 }
4699
4700 #ifndef _SYS_SYSPROTO_H_
4701 struct vop_fsync_args {
4702         struct vnode *a_vp;
4703         int a_waitfor;
4704         struct thread *a_td;
4705 };
4706 #endif
4707
4708 static int
4709 zfs_freebsd_fsync(struct vop_fsync_args *ap)
4710 {
4711
4712         vop_stdfsync(ap);
4713         return (zfs_fsync(VTOZ(ap->a_vp), 0, ap->a_td->td_ucred));
4714 }
4715
4716 #ifndef _SYS_SYSPROTO_H_
4717 struct vop_getattr_args {
4718         struct vnode *a_vp;
4719         struct vattr *a_vap;
4720         struct ucred *a_cred;
4721 };
4722 #endif
4723
4724 static int
4725 zfs_freebsd_getattr(struct vop_getattr_args *ap)
4726 {
4727         vattr_t *vap = ap->a_vap;
4728         xvattr_t xvap;
4729         ulong_t fflags = 0;
4730         int error;
4731
4732         xva_init(&xvap);
4733         xvap.xva_vattr = *vap;
4734         xvap.xva_vattr.va_mask |= AT_XVATTR;
4735
4736         /* Convert chflags into ZFS-type flags. */
4737         /* XXX: what about SF_SETTABLE?. */
4738         XVA_SET_REQ(&xvap, XAT_IMMUTABLE);
4739         XVA_SET_REQ(&xvap, XAT_APPENDONLY);
4740         XVA_SET_REQ(&xvap, XAT_NOUNLINK);
4741         XVA_SET_REQ(&xvap, XAT_NODUMP);
4742         XVA_SET_REQ(&xvap, XAT_READONLY);
4743         XVA_SET_REQ(&xvap, XAT_ARCHIVE);
4744         XVA_SET_REQ(&xvap, XAT_SYSTEM);
4745         XVA_SET_REQ(&xvap, XAT_HIDDEN);
4746         XVA_SET_REQ(&xvap, XAT_REPARSE);
4747         XVA_SET_REQ(&xvap, XAT_OFFLINE);
4748         XVA_SET_REQ(&xvap, XAT_SPARSE);
4749
4750         error = zfs_getattr(ap->a_vp, (vattr_t *)&xvap, 0, ap->a_cred);
4751         if (error != 0)
4752                 return (error);
4753
4754         /* Convert ZFS xattr into chflags. */
4755 #define FLAG_CHECK(fflag, xflag, xfield)        do {                    \
4756         if (XVA_ISSET_RTN(&xvap, (xflag)) && (xfield) != 0)             \
4757                 fflags |= (fflag);                                      \
4758 } while (0)
4759         FLAG_CHECK(SF_IMMUTABLE, XAT_IMMUTABLE,
4760             xvap.xva_xoptattrs.xoa_immutable);
4761         FLAG_CHECK(SF_APPEND, XAT_APPENDONLY,
4762             xvap.xva_xoptattrs.xoa_appendonly);
4763         FLAG_CHECK(SF_NOUNLINK, XAT_NOUNLINK,
4764             xvap.xva_xoptattrs.xoa_nounlink);
4765         FLAG_CHECK(UF_ARCHIVE, XAT_ARCHIVE,
4766             xvap.xva_xoptattrs.xoa_archive);
4767         FLAG_CHECK(UF_NODUMP, XAT_NODUMP,
4768             xvap.xva_xoptattrs.xoa_nodump);
4769         FLAG_CHECK(UF_READONLY, XAT_READONLY,
4770             xvap.xva_xoptattrs.xoa_readonly);
4771         FLAG_CHECK(UF_SYSTEM, XAT_SYSTEM,
4772             xvap.xva_xoptattrs.xoa_system);
4773         FLAG_CHECK(UF_HIDDEN, XAT_HIDDEN,
4774             xvap.xva_xoptattrs.xoa_hidden);
4775         FLAG_CHECK(UF_REPARSE, XAT_REPARSE,
4776             xvap.xva_xoptattrs.xoa_reparse);
4777         FLAG_CHECK(UF_OFFLINE, XAT_OFFLINE,
4778             xvap.xva_xoptattrs.xoa_offline);
4779         FLAG_CHECK(UF_SPARSE, XAT_SPARSE,
4780             xvap.xva_xoptattrs.xoa_sparse);
4781
4782 #undef  FLAG_CHECK
4783         *vap = xvap.xva_vattr;
4784         vap->va_flags = fflags;
4785         return (0);
4786 }
4787
4788 #ifndef _SYS_SYSPROTO_H_
4789 struct vop_setattr_args {
4790         struct vnode *a_vp;
4791         struct vattr *a_vap;
4792         struct ucred *a_cred;
4793 };
4794 #endif
4795
4796 static int
4797 zfs_freebsd_setattr(struct vop_setattr_args *ap)
4798 {
4799         vnode_t *vp = ap->a_vp;
4800         vattr_t *vap = ap->a_vap;
4801         cred_t *cred = ap->a_cred;
4802         xvattr_t xvap;
4803         ulong_t fflags;
4804         uint64_t zflags;
4805
4806         vattr_init_mask(vap);
4807         vap->va_mask &= ~AT_NOSET;
4808
4809         xva_init(&xvap);
4810         xvap.xva_vattr = *vap;
4811
4812         zflags = VTOZ(vp)->z_pflags;
4813
4814         if (vap->va_flags != VNOVAL) {
4815                 zfsvfs_t *zfsvfs = VTOZ(vp)->z_zfsvfs;
4816                 int error;
4817
4818                 if (zfsvfs->z_use_fuids == B_FALSE)
4819                         return (EOPNOTSUPP);
4820
4821                 fflags = vap->va_flags;
4822                 /*
4823                  * XXX KDM
4824                  * We need to figure out whether it makes sense to allow
4825                  * UF_REPARSE through, since we don't really have other
4826                  * facilities to handle reparse points and zfs_setattr()
4827                  * doesn't currently allow setting that attribute anyway.
4828                  */
4829                 if ((fflags & ~(SF_IMMUTABLE|SF_APPEND|SF_NOUNLINK|UF_ARCHIVE|
4830                     UF_NODUMP|UF_SYSTEM|UF_HIDDEN|UF_READONLY|UF_REPARSE|
4831                     UF_OFFLINE|UF_SPARSE)) != 0)
4832                         return (EOPNOTSUPP);
4833                 /*
4834                  * Unprivileged processes are not permitted to unset system
4835                  * flags, or modify flags if any system flags are set.
4836                  * Privileged non-jail processes may not modify system flags
4837                  * if securelevel > 0 and any existing system flags are set.
4838                  * Privileged jail processes behave like privileged non-jail
4839                  * processes if the PR_ALLOW_CHFLAGS permission bit is set;
4840                  * otherwise, they behave like unprivileged processes.
4841                  */
4842                 if (secpolicy_fs_owner(vp->v_mount, cred) == 0 ||
4843                     spl_priv_check_cred(cred, PRIV_VFS_SYSFLAGS) == 0) {
4844                         if (zflags &
4845                             (ZFS_IMMUTABLE | ZFS_APPENDONLY | ZFS_NOUNLINK)) {
4846                                 error = securelevel_gt(cred, 0);
4847                                 if (error != 0)
4848                                         return (error);
4849                         }
4850                 } else {
4851                         /*
4852                          * Callers may only modify the file flags on
4853                          * objects they have VADMIN rights for.
4854                          */
4855                         if ((error = VOP_ACCESS(vp, VADMIN, cred,
4856                             curthread)) != 0)
4857                                 return (error);
4858                         if (zflags &
4859                             (ZFS_IMMUTABLE | ZFS_APPENDONLY |
4860                             ZFS_NOUNLINK)) {
4861                                 return (EPERM);
4862                         }
4863                         if (fflags &
4864                             (SF_IMMUTABLE | SF_APPEND | SF_NOUNLINK)) {
4865                                 return (EPERM);
4866                         }
4867                 }
4868
4869 #define FLAG_CHANGE(fflag, zflag, xflag, xfield)        do {            \
4870         if (((fflags & (fflag)) && !(zflags & (zflag))) ||              \
4871             ((zflags & (zflag)) && !(fflags & (fflag)))) {              \
4872                 XVA_SET_REQ(&xvap, (xflag));                            \
4873                 (xfield) = ((fflags & (fflag)) != 0);                   \
4874         }                                                               \
4875 } while (0)
4876                 /* Convert chflags into ZFS-type flags. */
4877                 /* XXX: what about SF_SETTABLE?. */
4878                 FLAG_CHANGE(SF_IMMUTABLE, ZFS_IMMUTABLE, XAT_IMMUTABLE,
4879                     xvap.xva_xoptattrs.xoa_immutable);
4880                 FLAG_CHANGE(SF_APPEND, ZFS_APPENDONLY, XAT_APPENDONLY,
4881                     xvap.xva_xoptattrs.xoa_appendonly);
4882                 FLAG_CHANGE(SF_NOUNLINK, ZFS_NOUNLINK, XAT_NOUNLINK,
4883                     xvap.xva_xoptattrs.xoa_nounlink);
4884                 FLAG_CHANGE(UF_ARCHIVE, ZFS_ARCHIVE, XAT_ARCHIVE,
4885                     xvap.xva_xoptattrs.xoa_archive);
4886                 FLAG_CHANGE(UF_NODUMP, ZFS_NODUMP, XAT_NODUMP,
4887                     xvap.xva_xoptattrs.xoa_nodump);
4888                 FLAG_CHANGE(UF_READONLY, ZFS_READONLY, XAT_READONLY,
4889                     xvap.xva_xoptattrs.xoa_readonly);
4890                 FLAG_CHANGE(UF_SYSTEM, ZFS_SYSTEM, XAT_SYSTEM,
4891                     xvap.xva_xoptattrs.xoa_system);
4892                 FLAG_CHANGE(UF_HIDDEN, ZFS_HIDDEN, XAT_HIDDEN,
4893                     xvap.xva_xoptattrs.xoa_hidden);
4894                 FLAG_CHANGE(UF_REPARSE, ZFS_REPARSE, XAT_REPARSE,
4895                     xvap.xva_xoptattrs.xoa_reparse);
4896                 FLAG_CHANGE(UF_OFFLINE, ZFS_OFFLINE, XAT_OFFLINE,
4897                     xvap.xva_xoptattrs.xoa_offline);
4898                 FLAG_CHANGE(UF_SPARSE, ZFS_SPARSE, XAT_SPARSE,
4899                     xvap.xva_xoptattrs.xoa_sparse);
4900 #undef  FLAG_CHANGE
4901         }
4902         if (vap->va_birthtime.tv_sec != VNOVAL) {
4903                 xvap.xva_vattr.va_mask |= AT_XVATTR;
4904                 XVA_SET_REQ(&xvap, XAT_CREATETIME);
4905         }
4906         return (zfs_setattr(VTOZ(vp), (vattr_t *)&xvap, 0, cred));
4907 }
4908
4909 #ifndef _SYS_SYSPROTO_H_
4910 struct vop_rename_args {
4911         struct vnode *a_fdvp;
4912         struct vnode *a_fvp;
4913         struct componentname *a_fcnp;
4914         struct vnode *a_tdvp;
4915         struct vnode *a_tvp;
4916         struct componentname *a_tcnp;
4917 };
4918 #endif
4919
4920 static int
4921 zfs_freebsd_rename(struct vop_rename_args *ap)
4922 {
4923         vnode_t *fdvp = ap->a_fdvp;
4924         vnode_t *fvp = ap->a_fvp;
4925         vnode_t *tdvp = ap->a_tdvp;
4926         vnode_t *tvp = ap->a_tvp;
4927         int error;
4928
4929         ASSERT(ap->a_fcnp->cn_flags & (SAVENAME|SAVESTART));
4930         ASSERT(ap->a_tcnp->cn_flags & (SAVENAME|SAVESTART));
4931
4932         error = zfs_rename_(fdvp, &fvp, ap->a_fcnp, tdvp, &tvp,
4933             ap->a_tcnp, ap->a_fcnp->cn_cred, 1);
4934
4935         vrele(fdvp);
4936         vrele(fvp);
4937         vrele(tdvp);
4938         if (tvp != NULL)
4939                 vrele(tvp);
4940
4941         return (error);
4942 }
4943
4944 #ifndef _SYS_SYSPROTO_H_
4945 struct vop_symlink_args {
4946         struct vnode *a_dvp;
4947         struct vnode **a_vpp;
4948         struct componentname *a_cnp;
4949         struct vattr *a_vap;
4950         char *a_target;
4951 };
4952 #endif
4953
4954 static int
4955 zfs_freebsd_symlink(struct vop_symlink_args *ap)
4956 {
4957         struct componentname *cnp = ap->a_cnp;
4958         vattr_t *vap = ap->a_vap;
4959         znode_t *zp = NULL;
4960         int rc;
4961
4962         ASSERT(cnp->cn_flags & SAVENAME);
4963
4964         vap->va_type = VLNK;    /* FreeBSD: Syscall only sets va_mode. */
4965         vattr_init_mask(vap);
4966         *ap->a_vpp = NULL;
4967
4968         rc = zfs_symlink(VTOZ(ap->a_dvp), cnp->cn_nameptr, vap,
4969             ap->a_target, &zp, cnp->cn_cred, 0 /* flags */);
4970         if (rc == 0)
4971                 *ap->a_vpp = ZTOV(zp);
4972         return (rc);
4973 }
4974
4975 #ifndef _SYS_SYSPROTO_H_
4976 struct vop_readlink_args {
4977         struct vnode *a_vp;
4978         struct uio *a_uio;
4979         struct ucred *a_cred;
4980 };
4981 #endif
4982
4983 static int
4984 zfs_freebsd_readlink(struct vop_readlink_args *ap)
4985 {
4986         zfs_uio_t uio;
4987         zfs_uio_init(&uio, ap->a_uio);
4988         return (zfs_readlink(ap->a_vp, &uio, ap->a_cred, NULL));
4989 }
4990
4991 #ifndef _SYS_SYSPROTO_H_
4992 struct vop_link_args {
4993         struct vnode *a_tdvp;
4994         struct vnode *a_vp;
4995         struct componentname *a_cnp;
4996 };
4997 #endif
4998
4999 static int
5000 zfs_freebsd_link(struct vop_link_args *ap)
5001 {
5002         struct componentname *cnp = ap->a_cnp;
5003         vnode_t *vp = ap->a_vp;
5004         vnode_t *tdvp = ap->a_tdvp;
5005
5006         if (tdvp->v_mount != vp->v_mount)
5007                 return (EXDEV);
5008
5009         ASSERT(cnp->cn_flags & SAVENAME);
5010
5011         return (zfs_link(VTOZ(tdvp), VTOZ(vp),
5012             cnp->cn_nameptr, cnp->cn_cred, 0));
5013 }
5014
5015 #ifndef _SYS_SYSPROTO_H_
5016 struct vop_inactive_args {
5017         struct vnode *a_vp;
5018         struct thread *a_td;
5019 };
5020 #endif
5021
5022 static int
5023 zfs_freebsd_inactive(struct vop_inactive_args *ap)
5024 {
5025         vnode_t *vp = ap->a_vp;
5026
5027 #if __FreeBSD_version >= 1300123
5028         zfs_inactive(vp, curthread->td_ucred, NULL);
5029 #else
5030         zfs_inactive(vp, ap->a_td->td_ucred, NULL);
5031 #endif
5032         return (0);
5033 }
5034
5035 #if __FreeBSD_version >= 1300042
5036 #ifndef _SYS_SYSPROTO_H_
5037 struct vop_need_inactive_args {
5038         struct vnode *a_vp;
5039         struct thread *a_td;
5040 };
5041 #endif
5042
5043 static int
5044 zfs_freebsd_need_inactive(struct vop_need_inactive_args *ap)
5045 {
5046         vnode_t *vp = ap->a_vp;
5047         znode_t *zp = VTOZ(vp);
5048         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5049         int need;
5050
5051         if (vn_need_pageq_flush(vp))
5052                 return (1);
5053
5054         if (!ZFS_TRYRLOCK_TEARDOWN_INACTIVE(zfsvfs))
5055                 return (1);
5056         need = (zp->z_sa_hdl == NULL || zp->z_unlinked || zp->z_atime_dirty);
5057         ZFS_RUNLOCK_TEARDOWN_INACTIVE(zfsvfs);
5058
5059         return (need);
5060 }
5061 #endif
5062
5063 #ifndef _SYS_SYSPROTO_H_
5064 struct vop_reclaim_args {
5065         struct vnode *a_vp;
5066         struct thread *a_td;
5067 };
5068 #endif
5069
5070 static int
5071 zfs_freebsd_reclaim(struct vop_reclaim_args *ap)
5072 {
5073         vnode_t *vp = ap->a_vp;
5074         znode_t *zp = VTOZ(vp);
5075         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5076
5077         ASSERT(zp != NULL);
5078
5079 #if __FreeBSD_version < 1300042
5080         /* Destroy the vm object and flush associated pages. */
5081         vnode_destroy_vobject(vp);
5082 #endif
5083         /*
5084          * z_teardown_inactive_lock protects from a race with
5085          * zfs_znode_dmu_fini in zfsvfs_teardown during
5086          * force unmount.
5087          */
5088         ZFS_RLOCK_TEARDOWN_INACTIVE(zfsvfs);
5089         if (zp->z_sa_hdl == NULL)
5090                 zfs_znode_free(zp);
5091         else
5092                 zfs_zinactive(zp);
5093         ZFS_RUNLOCK_TEARDOWN_INACTIVE(zfsvfs);
5094
5095         vp->v_data = NULL;
5096         return (0);
5097 }
5098
5099 #ifndef _SYS_SYSPROTO_H_
5100 struct vop_fid_args {
5101         struct vnode *a_vp;
5102         struct fid *a_fid;
5103 };
5104 #endif
5105
5106 static int
5107 zfs_freebsd_fid(struct vop_fid_args *ap)
5108 {
5109
5110         return (zfs_fid(ap->a_vp, (void *)ap->a_fid, NULL));
5111 }
5112
5113
5114 #ifndef _SYS_SYSPROTO_H_
5115 struct vop_pathconf_args {
5116         struct vnode *a_vp;
5117         int a_name;
5118         register_t *a_retval;
5119 } *ap;
5120 #endif
5121
5122 static int
5123 zfs_freebsd_pathconf(struct vop_pathconf_args *ap)
5124 {
5125         ulong_t val;
5126         int error;
5127
5128         error = zfs_pathconf(ap->a_vp, ap->a_name, &val,
5129             curthread->td_ucred, NULL);
5130         if (error == 0) {
5131                 *ap->a_retval = val;
5132                 return (error);
5133         }
5134         if (error != EOPNOTSUPP)
5135                 return (error);
5136
5137         switch (ap->a_name) {
5138         case _PC_NAME_MAX:
5139                 *ap->a_retval = NAME_MAX;
5140                 return (0);
5141         case _PC_PIPE_BUF:
5142                 if (ap->a_vp->v_type == VDIR || ap->a_vp->v_type == VFIFO) {
5143                         *ap->a_retval = PIPE_BUF;
5144                         return (0);
5145                 }
5146                 return (EINVAL);
5147         default:
5148                 return (vop_stdpathconf(ap));
5149         }
5150 }
5151
5152 /*
5153  * FreeBSD's extended attributes namespace defines file name prefix for ZFS'
5154  * extended attribute name:
5155  *
5156  *      NAMESPACE       PREFIX
5157  *      system          freebsd:system:
5158  *      user            (none, can be used to access ZFS fsattr(5) attributes
5159  *                      created on Solaris)
5160  */
5161 static int
5162 zfs_create_attrname(int attrnamespace, const char *name, char *attrname,
5163     size_t size)
5164 {
5165         const char *namespace, *prefix, *suffix;
5166
5167         /* We don't allow '/' character in attribute name. */
5168         if (strchr(name, '/') != NULL)
5169                 return (EINVAL);
5170         /* We don't allow attribute names that start with "freebsd:" string. */
5171         if (strncmp(name, "freebsd:", 8) == 0)
5172                 return (EINVAL);
5173
5174         bzero(attrname, size);
5175
5176         switch (attrnamespace) {
5177         case EXTATTR_NAMESPACE_USER:
5178 #if 0
5179                 prefix = "freebsd:";
5180                 namespace = EXTATTR_NAMESPACE_USER_STRING;
5181                 suffix = ":";
5182 #else
5183                 /*
5184                  * This is the default namespace by which we can access all
5185                  * attributes created on Solaris.
5186                  */
5187                 prefix = namespace = suffix = "";
5188 #endif
5189                 break;
5190         case EXTATTR_NAMESPACE_SYSTEM:
5191                 prefix = "freebsd:";
5192                 namespace = EXTATTR_NAMESPACE_SYSTEM_STRING;
5193                 suffix = ":";
5194                 break;
5195         case EXTATTR_NAMESPACE_EMPTY:
5196         default:
5197                 return (EINVAL);
5198         }
5199         if (snprintf(attrname, size, "%s%s%s%s", prefix, namespace, suffix,
5200             name) >= size) {
5201                 return (ENAMETOOLONG);
5202         }
5203         return (0);
5204 }
5205
5206 #ifndef _SYS_SYSPROTO_H_
5207 struct vop_getextattr {
5208         IN struct vnode *a_vp;
5209         IN int a_attrnamespace;
5210         IN const char *a_name;
5211         INOUT struct uio *a_uio;
5212         OUT size_t *a_size;
5213         IN struct ucred *a_cred;
5214         IN struct thread *a_td;
5215 };
5216 #endif
5217
5218 /*
5219  * Vnode operating to retrieve a named extended attribute.
5220  */
5221 static int
5222 zfs_getextattr(struct vop_getextattr_args *ap)
5223 {
5224         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
5225         struct thread *td = ap->a_td;
5226         struct nameidata nd;
5227         char attrname[255];
5228         struct vattr va;
5229         vnode_t *xvp = NULL, *vp;
5230         int error, flags;
5231
5232         /*
5233          * If the xattr property is off, refuse the request.
5234          */
5235         if (!(zfsvfs->z_flags & ZSB_XATTR)) {
5236                 return (SET_ERROR(EOPNOTSUPP));
5237         }
5238
5239         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
5240             ap->a_cred, ap->a_td, VREAD);
5241         if (error != 0)
5242                 return (error);
5243
5244         error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
5245             sizeof (attrname));
5246         if (error != 0)
5247                 return (error);
5248
5249         ZFS_ENTER(zfsvfs);
5250
5251         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
5252             LOOKUP_XATTR, B_FALSE);
5253         if (error != 0) {
5254                 ZFS_EXIT(zfsvfs);
5255                 return (error);
5256         }
5257
5258         flags = FREAD;
5259         NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, attrname,
5260             xvp, td);
5261         error = vn_open_cred(&nd, &flags, 0, VN_OPEN_INVFS, ap->a_cred, NULL);
5262         vp = nd.ni_vp;
5263         NDFREE(&nd, NDF_ONLY_PNBUF);
5264         if (error != 0) {
5265                 ZFS_EXIT(zfsvfs);
5266                 if (error == ENOENT)
5267                         error = ENOATTR;
5268                 return (error);
5269         }
5270
5271         if (ap->a_size != NULL) {
5272                 error = VOP_GETATTR(vp, &va, ap->a_cred);
5273                 if (error == 0)
5274                         *ap->a_size = (size_t)va.va_size;
5275         } else if (ap->a_uio != NULL)
5276                 error = VOP_READ(vp, ap->a_uio, IO_UNIT, ap->a_cred);
5277
5278         VOP_UNLOCK1(vp);
5279         vn_close(vp, flags, ap->a_cred, td);
5280         ZFS_EXIT(zfsvfs);
5281         return (error);
5282 }
5283
5284 #ifndef _SYS_SYSPROTO_H_
5285 struct vop_deleteextattr {
5286         IN struct vnode *a_vp;
5287         IN int a_attrnamespace;
5288         IN const char *a_name;
5289         IN struct ucred *a_cred;
5290         IN struct thread *a_td;
5291 };
5292 #endif
5293
5294 /*
5295  * Vnode operation to remove a named attribute.
5296  */
5297 static int
5298 zfs_deleteextattr(struct vop_deleteextattr_args *ap)
5299 {
5300         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
5301         struct thread *td = ap->a_td;
5302         struct nameidata nd;
5303         char attrname[255];
5304         vnode_t *xvp = NULL, *vp;
5305         int error;
5306
5307         /*
5308          * If the xattr property is off, refuse the request.
5309          */
5310         if (!(zfsvfs->z_flags & ZSB_XATTR)) {
5311                 return (SET_ERROR(EOPNOTSUPP));
5312         }
5313
5314         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
5315             ap->a_cred, ap->a_td, VWRITE);
5316         if (error != 0)
5317                 return (error);
5318
5319         error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
5320             sizeof (attrname));
5321         if (error != 0)
5322                 return (error);
5323
5324         ZFS_ENTER(zfsvfs);
5325
5326         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
5327             LOOKUP_XATTR, B_FALSE);
5328         if (error != 0) {
5329                 ZFS_EXIT(zfsvfs);
5330                 return (error);
5331         }
5332
5333         NDINIT_ATVP(&nd, DELETE, NOFOLLOW | LOCKPARENT | LOCKLEAF,
5334             UIO_SYSSPACE, attrname, xvp, td);
5335         error = namei(&nd);
5336         vp = nd.ni_vp;
5337         if (error != 0) {
5338                 ZFS_EXIT(zfsvfs);
5339                 NDFREE(&nd, NDF_ONLY_PNBUF);
5340                 if (error == ENOENT)
5341                         error = ENOATTR;
5342                 return (error);
5343         }
5344
5345         error = VOP_REMOVE(nd.ni_dvp, vp, &nd.ni_cnd);
5346         NDFREE(&nd, NDF_ONLY_PNBUF);
5347
5348         vput(nd.ni_dvp);
5349         if (vp == nd.ni_dvp)
5350                 vrele(vp);
5351         else
5352                 vput(vp);
5353         ZFS_EXIT(zfsvfs);
5354
5355         return (error);
5356 }
5357
5358 #ifndef _SYS_SYSPROTO_H_
5359 struct vop_setextattr {
5360         IN struct vnode *a_vp;
5361         IN int a_attrnamespace;
5362         IN const char *a_name;
5363         INOUT struct uio *a_uio;
5364         IN struct ucred *a_cred;
5365         IN struct thread *a_td;
5366 };
5367 #endif
5368
5369 /*
5370  * Vnode operation to set a named attribute.
5371  */
5372 static int
5373 zfs_setextattr(struct vop_setextattr_args *ap)
5374 {
5375         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
5376         struct thread *td = ap->a_td;
5377         struct nameidata nd;
5378         char attrname[255];
5379         struct vattr va;
5380         vnode_t *xvp = NULL, *vp;
5381         int error, flags;
5382
5383         /*
5384          * If the xattr property is off, refuse the request.
5385          */
5386         if (!(zfsvfs->z_flags & ZSB_XATTR)) {
5387                 return (SET_ERROR(EOPNOTSUPP));
5388         }
5389
5390         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
5391             ap->a_cred, ap->a_td, VWRITE);
5392         if (error != 0)
5393                 return (error);
5394         error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
5395             sizeof (attrname));
5396         if (error != 0)
5397                 return (error);
5398
5399         ZFS_ENTER(zfsvfs);
5400
5401         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
5402             LOOKUP_XATTR | CREATE_XATTR_DIR, B_FALSE);
5403         if (error != 0) {
5404                 ZFS_EXIT(zfsvfs);
5405                 return (error);
5406         }
5407
5408         flags = FFLAGS(O_WRONLY | O_CREAT);
5409         NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, attrname,
5410             xvp, td);
5411         error = vn_open_cred(&nd, &flags, 0600, VN_OPEN_INVFS, ap->a_cred,
5412             NULL);
5413         vp = nd.ni_vp;
5414         NDFREE(&nd, NDF_ONLY_PNBUF);
5415         if (error != 0) {
5416                 ZFS_EXIT(zfsvfs);
5417                 return (error);
5418         }
5419
5420         VATTR_NULL(&va);
5421         va.va_size = 0;
5422         error = VOP_SETATTR(vp, &va, ap->a_cred);
5423         if (error == 0)
5424                 VOP_WRITE(vp, ap->a_uio, IO_UNIT, ap->a_cred);
5425
5426         VOP_UNLOCK1(vp);
5427         vn_close(vp, flags, ap->a_cred, td);
5428         ZFS_EXIT(zfsvfs);
5429         return (error);
5430 }
5431
5432 #ifndef _SYS_SYSPROTO_H_
5433 struct vop_listextattr {
5434         IN struct vnode *a_vp;
5435         IN int a_attrnamespace;
5436         INOUT struct uio *a_uio;
5437         OUT size_t *a_size;
5438         IN struct ucred *a_cred;
5439         IN struct thread *a_td;
5440 };
5441 #endif
5442
5443 /*
5444  * Vnode operation to retrieve extended attributes on a vnode.
5445  */
5446 static int
5447 zfs_listextattr(struct vop_listextattr_args *ap)
5448 {
5449         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
5450         struct thread *td = ap->a_td;
5451         struct nameidata nd;
5452         char attrprefix[16];
5453         uint8_t dirbuf[sizeof (struct dirent)];
5454         struct dirent *dp;
5455         struct iovec aiov;
5456         struct uio auio;
5457         size_t *sizep = ap->a_size;
5458         size_t plen;
5459         vnode_t *xvp = NULL, *vp;
5460         int done, error, eof, pos;
5461         zfs_uio_t uio;
5462
5463         zfs_uio_init(&uio, ap->a_uio);
5464
5465         /*
5466          * If the xattr property is off, refuse the request.
5467          */
5468         if (!(zfsvfs->z_flags & ZSB_XATTR)) {
5469                 return (SET_ERROR(EOPNOTSUPP));
5470         }
5471
5472         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
5473             ap->a_cred, ap->a_td, VREAD);
5474         if (error != 0)
5475                 return (error);
5476
5477         error = zfs_create_attrname(ap->a_attrnamespace, "", attrprefix,
5478             sizeof (attrprefix));
5479         if (error != 0)
5480                 return (error);
5481         plen = strlen(attrprefix);
5482
5483         ZFS_ENTER(zfsvfs);
5484
5485         if (sizep != NULL)
5486                 *sizep = 0;
5487
5488         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
5489             LOOKUP_XATTR, B_FALSE);
5490         if (error != 0) {
5491                 ZFS_EXIT(zfsvfs);
5492                 /*
5493                  * ENOATTR means that the EA directory does not yet exist,
5494                  * i.e. there are no extended attributes there.
5495                  */
5496                 if (error == ENOATTR)
5497                         error = 0;
5498                 return (error);
5499         }
5500
5501         NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | LOCKLEAF | LOCKSHARED,
5502             UIO_SYSSPACE, ".", xvp, td);
5503         error = namei(&nd);
5504         vp = nd.ni_vp;
5505         NDFREE(&nd, NDF_ONLY_PNBUF);
5506         if (error != 0) {
5507                 ZFS_EXIT(zfsvfs);
5508                 return (error);
5509         }
5510
5511         auio.uio_iov = &aiov;
5512         auio.uio_iovcnt = 1;
5513         auio.uio_segflg = UIO_SYSSPACE;
5514         auio.uio_td = td;
5515         auio.uio_rw = UIO_READ;
5516         auio.uio_offset = 0;
5517
5518         do {
5519                 uint8_t nlen;
5520
5521                 aiov.iov_base = (void *)dirbuf;
5522                 aiov.iov_len = sizeof (dirbuf);
5523                 auio.uio_resid = sizeof (dirbuf);
5524                 error = VOP_READDIR(vp, &auio, ap->a_cred, &eof, NULL, NULL);
5525                 done = sizeof (dirbuf) - auio.uio_resid;
5526                 if (error != 0)
5527                         break;
5528                 for (pos = 0; pos < done; ) {
5529                         dp = (struct dirent *)(dirbuf + pos);
5530                         pos += dp->d_reclen;
5531                         /*
5532                          * XXX: Temporarily we also accept DT_UNKNOWN, as this
5533                          * is what we get when attribute was created on Solaris.
5534                          */
5535                         if (dp->d_type != DT_REG && dp->d_type != DT_UNKNOWN)
5536                                 continue;
5537                         if (plen == 0 &&
5538                             strncmp(dp->d_name, "freebsd:", 8) == 0)
5539                                 continue;
5540                         else if (strncmp(dp->d_name, attrprefix, plen) != 0)
5541                                 continue;
5542                         nlen = dp->d_namlen - plen;
5543                         if (sizep != NULL)
5544                                 *sizep += 1 + nlen;
5545                         else if (GET_UIO_STRUCT(&uio) != NULL) {
5546                                 /*
5547                                  * Format of extattr name entry is one byte for
5548                                  * length and the rest for name.
5549                                  */
5550                                 error = zfs_uiomove(&nlen, 1, zfs_uio_rw(&uio),
5551                                     &uio);
5552                                 if (error == 0) {
5553                                         error = zfs_uiomove(dp->d_name + plen,
5554                                             nlen, zfs_uio_rw(&uio), &uio);
5555                                 }
5556                                 if (error != 0)
5557                                         break;
5558                         }
5559                 }
5560         } while (!eof && error == 0);
5561
5562         vput(vp);
5563         ZFS_EXIT(zfsvfs);
5564
5565         return (error);
5566 }
5567
5568 #ifndef _SYS_SYSPROTO_H_
5569 struct vop_getacl_args {
5570         struct vnode *vp;
5571         acl_type_t type;
5572         struct acl *aclp;
5573         struct ucred *cred;
5574         struct thread *td;
5575 };
5576 #endif
5577
5578 static int
5579 zfs_freebsd_getacl(struct vop_getacl_args *ap)
5580 {
5581         int             error;
5582         vsecattr_t      vsecattr;
5583
5584         if (ap->a_type != ACL_TYPE_NFS4)
5585                 return (EINVAL);
5586
5587         vsecattr.vsa_mask = VSA_ACE | VSA_ACECNT;
5588         if ((error = zfs_getsecattr(VTOZ(ap->a_vp),
5589             &vsecattr, 0, ap->a_cred)))
5590                 return (error);
5591
5592         error = acl_from_aces(ap->a_aclp, vsecattr.vsa_aclentp,
5593             vsecattr.vsa_aclcnt);
5594         if (vsecattr.vsa_aclentp != NULL)
5595                 kmem_free(vsecattr.vsa_aclentp, vsecattr.vsa_aclentsz);
5596
5597         return (error);
5598 }
5599
5600 #ifndef _SYS_SYSPROTO_H_
5601 struct vop_setacl_args {
5602         struct vnode *vp;
5603         acl_type_t type;
5604         struct acl *aclp;
5605         struct ucred *cred;
5606         struct thread *td;
5607 };
5608 #endif
5609
5610 static int
5611 zfs_freebsd_setacl(struct vop_setacl_args *ap)
5612 {
5613         int             error;
5614         vsecattr_t vsecattr;
5615         int             aclbsize;       /* size of acl list in bytes */
5616         aclent_t        *aaclp;
5617
5618         if (ap->a_type != ACL_TYPE_NFS4)
5619                 return (EINVAL);
5620
5621         if (ap->a_aclp == NULL)
5622                 return (EINVAL);
5623
5624         if (ap->a_aclp->acl_cnt < 1 || ap->a_aclp->acl_cnt > MAX_ACL_ENTRIES)
5625                 return (EINVAL);
5626
5627         /*
5628          * With NFSv4 ACLs, chmod(2) may need to add additional entries,
5629          * splitting every entry into two and appending "canonical six"
5630          * entries at the end.  Don't allow for setting an ACL that would
5631          * cause chmod(2) to run out of ACL entries.
5632          */
5633         if (ap->a_aclp->acl_cnt * 2 + 6 > ACL_MAX_ENTRIES)
5634                 return (ENOSPC);
5635
5636         error = acl_nfs4_check(ap->a_aclp, ap->a_vp->v_type == VDIR);
5637         if (error != 0)
5638                 return (error);
5639
5640         vsecattr.vsa_mask = VSA_ACE;
5641         aclbsize = ap->a_aclp->acl_cnt * sizeof (ace_t);
5642         vsecattr.vsa_aclentp = kmem_alloc(aclbsize, KM_SLEEP);
5643         aaclp = vsecattr.vsa_aclentp;
5644         vsecattr.vsa_aclentsz = aclbsize;
5645
5646         aces_from_acl(vsecattr.vsa_aclentp, &vsecattr.vsa_aclcnt, ap->a_aclp);
5647         error = zfs_setsecattr(VTOZ(ap->a_vp), &vsecattr, 0, ap->a_cred);
5648         kmem_free(aaclp, aclbsize);
5649
5650         return (error);
5651 }
5652
5653 #ifndef _SYS_SYSPROTO_H_
5654 struct vop_aclcheck_args {
5655         struct vnode *vp;
5656         acl_type_t type;
5657         struct acl *aclp;
5658         struct ucred *cred;
5659         struct thread *td;
5660 };
5661 #endif
5662
5663 static int
5664 zfs_freebsd_aclcheck(struct vop_aclcheck_args *ap)
5665 {
5666
5667         return (EOPNOTSUPP);
5668 }
5669
5670 static int
5671 zfs_vptocnp(struct vop_vptocnp_args *ap)
5672 {
5673         vnode_t *covered_vp;
5674         vnode_t *vp = ap->a_vp;
5675         zfsvfs_t *zfsvfs = vp->v_vfsp->vfs_data;
5676         znode_t *zp = VTOZ(vp);
5677         int ltype;
5678         int error;
5679
5680         ZFS_ENTER(zfsvfs);
5681         ZFS_VERIFY_ZP(zp);
5682
5683         /*
5684          * If we are a snapshot mounted under .zfs, run the operation
5685          * on the covered vnode.
5686          */
5687         if (zp->z_id != zfsvfs->z_root || zfsvfs->z_parent == zfsvfs) {
5688                 char name[MAXNAMLEN + 1];
5689                 znode_t *dzp;
5690                 size_t len;
5691
5692                 error = zfs_znode_parent_and_name(zp, &dzp, name);
5693                 if (error == 0) {
5694                         len = strlen(name);
5695                         if (*ap->a_buflen < len)
5696                                 error = SET_ERROR(ENOMEM);
5697                 }
5698                 if (error == 0) {
5699                         *ap->a_buflen -= len;
5700                         bcopy(name, ap->a_buf + *ap->a_buflen, len);
5701                         *ap->a_vpp = ZTOV(dzp);
5702                 }
5703                 ZFS_EXIT(zfsvfs);
5704                 return (error);
5705         }
5706         ZFS_EXIT(zfsvfs);
5707
5708         covered_vp = vp->v_mount->mnt_vnodecovered;
5709 #if __FreeBSD_version >= 1300045
5710         enum vgetstate vs = vget_prep(covered_vp);
5711 #else
5712         vhold(covered_vp);
5713 #endif
5714         ltype = VOP_ISLOCKED(vp);
5715         VOP_UNLOCK1(vp);
5716 #if __FreeBSD_version >= 1300045
5717         error = vget_finish(covered_vp, LK_SHARED, vs);
5718 #else
5719         error = vget(covered_vp, LK_SHARED | LK_VNHELD, curthread);
5720 #endif
5721         if (error == 0) {
5722 #if __FreeBSD_version >= 1300123
5723                 error = VOP_VPTOCNP(covered_vp, ap->a_vpp, ap->a_buf,
5724                     ap->a_buflen);
5725 #else
5726                 error = VOP_VPTOCNP(covered_vp, ap->a_vpp, ap->a_cred,
5727                     ap->a_buf, ap->a_buflen);
5728 #endif
5729                 vput(covered_vp);
5730         }
5731         vn_lock(vp, ltype | LK_RETRY);
5732         if (VN_IS_DOOMED(vp))
5733                 error = SET_ERROR(ENOENT);
5734         return (error);
5735 }
5736
5737 #ifdef DIAGNOSTIC
5738 #ifndef _SYS_SYSPROTO_H_
5739 struct vop_lock1_args {
5740         struct vnode *a_vp;
5741         int a_flags;
5742         char *file;
5743         int line;
5744 };
5745 #endif
5746
5747 static int
5748 zfs_lock(struct vop_lock1_args *ap)
5749 {
5750         vnode_t *vp;
5751         znode_t *zp;
5752         int err;
5753
5754 #if __FreeBSD_version >= 1300064
5755         err = vop_lock(ap);
5756 #else
5757         err = vop_stdlock(ap);
5758 #endif
5759         if (err == 0 && (ap->a_flags & LK_NOWAIT) == 0) {
5760                 vp = ap->a_vp;
5761                 zp = vp->v_data;
5762                 if (vp->v_mount != NULL && !VN_IS_DOOMED(vp) &&
5763                     zp != NULL && (zp->z_pflags & ZFS_XATTR) == 0)
5764                         VERIFY(!RRM_LOCK_HELD(&zp->z_zfsvfs->z_teardown_lock));
5765         }
5766         return (err);
5767 }
5768 #endif
5769
5770 struct vop_vector zfs_vnodeops;
5771 struct vop_vector zfs_fifoops;
5772 struct vop_vector zfs_shareops;
5773
5774 struct vop_vector zfs_vnodeops = {
5775         .vop_default =          &default_vnodeops,
5776         .vop_inactive =         zfs_freebsd_inactive,
5777 #if __FreeBSD_version >= 1300042
5778         .vop_need_inactive =    zfs_freebsd_need_inactive,
5779 #endif
5780         .vop_reclaim =          zfs_freebsd_reclaim,
5781 #if __FreeBSD_version >= 1300102
5782         .vop_fplookup_vexec = zfs_freebsd_fplookup_vexec,
5783 #endif
5784         .vop_access =           zfs_freebsd_access,
5785         .vop_allocate =         VOP_EINVAL,
5786         .vop_lookup =           zfs_cache_lookup,
5787         .vop_cachedlookup =     zfs_freebsd_cachedlookup,
5788         .vop_getattr =          zfs_freebsd_getattr,
5789         .vop_setattr =          zfs_freebsd_setattr,
5790         .vop_create =           zfs_freebsd_create,
5791         .vop_mknod =            (vop_mknod_t *)zfs_freebsd_create,
5792         .vop_mkdir =            zfs_freebsd_mkdir,
5793         .vop_readdir =          zfs_freebsd_readdir,
5794         .vop_fsync =            zfs_freebsd_fsync,
5795         .vop_open =             zfs_freebsd_open,
5796         .vop_close =            zfs_freebsd_close,
5797         .vop_rmdir =            zfs_freebsd_rmdir,
5798         .vop_ioctl =            zfs_freebsd_ioctl,
5799         .vop_link =             zfs_freebsd_link,
5800         .vop_symlink =          zfs_freebsd_symlink,
5801         .vop_readlink =         zfs_freebsd_readlink,
5802         .vop_read =             zfs_freebsd_read,
5803         .vop_write =            zfs_freebsd_write,
5804         .vop_remove =           zfs_freebsd_remove,
5805         .vop_rename =           zfs_freebsd_rename,
5806         .vop_pathconf =         zfs_freebsd_pathconf,
5807         .vop_bmap =             zfs_freebsd_bmap,
5808         .vop_fid =              zfs_freebsd_fid,
5809         .vop_getextattr =       zfs_getextattr,
5810         .vop_deleteextattr =    zfs_deleteextattr,
5811         .vop_setextattr =       zfs_setextattr,
5812         .vop_listextattr =      zfs_listextattr,
5813         .vop_getacl =           zfs_freebsd_getacl,
5814         .vop_setacl =           zfs_freebsd_setacl,
5815         .vop_aclcheck =         zfs_freebsd_aclcheck,
5816         .vop_getpages =         zfs_freebsd_getpages,
5817         .vop_putpages =         zfs_freebsd_putpages,
5818         .vop_vptocnp =          zfs_vptocnp,
5819 #if __FreeBSD_version >= 1300064
5820 #ifdef DIAGNOSTIC
5821         .vop_lock1 =            zfs_lock,
5822 #else
5823         .vop_lock1 =            vop_lock,
5824 #endif
5825         .vop_unlock =           vop_unlock,
5826         .vop_islocked =         vop_islocked,
5827 #else
5828 #ifdef DIAGNOSTIC
5829         .vop_lock1 =            zfs_lock,
5830 #endif
5831 #endif
5832 };
5833 VFS_VOP_VECTOR_REGISTER(zfs_vnodeops);
5834
5835 struct vop_vector zfs_fifoops = {
5836         .vop_default =          &fifo_specops,
5837         .vop_fsync =            zfs_freebsd_fsync,
5838 #if __FreeBSD_version >= 1300102
5839         .vop_fplookup_vexec = zfs_freebsd_fplookup_vexec,
5840 #endif
5841         .vop_access =           zfs_freebsd_access,
5842         .vop_getattr =          zfs_freebsd_getattr,
5843         .vop_inactive =         zfs_freebsd_inactive,
5844         .vop_read =             VOP_PANIC,
5845         .vop_reclaim =          zfs_freebsd_reclaim,
5846         .vop_setattr =          zfs_freebsd_setattr,
5847         .vop_write =            VOP_PANIC,
5848         .vop_pathconf =         zfs_freebsd_pathconf,
5849         .vop_fid =              zfs_freebsd_fid,
5850         .vop_getacl =           zfs_freebsd_getacl,
5851         .vop_setacl =           zfs_freebsd_setacl,
5852         .vop_aclcheck =         zfs_freebsd_aclcheck,
5853 };
5854 VFS_VOP_VECTOR_REGISTER(zfs_fifoops);
5855
5856 /*
5857  * special share hidden files vnode operations template
5858  */
5859 struct vop_vector zfs_shareops = {
5860         .vop_default =          &default_vnodeops,
5861 #if __FreeBSD_version >= 1300121
5862         .vop_fplookup_vexec =   VOP_EAGAIN,
5863 #endif
5864         .vop_access =           zfs_freebsd_access,
5865         .vop_inactive =         zfs_freebsd_inactive,
5866         .vop_reclaim =          zfs_freebsd_reclaim,
5867         .vop_fid =              zfs_freebsd_fid,
5868         .vop_pathconf =         zfs_freebsd_pathconf,
5869 };
5870 VFS_VOP_VECTOR_REGISTER(zfs_shareops);