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