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