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