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