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