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