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