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