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