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