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