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