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