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