]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
MFC r212650: tmpfs, zfs + sendfile: mark page bits as valid after
[FreeBSD/stable/8.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / zfs_vnops.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24
25 /* Portions Copyright 2007 Jeremy Teo */
26
27 #include <sys/types.h>
28 #include <sys/param.h>
29 #include <sys/time.h>
30 #include <sys/systm.h>
31 #include <sys/sysmacros.h>
32 #include <sys/resource.h>
33 #include <sys/vfs.h>
34 #include <sys/vnode.h>
35 #include <sys/file.h>
36 #include <sys/stat.h>
37 #include <sys/kmem.h>
38 #include <sys/taskq.h>
39 #include <sys/uio.h>
40 #include <sys/atomic.h>
41 #include <sys/namei.h>
42 #include <sys/mman.h>
43 #include <sys/cmn_err.h>
44 #include <sys/errno.h>
45 #include <sys/unistd.h>
46 #include <sys/zfs_dir.h>
47 #include <sys/zfs_ioctl.h>
48 #include <sys/fs/zfs.h>
49 #include <sys/dmu.h>
50 #include <sys/spa.h>
51 #include <sys/txg.h>
52 #include <sys/dbuf.h>
53 #include <sys/zap.h>
54 #include <sys/dirent.h>
55 #include <sys/policy.h>
56 #include <sys/sunddi.h>
57 #include <sys/filio.h>
58 #include <sys/sid.h>
59 #include <sys/zfs_ctldir.h>
60 #include <sys/zfs_fuid.h>
61 #include <sys/dnlc.h>
62 #include <sys/zfs_rlock.h>
63 #include <sys/extdirent.h>
64 #include <sys/kidmap.h>
65 #include <sys/bio.h>
66 #include <sys/buf.h>
67 #include <sys/sf_buf.h>
68 #include <sys/sched.h>
69 #include <sys/acl.h>
70
71 /*
72  * Programming rules.
73  *
74  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
75  * properly lock its in-core state, create a DMU transaction, do the work,
76  * record this work in the intent log (ZIL), commit the DMU transaction,
77  * and wait for the intent log to commit if it is a synchronous operation.
78  * Moreover, the vnode ops must work in both normal and log replay context.
79  * The ordering of events is important to avoid deadlocks and references
80  * to freed memory.  The example below illustrates the following Big Rules:
81  *
82  *  (1) A check must be made in each zfs thread for a mounted file system.
83  *      This is done avoiding races using ZFS_ENTER(zfsvfs).
84  *      A ZFS_EXIT(zfsvfs) is needed before all returns.  Any znodes
85  *      must be checked with ZFS_VERIFY_ZP(zp).  Both of these macros
86  *      can return EIO from the calling function.
87  *
88  *  (2) VN_RELE() should always be the last thing except for zil_commit()
89  *      (if necessary) and ZFS_EXIT(). This is for 3 reasons:
90  *      First, if it's the last reference, the vnode/znode
91  *      can be freed, so the zp may point to freed memory.  Second, the last
92  *      reference will call zfs_zinactive(), which may induce a lot of work --
93  *      pushing cached pages (which acquires range locks) and syncing out
94  *      cached atime changes.  Third, zfs_zinactive() may require a new tx,
95  *      which could deadlock the system if you were already holding one.
96  *      If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
97  *
98  *  (3) All range locks must be grabbed before calling dmu_tx_assign(),
99  *      as they can span dmu_tx_assign() calls.
100  *
101  *  (4) Always pass TXG_NOWAIT as the second argument to dmu_tx_assign().
102  *      This is critical because we don't want to block while holding locks.
103  *      Note, in particular, that if a lock is sometimes acquired before
104  *      the tx assigns, and sometimes after (e.g. z_lock), then failing to
105  *      use a non-blocking assign can deadlock the system.  The scenario:
106  *
107  *      Thread A has grabbed a lock before calling dmu_tx_assign().
108  *      Thread B is in an already-assigned tx, and blocks for this lock.
109  *      Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
110  *      forever, because the previous txg can't quiesce until B's tx commits.
111  *
112  *      If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
113  *      then drop all locks, call dmu_tx_wait(), and try again.
114  *
115  *  (5) If the operation succeeded, generate the intent log entry for it
116  *      before dropping locks.  This ensures that the ordering of events
117  *      in the intent log matches the order in which they actually occurred.
118  *      During ZIL replay the zfs_log_* functions will update the sequence
119  *      number to indicate the zil transaction has replayed.
120  *
121  *  (6) At the end of each vnode op, the DMU tx must always commit,
122  *      regardless of whether there were any errors.
123  *
124  *  (7) After dropping all locks, invoke zil_commit(zilog, seq, foid)
125  *      to ensure that synchronous semantics are provided when necessary.
126  *
127  * In general, this is how things should be ordered in each vnode op:
128  *
129  *      ZFS_ENTER(zfsvfs);              // exit if unmounted
130  * top:
131  *      zfs_dirent_lock(&dl, ...)       // lock directory entry (may VN_HOLD())
132  *      rw_enter(...);                  // grab any other locks you need
133  *      tx = dmu_tx_create(...);        // get DMU tx
134  *      dmu_tx_hold_*();                // hold each object you might modify
135  *      error = dmu_tx_assign(tx, TXG_NOWAIT);  // try to assign
136  *      if (error) {
137  *              rw_exit(...);           // drop locks
138  *              zfs_dirent_unlock(dl);  // unlock directory entry
139  *              VN_RELE(...);           // release held vnodes
140  *              if (error == ERESTART) {
141  *                      dmu_tx_wait(tx);
142  *                      dmu_tx_abort(tx);
143  *                      goto top;
144  *              }
145  *              dmu_tx_abort(tx);       // abort DMU tx
146  *              ZFS_EXIT(zfsvfs);       // finished in zfs
147  *              return (error);         // really out of space
148  *      }
149  *      error = do_real_work();         // do whatever this VOP does
150  *      if (error == 0)
151  *              zfs_log_*(...);         // on success, make ZIL entry
152  *      dmu_tx_commit(tx);              // commit DMU tx -- error or not
153  *      rw_exit(...);                   // drop locks
154  *      zfs_dirent_unlock(dl);          // unlock directory entry
155  *      VN_RELE(...);                   // release held vnodes
156  *      zil_commit(zilog, seq, foid);   // synchronous when necessary
157  *      ZFS_EXIT(zfsvfs);               // finished in zfs
158  *      return (error);                 // done, report error
159  */
160
161 /* ARGSUSED */
162 static int
163 zfs_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
164 {
165         znode_t *zp = VTOZ(*vpp);
166         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
167
168         ZFS_ENTER(zfsvfs);
169         ZFS_VERIFY_ZP(zp);
170
171         if ((flag & FWRITE) && (zp->z_phys->zp_flags & ZFS_APPENDONLY) &&
172             ((flag & FAPPEND) == 0)) {
173                 ZFS_EXIT(zfsvfs);
174                 return (EPERM);
175         }
176
177         if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
178             ZTOV(zp)->v_type == VREG &&
179             !(zp->z_phys->zp_flags & ZFS_AV_QUARANTINED) &&
180             zp->z_phys->zp_size > 0) {
181                 if (fs_vscan(*vpp, cr, 0) != 0) {
182                         ZFS_EXIT(zfsvfs);
183                         return (EACCES);
184                 }
185         }
186
187         /* Keep a count of the synchronous opens in the znode */
188         if (flag & (FSYNC | FDSYNC))
189                 atomic_inc_32(&zp->z_sync_cnt);
190
191         ZFS_EXIT(zfsvfs);
192         return (0);
193 }
194
195 /* ARGSUSED */
196 static int
197 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
198     caller_context_t *ct)
199 {
200         znode_t *zp = VTOZ(vp);
201         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
202
203         ZFS_ENTER(zfsvfs);
204         ZFS_VERIFY_ZP(zp);
205
206         /* Decrement the synchronous opens in the znode */
207         if ((flag & (FSYNC | FDSYNC)) && (count == 1))
208                 atomic_dec_32(&zp->z_sync_cnt);
209
210         /*
211          * Clean up any locks held by this process on the vp.
212          */
213         cleanlocks(vp, ddi_get_pid(), 0);
214         cleanshares(vp, ddi_get_pid());
215
216         if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
217             ZTOV(zp)->v_type == VREG &&
218             !(zp->z_phys->zp_flags & ZFS_AV_QUARANTINED) &&
219             zp->z_phys->zp_size > 0)
220                 VERIFY(fs_vscan(vp, cr, 1) == 0);
221
222         ZFS_EXIT(zfsvfs);
223         return (0);
224 }
225
226 /*
227  * Lseek support for finding holes (cmd == _FIO_SEEK_HOLE) and
228  * data (cmd == _FIO_SEEK_DATA). "off" is an in/out parameter.
229  */
230 static int
231 zfs_holey(vnode_t *vp, u_long cmd, offset_t *off)
232 {
233         znode_t *zp = VTOZ(vp);
234         uint64_t noff = (uint64_t)*off; /* new offset */
235         uint64_t file_sz;
236         int error;
237         boolean_t hole;
238
239         file_sz = zp->z_phys->zp_size;
240         if (noff >= file_sz)  {
241                 return (ENXIO);
242         }
243
244         if (cmd == _FIO_SEEK_HOLE)
245                 hole = B_TRUE;
246         else
247                 hole = B_FALSE;
248
249         error = dmu_offset_next(zp->z_zfsvfs->z_os, zp->z_id, hole, &noff);
250
251         /* end of file? */
252         if ((error == ESRCH) || (noff > file_sz)) {
253                 /*
254                  * Handle the virtual hole at the end of file.
255                  */
256                 if (hole) {
257                         *off = file_sz;
258                         return (0);
259                 }
260                 return (ENXIO);
261         }
262
263         if (noff < *off)
264                 return (error);
265         *off = noff;
266         return (error);
267 }
268
269 /* ARGSUSED */
270 static int
271 zfs_ioctl(vnode_t *vp, u_long com, intptr_t data, int flag, cred_t *cred,
272     int *rvalp, caller_context_t *ct)
273 {
274         offset_t off;
275         int error;
276         zfsvfs_t *zfsvfs;
277         znode_t *zp;
278
279         switch (com) {
280         case _FIOFFS:
281                 return (0);
282
283                 /*
284                  * The following two ioctls are used by bfu.  Faking out,
285                  * necessary to avoid bfu errors.
286                  */
287         case _FIOGDIO:
288         case _FIOSDIO:
289                 return (0);
290
291         case _FIO_SEEK_DATA:
292         case _FIO_SEEK_HOLE:
293                 if (ddi_copyin((void *)data, &off, sizeof (off), flag))
294                         return (EFAULT);
295
296                 zp = VTOZ(vp);
297                 zfsvfs = zp->z_zfsvfs;
298                 ZFS_ENTER(zfsvfs);
299                 ZFS_VERIFY_ZP(zp);
300
301                 /* offset parameter is in/out */
302                 error = zfs_holey(vp, com, &off);
303                 ZFS_EXIT(zfsvfs);
304                 if (error)
305                         return (error);
306                 if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
307                         return (EFAULT);
308                 return (0);
309         }
310         return (ENOTTY);
311 }
312
313 static vm_page_t
314 page_lookup(vnode_t *vp, int64_t start, int64_t off, int64_t nbytes)
315 {
316         vm_object_t obj;
317         vm_page_t pp;
318
319         obj = vp->v_object;
320         VM_OBJECT_LOCK_ASSERT(obj, MA_OWNED);
321
322         for (;;) {
323                 if ((pp = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
324                     vm_page_is_valid(pp, (vm_offset_t)off, nbytes)) {
325                         if (vm_page_sleep_if_busy(pp, FALSE, "zfsmwb"))
326                                 continue;
327                         vm_page_busy(pp);
328                         vm_page_lock_queues();
329                         vm_page_undirty(pp);
330                         vm_page_unlock_queues();
331                 } else {
332                         if (__predict_false(obj->cache != NULL)) {
333                                 vm_page_cache_free(obj, OFF_TO_IDX(start),
334                                     OFF_TO_IDX(start) + 1);
335                         }
336                         pp = NULL;
337                 }
338                 break;
339         }
340         return (pp);
341 }
342
343 static void
344 page_unlock(vm_page_t pp)
345 {
346
347         vm_page_wakeup(pp);
348 }
349
350 static caddr_t
351 zfs_map_page(vm_page_t pp, struct sf_buf **sfp)
352 {
353
354         sched_pin();
355         *sfp = sf_buf_alloc(pp, SFB_CPUPRIVATE);
356         return ((caddr_t)sf_buf_kva(*sfp));
357 }
358
359 static void
360 zfs_unmap_page(struct sf_buf *sf)
361 {
362
363         sf_buf_free(sf);
364         sched_unpin();
365 }
366
367
368 /*
369  * When a file is memory mapped, we must keep the IO data synchronized
370  * between the DMU cache and the memory mapped pages.  What this means:
371  *
372  * On Write:    If we find a memory mapped page, we write to *both*
373  *              the page and the dmu buffer.
374  */
375
376 static void
377 update_pages(vnode_t *vp, int64_t start, int len, objset_t *os, uint64_t oid,
378     int segflg, dmu_tx_t *tx)
379 {
380         vm_object_t obj;
381         struct sf_buf *sf;
382         int64_t off;
383
384         ASSERT(vp->v_mount != NULL);
385         obj = vp->v_object;
386         ASSERT(obj != NULL);
387
388         off = start & PAGEOFFSET;
389         VM_OBJECT_LOCK(obj);
390         for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
391                 vm_page_t pp;
392                 uint64_t nbytes = MIN(PAGESIZE - off, len);
393
394                 if ((pp = page_lookup(vp, start, off, nbytes)) != NULL) {
395                         caddr_t va;
396
397                         VM_OBJECT_UNLOCK(obj);
398                         va = zfs_map_page(pp, &sf);
399                         if (segflg == UIO_NOCOPY) {
400                                 (void) dmu_write(os, oid, start+off, nbytes,
401                                     va+off, tx);
402                         } else {
403                                 (void) dmu_read(os, oid, start+off, nbytes,
404                                     va+off, DMU_READ_PREFETCH);;
405                         }
406                         zfs_unmap_page(sf);
407                         VM_OBJECT_LOCK(obj);
408                         page_unlock(pp);
409
410                 }
411                 len -= nbytes;
412                 off = 0;
413         }
414         VM_OBJECT_UNLOCK(obj);
415 }
416
417 /*
418  * When a file is memory mapped, we must keep the IO data synchronized
419  * between the DMU cache and the memory mapped pages.  What this means:
420  *
421  * On Read:     We "read" preferentially from memory mapped pages,
422  *              else we default from the dmu buffer.
423  *
424  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
425  *      the file is memory mapped.
426  */
427 static int
428 mappedread(vnode_t *vp, int nbytes, uio_t *uio)
429 {
430         znode_t *zp = VTOZ(vp);
431         objset_t *os = zp->z_zfsvfs->z_os;
432         vm_object_t obj;
433         vm_page_t m;
434         struct sf_buf *sf;
435         int64_t start, off;
436         caddr_t va;
437         int len = nbytes;
438         int error = 0;
439         uint64_t dirbytes;
440
441         ASSERT(vp->v_mount != NULL);
442         obj = vp->v_object;
443         ASSERT(obj != NULL);
444
445         start = uio->uio_loffset;
446         off = start & PAGEOFFSET;
447         dirbytes = 0;
448         VM_OBJECT_LOCK(obj);
449         for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
450                 uint64_t bytes = MIN(PAGESIZE - off, len);
451
452 again:
453                 if ((m = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
454                     vm_page_is_valid(m, (vm_offset_t)off, bytes)) {
455                         if (vm_page_sleep_if_busy(m, FALSE, "zfsmrb"))
456                                 goto again;
457                         vm_page_busy(m);
458                         VM_OBJECT_UNLOCK(obj);
459                         if (dirbytes > 0) {
460                                 error = dmu_read_uio(os, zp->z_id, uio,
461                                     dirbytes);
462                                 dirbytes = 0;
463                         }
464                         if (error == 0) {
465                                 sched_pin();
466                                 sf = sf_buf_alloc(m, SFB_CPUPRIVATE);
467                                 va = (caddr_t)sf_buf_kva(sf);
468                                 error = uiomove(va + off, bytes, UIO_READ, uio);
469                                 sf_buf_free(sf);
470                                 sched_unpin();
471                         }
472                         VM_OBJECT_LOCK(obj);
473                         vm_page_wakeup(m);
474                 } else if (m != NULL && uio->uio_segflg == UIO_NOCOPY) {
475                         /*
476                          * The code below is here to make sendfile(2) work
477                          * correctly with ZFS. As pointed out by ups@
478                          * sendfile(2) should be changed to use VOP_GETPAGES(),
479                          * but it pessimize performance of sendfile/UFS, that's
480                          * why I handle this special case in ZFS code.
481                          */
482                         if (vm_page_sleep_if_busy(m, FALSE, "zfsmrb"))
483                                 goto again;
484                         vm_page_busy(m);
485                         VM_OBJECT_UNLOCK(obj);
486                         if (dirbytes > 0) {
487                                 error = dmu_read_uio(os, zp->z_id, uio,
488                                     dirbytes);
489                                 dirbytes = 0;
490                         }
491                         if (error == 0) {
492                                 sched_pin();
493                                 sf = sf_buf_alloc(m, SFB_CPUPRIVATE);
494                                 va = (caddr_t)sf_buf_kva(sf);
495                                 error = dmu_read(os, zp->z_id, start + off,
496                                     bytes, (void *)(va + off),
497                                     DMU_READ_PREFETCH);
498                                 sf_buf_free(sf);
499                                 sched_unpin();
500                         }
501                         VM_OBJECT_LOCK(obj);
502                         if (error == 0)
503                                 vm_page_set_valid(m, off, bytes);
504                         vm_page_wakeup(m);
505                         if (error == 0) {
506                                 uio->uio_resid -= bytes;
507                                 uio->uio_offset += bytes;
508                         }
509                 } else {
510                         dirbytes += bytes;
511                 }
512                 len -= bytes;
513                 off = 0;
514                 if (error)
515                         break;
516         }
517         VM_OBJECT_UNLOCK(obj);
518         if (error == 0 && dirbytes > 0)
519                 error = dmu_read_uio(os, zp->z_id, uio, dirbytes);
520         return (error);
521 }
522
523 offset_t zfs_read_chunk_size = 1024 * 1024; /* Tunable */
524
525 /*
526  * Read bytes from specified file into supplied buffer.
527  *
528  *      IN:     vp      - vnode of file to be read from.
529  *              uio     - structure supplying read location, range info,
530  *                        and return buffer.
531  *              ioflag  - SYNC flags; used to provide FRSYNC semantics.
532  *              cr      - credentials of caller.
533  *              ct      - caller context
534  *
535  *      OUT:    uio     - updated offset and range, buffer filled.
536  *
537  *      RETURN: 0 if success
538  *              error code if failure
539  *
540  * Side Effects:
541  *      vp - atime updated if byte count > 0
542  */
543 /* ARGSUSED */
544 static int
545 zfs_read(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
546 {
547         znode_t         *zp = VTOZ(vp);
548         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
549         objset_t        *os;
550         ssize_t         n, nbytes;
551         int             error;
552         rl_t            *rl;
553
554         ZFS_ENTER(zfsvfs);
555         ZFS_VERIFY_ZP(zp);
556         os = zfsvfs->z_os;
557
558         if (zp->z_phys->zp_flags & ZFS_AV_QUARANTINED) {
559                 ZFS_EXIT(zfsvfs);
560                 return (EACCES);
561         }
562
563         /*
564          * Validate file offset
565          */
566         if (uio->uio_loffset < (offset_t)0) {
567                 ZFS_EXIT(zfsvfs);
568                 return (EINVAL);
569         }
570
571         /*
572          * Fasttrack empty reads
573          */
574         if (uio->uio_resid == 0) {
575                 ZFS_EXIT(zfsvfs);
576                 return (0);
577         }
578
579         /*
580          * Check for mandatory locks
581          */
582         if (MANDMODE((mode_t)zp->z_phys->zp_mode)) {
583                 if (error = chklock(vp, FREAD,
584                     uio->uio_loffset, uio->uio_resid, uio->uio_fmode, ct)) {
585                         ZFS_EXIT(zfsvfs);
586                         return (error);
587                 }
588         }
589
590         /*
591          * If we're in FRSYNC mode, sync out this znode before reading it.
592          */
593         if (ioflag & FRSYNC)
594                 zil_commit(zfsvfs->z_log, zp->z_last_itx, zp->z_id);
595
596         /*
597          * Lock the range against changes.
598          */
599         rl = zfs_range_lock(zp, uio->uio_loffset, uio->uio_resid, RL_READER);
600
601         /*
602          * If we are reading past end-of-file we can skip
603          * to the end; but we might still need to set atime.
604          */
605         if (uio->uio_loffset >= zp->z_phys->zp_size) {
606                 error = 0;
607                 goto out;
608         }
609
610         ASSERT(uio->uio_loffset < zp->z_phys->zp_size);
611         n = MIN(uio->uio_resid, zp->z_phys->zp_size - uio->uio_loffset);
612
613         while (n > 0) {
614                 nbytes = MIN(n, zfs_read_chunk_size -
615                     P2PHASE(uio->uio_loffset, zfs_read_chunk_size));
616
617                 if (vn_has_cached_data(vp))
618                         error = mappedread(vp, nbytes, uio);
619                 else
620                         error = dmu_read_uio(os, zp->z_id, uio, nbytes);
621                 if (error) {
622                         /* convert checksum errors into IO errors */
623                         if (error == ECKSUM)
624                                 error = EIO;
625                         break;
626                 }
627
628                 n -= nbytes;
629         }
630
631 out:
632         zfs_range_unlock(rl);
633
634         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
635         ZFS_EXIT(zfsvfs);
636         return (error);
637 }
638
639 /*
640  * Fault in the pages of the first n bytes specified by the uio structure.
641  * 1 byte in each page is touched and the uio struct is unmodified.
642  * Any error will exit this routine as this is only a best
643  * attempt to get the pages resident. This is a copy of ufs_trans_touch().
644  */
645 static void
646 zfs_prefault_write(ssize_t n, struct uio *uio)
647 {
648         struct iovec *iov;
649         ulong_t cnt, incr;
650         caddr_t p;
651
652         if (uio->uio_segflg != UIO_USERSPACE)
653                 return;
654
655         iov = uio->uio_iov;
656
657         while (n) {
658                 cnt = MIN(iov->iov_len, n);
659                 if (cnt == 0) {
660                         /* empty iov entry */
661                         iov++;
662                         continue;
663                 }
664                 n -= cnt;
665                 /*
666                  * touch each page in this segment.
667                  */
668                 p = iov->iov_base;
669                 while (cnt) {
670                         if (fubyte(p) == -1)
671                                 return;
672                         incr = MIN(cnt, PAGESIZE);
673                         p += incr;
674                         cnt -= incr;
675                 }
676                 /*
677                  * touch the last byte in case it straddles a page.
678                  */
679                 p--;
680                 if (fubyte(p) == -1)
681                         return;
682                 iov++;
683         }
684 }
685
686 /*
687  * Write the bytes to a file.
688  *
689  *      IN:     vp      - vnode of file to be written to.
690  *              uio     - structure supplying write location, range info,
691  *                        and data buffer.
692  *              ioflag  - IO_APPEND flag set if in append mode.
693  *              cr      - credentials of caller.
694  *              ct      - caller context (NFS/CIFS fem monitor only)
695  *
696  *      OUT:    uio     - updated offset and range.
697  *
698  *      RETURN: 0 if success
699  *              error code if failure
700  *
701  * Timestamps:
702  *      vp - ctime|mtime updated if byte count > 0
703  */
704 /* ARGSUSED */
705 static int
706 zfs_write(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
707 {
708         znode_t         *zp = VTOZ(vp);
709         rlim64_t        limit = MAXOFFSET_T;
710         ssize_t         start_resid = uio->uio_resid;
711         ssize_t         tx_bytes;
712         uint64_t        end_size;
713         dmu_tx_t        *tx;
714         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
715         zilog_t         *zilog;
716         offset_t        woff;
717         ssize_t         n, nbytes;
718         rl_t            *rl;
719         int             max_blksz = zfsvfs->z_max_blksz;
720         uint64_t        pflags;
721         int             error;
722         arc_buf_t       *abuf;
723
724         /*
725          * Fasttrack empty write
726          */
727         n = start_resid;
728         if (n == 0)
729                 return (0);
730
731         if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
732                 limit = MAXOFFSET_T;
733
734         ZFS_ENTER(zfsvfs);
735         ZFS_VERIFY_ZP(zp);
736
737         /*
738          * If immutable or not appending then return EPERM
739          */
740         pflags = zp->z_phys->zp_flags;
741         if ((pflags & (ZFS_IMMUTABLE | ZFS_READONLY)) ||
742             ((pflags & ZFS_APPENDONLY) && !(ioflag & FAPPEND) &&
743             (uio->uio_loffset < zp->z_phys->zp_size))) {
744                 ZFS_EXIT(zfsvfs);
745                 return (EPERM);
746         }
747
748         zilog = zfsvfs->z_log;
749
750         /*
751          * Pre-fault the pages to ensure slow (eg NFS) pages
752          * don't hold up txg.
753          */
754         zfs_prefault_write(n, uio);
755
756         /*
757          * If in append mode, set the io offset pointer to eof.
758          */
759         if (ioflag & IO_APPEND) {
760                 /*
761                  * Range lock for a file append:
762                  * The value for the start of range will be determined by
763                  * zfs_range_lock() (to guarantee append semantics).
764                  * If this write will cause the block size to increase,
765                  * zfs_range_lock() will lock the entire file, so we must
766                  * later reduce the range after we grow the block size.
767                  */
768                 rl = zfs_range_lock(zp, 0, n, RL_APPEND);
769                 if (rl->r_len == UINT64_MAX) {
770                         /* overlocked, zp_size can't change */
771                         woff = uio->uio_loffset = zp->z_phys->zp_size;
772                 } else {
773                         woff = uio->uio_loffset = rl->r_off;
774                 }
775         } else {
776                 woff = uio->uio_loffset;
777                 /*
778                  * Validate file offset
779                  */
780                 if (woff < 0) {
781                         ZFS_EXIT(zfsvfs);
782                         return (EINVAL);
783                 }
784
785                 /*
786                  * If we need to grow the block size then zfs_range_lock()
787                  * will lock a wider range than we request here.
788                  * Later after growing the block size we reduce the range.
789                  */
790                 rl = zfs_range_lock(zp, woff, n, RL_WRITER);
791         }
792
793         if (woff >= limit) {
794                 zfs_range_unlock(rl);
795                 ZFS_EXIT(zfsvfs);
796                 return (EFBIG);
797         }
798
799         if ((woff + n) > limit || woff > (limit - n))
800                 n = limit - woff;
801
802         /*
803          * Check for mandatory locks
804          */
805         if (MANDMODE((mode_t)zp->z_phys->zp_mode) &&
806             (error = chklock(vp, FWRITE, woff, n, uio->uio_fmode, ct)) != 0) {
807                 zfs_range_unlock(rl);
808                 ZFS_EXIT(zfsvfs);
809                 return (error);
810         }
811         end_size = MAX(zp->z_phys->zp_size, woff + n);
812
813         /*
814          * Write the file in reasonable size chunks.  Each chunk is written
815          * in a separate transaction; this keeps the intent log records small
816          * and allows us to do more fine-grained space accounting.
817          */
818         while (n > 0) {
819                 abuf = NULL;
820                 woff = uio->uio_loffset;
821
822 again:
823                 if (zfs_usergroup_overquota(zfsvfs,
824                     B_FALSE, zp->z_phys->zp_uid) ||
825                     zfs_usergroup_overquota(zfsvfs,
826                     B_TRUE, zp->z_phys->zp_gid)) {
827                         if (abuf != NULL)
828                                 dmu_return_arcbuf(abuf);
829                         error = EDQUOT;
830                         break;
831                 }
832
833                 /*
834                  * If dmu_assign_arcbuf() is expected to execute with minimum
835                  * overhead loan an arc buffer and copy user data to it before
836                  * we enter a txg.  This avoids holding a txg forever while we
837                  * pagefault on a hanging NFS server mapping.
838                  */
839                 if (abuf == NULL && n >= max_blksz &&
840                     woff >= zp->z_phys->zp_size &&
841                     P2PHASE(woff, max_blksz) == 0 &&
842                     zp->z_blksz == max_blksz) {
843                         size_t cbytes;
844
845                         abuf = dmu_request_arcbuf(zp->z_dbuf, max_blksz);
846                         ASSERT(abuf != NULL);
847                         ASSERT(arc_buf_size(abuf) == max_blksz);
848                         if (error = uiocopy(abuf->b_data, max_blksz,
849                             UIO_WRITE, uio, &cbytes)) {
850                                 dmu_return_arcbuf(abuf);
851                                 break;
852                         }
853                         ASSERT(cbytes == max_blksz);
854                 }
855
856                 /*
857                  * Start a transaction.
858                  */
859                 tx = dmu_tx_create(zfsvfs->z_os);
860                 dmu_tx_hold_bonus(tx, zp->z_id);
861                 dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
862                 error = dmu_tx_assign(tx, TXG_NOWAIT);
863                 if (error) {
864                         if (error == ERESTART) {
865                                 dmu_tx_wait(tx);
866                                 dmu_tx_abort(tx);
867                                 goto again;
868                         }
869                         dmu_tx_abort(tx);
870                         if (abuf != NULL)
871                                 dmu_return_arcbuf(abuf);
872                         break;
873                 }
874
875                 /*
876                  * If zfs_range_lock() over-locked we grow the blocksize
877                  * and then reduce the lock range.  This will only happen
878                  * on the first iteration since zfs_range_reduce() will
879                  * shrink down r_len to the appropriate size.
880                  */
881                 if (rl->r_len == UINT64_MAX) {
882                         uint64_t new_blksz;
883
884                         if (zp->z_blksz > max_blksz) {
885                                 ASSERT(!ISP2(zp->z_blksz));
886                                 new_blksz = MIN(end_size, SPA_MAXBLOCKSIZE);
887                         } else {
888                                 new_blksz = MIN(end_size, max_blksz);
889                         }
890                         zfs_grow_blocksize(zp, new_blksz, tx);
891                         zfs_range_reduce(rl, woff, n);
892                 }
893
894                 /*
895                  * XXX - should we really limit each write to z_max_blksz?
896                  * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
897                  */
898                 nbytes = MIN(n, max_blksz - P2PHASE(woff, max_blksz));
899
900                 if (woff + nbytes > zp->z_phys->zp_size)
901                         vnode_pager_setsize(vp, woff + nbytes);
902
903                 if (abuf == NULL) {
904                         tx_bytes = uio->uio_resid;
905                         error = dmu_write_uio(zfsvfs->z_os, zp->z_id, uio,
906                             nbytes, tx);
907                         tx_bytes -= uio->uio_resid;
908                 } else {
909                         tx_bytes = nbytes;
910                         ASSERT(tx_bytes == max_blksz);
911                         dmu_assign_arcbuf(zp->z_dbuf, woff, abuf, tx);
912                         ASSERT(tx_bytes <= uio->uio_resid);
913                         uioskip(uio, tx_bytes);
914                 }
915
916                 /*
917                  * XXXPJD: There are some cases (triggered by fsx) where
918                  *         vn_has_cached_data(vp) returns false when it should
919                  *         return true. This should be investigated.
920                  */
921 #if 0
922                 if (tx_bytes && vn_has_cached_data(vp))
923 #else
924                 if (tx_bytes && vp->v_object != NULL)
925 #endif
926                 {
927                         update_pages(vp, woff, tx_bytes, zfsvfs->z_os,
928                             zp->z_id, uio->uio_segflg, tx);
929                 }
930
931                 /*
932                  * If we made no progress, we're done.  If we made even
933                  * partial progress, update the znode and ZIL accordingly.
934                  */
935                 if (tx_bytes == 0) {
936                         dmu_tx_commit(tx);
937                         ASSERT(error != 0);
938                         break;
939                 }
940
941                 /*
942                  * Clear Set-UID/Set-GID bits on successful write if not
943                  * privileged and at least one of the excute bits is set.
944                  *
945                  * It would be nice to to this after all writes have
946                  * been done, but that would still expose the ISUID/ISGID
947                  * to another app after the partial write is committed.
948                  *
949                  * Note: we don't call zfs_fuid_map_id() here because
950                  * user 0 is not an ephemeral uid.
951                  */
952                 mutex_enter(&zp->z_acl_lock);
953                 if ((zp->z_phys->zp_mode & (S_IXUSR | (S_IXUSR >> 3) |
954                     (S_IXUSR >> 6))) != 0 &&
955                     (zp->z_phys->zp_mode & (S_ISUID | S_ISGID)) != 0 &&
956                     secpolicy_vnode_setid_retain(vp, cr,
957                     (zp->z_phys->zp_mode & S_ISUID) != 0 &&
958                     zp->z_phys->zp_uid == 0) != 0) {
959                         zp->z_phys->zp_mode &= ~(S_ISUID | S_ISGID);
960                 }
961                 mutex_exit(&zp->z_acl_lock);
962
963                 /*
964                  * Update time stamp.  NOTE: This marks the bonus buffer as
965                  * dirty, so we don't have to do it again for zp_size.
966                  */
967                 zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
968
969                 /*
970                  * Update the file size (zp_size) if it has changed;
971                  * account for possible concurrent updates.
972                  */
973                 while ((end_size = zp->z_phys->zp_size) < uio->uio_loffset)
974                         (void) atomic_cas_64(&zp->z_phys->zp_size, end_size,
975                             uio->uio_loffset);
976                 zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, ioflag);
977                 dmu_tx_commit(tx);
978
979                 if (error != 0)
980                         break;
981                 ASSERT(tx_bytes == nbytes);
982                 n -= nbytes;
983         }
984
985         zfs_range_unlock(rl);
986
987         /*
988          * If we're in replay mode, or we made no progress, return error.
989          * Otherwise, it's at least a partial write, so it's successful.
990          */
991         if (zfsvfs->z_replay || uio->uio_resid == start_resid) {
992                 ZFS_EXIT(zfsvfs);
993                 return (error);
994         }
995
996         if (ioflag & (FSYNC | FDSYNC))
997                 zil_commit(zilog, zp->z_last_itx, zp->z_id);
998
999         ZFS_EXIT(zfsvfs);
1000         return (0);
1001 }
1002
1003 void
1004 zfs_get_done(dmu_buf_t *db, void *vzgd)
1005 {
1006         zgd_t *zgd = (zgd_t *)vzgd;
1007         rl_t *rl = zgd->zgd_rl;
1008         vnode_t *vp = ZTOV(rl->r_zp);
1009         objset_t *os = rl->r_zp->z_zfsvfs->z_os;
1010         int vfslocked;
1011
1012         vfslocked = VFS_LOCK_GIANT(vp->v_vfsp);
1013         dmu_buf_rele(db, vzgd);
1014         zfs_range_unlock(rl);
1015         /*
1016          * Release the vnode asynchronously as we currently have the
1017          * txg stopped from syncing.
1018          */
1019         VN_RELE_ASYNC(vp, dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1020         zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
1021         kmem_free(zgd, sizeof (zgd_t));
1022         VFS_UNLOCK_GIANT(vfslocked);
1023 }
1024
1025 /*
1026  * Get data to generate a TX_WRITE intent log record.
1027  */
1028 int
1029 zfs_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
1030 {
1031         zfsvfs_t *zfsvfs = arg;
1032         objset_t *os = zfsvfs->z_os;
1033         znode_t *zp;
1034         uint64_t off = lr->lr_offset;
1035         dmu_buf_t *db;
1036         rl_t *rl;
1037         zgd_t *zgd;
1038         int dlen = lr->lr_length;               /* length of user data */
1039         int error = 0;
1040
1041         ASSERT(zio);
1042         ASSERT(dlen != 0);
1043
1044         /*
1045          * Nothing to do if the file has been removed
1046          */
1047         if (zfs_zget(zfsvfs, lr->lr_foid, &zp) != 0)
1048                 return (ENOENT);
1049         if (zp->z_unlinked) {
1050                 /*
1051                  * Release the vnode asynchronously as we currently have the
1052                  * txg stopped from syncing.
1053                  */
1054                 VN_RELE_ASYNC(ZTOV(zp),
1055                     dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1056                 return (ENOENT);
1057         }
1058
1059         /*
1060          * Write records come in two flavors: immediate and indirect.
1061          * For small writes it's cheaper to store the data with the
1062          * log record (immediate); for large writes it's cheaper to
1063          * sync the data and get a pointer to it (indirect) so that
1064          * we don't have to write the data twice.
1065          */
1066         if (buf != NULL) { /* immediate write */
1067                 rl = zfs_range_lock(zp, off, dlen, RL_READER);
1068                 /* test for truncation needs to be done while range locked */
1069                 if (off >= zp->z_phys->zp_size) {
1070                         error = ENOENT;
1071                         goto out;
1072                 }
1073                 VERIFY(0 == dmu_read(os, lr->lr_foid, off, dlen, buf,
1074                     DMU_READ_NO_PREFETCH));
1075         } else { /* indirect write */
1076                 uint64_t boff; /* block starting offset */
1077
1078                 /*
1079                  * Have to lock the whole block to ensure when it's
1080                  * written out and it's checksum is being calculated
1081                  * that no one can change the data. We need to re-check
1082                  * blocksize after we get the lock in case it's changed!
1083                  */
1084                 for (;;) {
1085                         if (ISP2(zp->z_blksz)) {
1086                                 boff = P2ALIGN_TYPED(off, zp->z_blksz,
1087                                     uint64_t);
1088                         } else {
1089                                 boff = 0;
1090                         }
1091                         dlen = zp->z_blksz;
1092                         rl = zfs_range_lock(zp, boff, dlen, RL_READER);
1093                         if (zp->z_blksz == dlen)
1094                                 break;
1095                         zfs_range_unlock(rl);
1096                 }
1097                 /* test for truncation needs to be done while range locked */
1098                 if (off >= zp->z_phys->zp_size) {
1099                         error = ENOENT;
1100                         goto out;
1101                 }
1102                 zgd = (zgd_t *)kmem_alloc(sizeof (zgd_t), KM_SLEEP);
1103                 zgd->zgd_rl = rl;
1104                 zgd->zgd_zilog = zfsvfs->z_log;
1105                 zgd->zgd_bp = &lr->lr_blkptr;
1106                 VERIFY(0 == dmu_buf_hold(os, lr->lr_foid, boff, zgd, &db));
1107                 ASSERT(boff == db->db_offset);
1108                 lr->lr_blkoff = off - boff;
1109                 error = dmu_sync(zio, db, &lr->lr_blkptr,
1110                     lr->lr_common.lrc_txg, zfs_get_done, zgd);
1111                 ASSERT((error && error != EINPROGRESS) ||
1112                     lr->lr_length <= zp->z_blksz);
1113                 if (error == 0) {
1114                         /*
1115                          * dmu_sync() can compress a block of zeros to a null
1116                          * blkptr but the block size still needs to be passed
1117                          * through to replay.
1118                          */
1119                         BP_SET_LSIZE(&lr->lr_blkptr, db->db_size);
1120                         zil_add_block(zfsvfs->z_log, &lr->lr_blkptr);
1121                 }
1122
1123                 /*
1124                  * If we get EINPROGRESS, then we need to wait for a
1125                  * write IO initiated by dmu_sync() to complete before
1126                  * we can release this dbuf.  We will finish everything
1127                  * up in the zfs_get_done() callback.
1128                  */
1129                 if (error == EINPROGRESS) {
1130                         return (0);
1131                 } else if (error == EALREADY) {
1132                         lr->lr_common.lrc_txtype = TX_WRITE2;
1133                         error = 0;
1134                 }
1135                 dmu_buf_rele(db, zgd);
1136                 kmem_free(zgd, sizeof (zgd_t));
1137         }
1138 out:
1139         zfs_range_unlock(rl);
1140         /*
1141          * Release the vnode asynchronously as we currently have the
1142          * txg stopped from syncing.
1143          */
1144         VN_RELE_ASYNC(ZTOV(zp), dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1145         return (error);
1146 }
1147
1148 /*ARGSUSED*/
1149 static int
1150 zfs_access(vnode_t *vp, int mode, int flag, cred_t *cr,
1151     caller_context_t *ct)
1152 {
1153         znode_t *zp = VTOZ(vp);
1154         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1155         int error;
1156
1157         ZFS_ENTER(zfsvfs);
1158         ZFS_VERIFY_ZP(zp);
1159
1160         if (flag & V_ACE_MASK)
1161                 error = zfs_zaccess(zp, mode, flag, B_FALSE, cr);
1162         else
1163                 error = zfs_zaccess_rwx(zp, mode, flag, cr);
1164
1165         ZFS_EXIT(zfsvfs);
1166         return (error);
1167 }
1168
1169 /*
1170  * If vnode is for a device return a specfs vnode instead.
1171  */
1172 static int
1173 specvp_check(vnode_t **vpp, cred_t *cr)
1174 {
1175         int error = 0;
1176
1177         if (IS_DEVVP(*vpp)) {
1178                 struct vnode *svp;
1179
1180                 svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1181                 VN_RELE(*vpp);
1182                 if (svp == NULL)
1183                         error = ENOSYS;
1184                 *vpp = svp;
1185         }
1186         return (error);
1187 }
1188
1189
1190 /*
1191  * Lookup an entry in a directory, or an extended attribute directory.
1192  * If it exists, return a held vnode reference for it.
1193  *
1194  *      IN:     dvp     - vnode of directory to search.
1195  *              nm      - name of entry to lookup.
1196  *              pnp     - full pathname to lookup [UNUSED].
1197  *              flags   - LOOKUP_XATTR set if looking for an attribute.
1198  *              rdir    - root directory vnode [UNUSED].
1199  *              cr      - credentials of caller.
1200  *              ct      - caller context
1201  *              direntflags - directory lookup flags
1202  *              realpnp - returned pathname.
1203  *
1204  *      OUT:    vpp     - vnode of located entry, NULL if not found.
1205  *
1206  *      RETURN: 0 if success
1207  *              error code if failure
1208  *
1209  * Timestamps:
1210  *      NA
1211  */
1212 /* ARGSUSED */
1213 static int
1214 zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct componentname *cnp,
1215     int nameiop, cred_t *cr, kthread_t *td, int flags)
1216 {
1217         znode_t *zdp = VTOZ(dvp);
1218         zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
1219         int     error = 0;
1220         int *direntflags = NULL;
1221         void *realpnp = NULL;
1222
1223         /* fast path */
1224         if (!(flags & (LOOKUP_XATTR | FIGNORECASE))) {
1225
1226                 if (dvp->v_type != VDIR) {
1227                         return (ENOTDIR);
1228                 } else if (zdp->z_dbuf == NULL) {
1229                         return (EIO);
1230                 }
1231
1232                 if (nm[0] == 0 || (nm[0] == '.' && nm[1] == '\0')) {
1233                         error = zfs_fastaccesschk_execute(zdp, cr);
1234                         if (!error) {
1235                                 *vpp = dvp;
1236                                 VN_HOLD(*vpp);
1237                                 return (0);
1238                         }
1239                         return (error);
1240                 } else {
1241                         vnode_t *tvp = dnlc_lookup(dvp, nm);
1242
1243                         if (tvp) {
1244                                 error = zfs_fastaccesschk_execute(zdp, cr);
1245                                 if (error) {
1246                                         VN_RELE(tvp);
1247                                         return (error);
1248                                 }
1249                                 if (tvp == DNLC_NO_VNODE) {
1250                                         VN_RELE(tvp);
1251                                         return (ENOENT);
1252                                 } else {
1253                                         *vpp = tvp;
1254                                         return (specvp_check(vpp, cr));
1255                                 }
1256                         }
1257                 }
1258         }
1259
1260         DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp, char *, nm);
1261
1262         ZFS_ENTER(zfsvfs);
1263         ZFS_VERIFY_ZP(zdp);
1264
1265         *vpp = NULL;
1266
1267         if (flags & LOOKUP_XATTR) {
1268 #ifdef TODO
1269                 /*
1270                  * If the xattr property is off, refuse the lookup request.
1271                  */
1272                 if (!(zfsvfs->z_vfs->vfs_flag & VFS_XATTR)) {
1273                         ZFS_EXIT(zfsvfs);
1274                         return (EINVAL);
1275                 }
1276 #endif
1277
1278                 /*
1279                  * We don't allow recursive attributes..
1280                  * Maybe someday we will.
1281                  */
1282                 if (zdp->z_phys->zp_flags & ZFS_XATTR) {
1283                         ZFS_EXIT(zfsvfs);
1284                         return (EINVAL);
1285                 }
1286
1287                 if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr, flags)) {
1288                         ZFS_EXIT(zfsvfs);
1289                         return (error);
1290                 }
1291
1292                 /*
1293                  * Do we have permission to get into attribute directory?
1294                  */
1295
1296                 if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, 0,
1297                     B_FALSE, cr)) {
1298                         VN_RELE(*vpp);
1299                         *vpp = NULL;
1300                 }
1301
1302                 ZFS_EXIT(zfsvfs);
1303                 return (error);
1304         }
1305
1306         if (dvp->v_type != VDIR) {
1307                 ZFS_EXIT(zfsvfs);
1308                 return (ENOTDIR);
1309         }
1310
1311         /*
1312          * Check accessibility of directory.
1313          */
1314
1315         if (error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr)) {
1316                 ZFS_EXIT(zfsvfs);
1317                 return (error);
1318         }
1319
1320         if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
1321             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1322                 ZFS_EXIT(zfsvfs);
1323                 return (EILSEQ);
1324         }
1325
1326         error = zfs_dirlook(zdp, nm, vpp, flags, direntflags, realpnp);
1327         if (error == 0)
1328                 error = specvp_check(vpp, cr);
1329
1330         /* Translate errors and add SAVENAME when needed. */
1331         if (cnp->cn_flags & ISLASTCN) {
1332                 switch (nameiop) {
1333                 case CREATE:
1334                 case RENAME:
1335                         if (error == ENOENT) {
1336                                 error = EJUSTRETURN;
1337                                 cnp->cn_flags |= SAVENAME;
1338                                 break;
1339                         }
1340                         /* FALLTHROUGH */
1341                 case DELETE:
1342                         if (error == 0)
1343                                 cnp->cn_flags |= SAVENAME;
1344                         break;
1345                 }
1346         }
1347         if (error == 0 && (nm[0] != '.' || nm[1] != '\0')) {
1348                 int ltype = 0;
1349
1350                 if (cnp->cn_flags & ISDOTDOT) {
1351                         ltype = VOP_ISLOCKED(dvp);
1352                         VOP_UNLOCK(dvp, 0);
1353                 }
1354                 ZFS_EXIT(zfsvfs);
1355                 error = vn_lock(*vpp, cnp->cn_lkflags);
1356                 if (cnp->cn_flags & ISDOTDOT)
1357                         vn_lock(dvp, ltype | LK_RETRY);
1358                 if (error != 0) {
1359                         VN_RELE(*vpp);
1360                         *vpp = NULL;
1361                         return (error);
1362                 }
1363         } else {
1364                 ZFS_EXIT(zfsvfs);
1365         }
1366
1367 #ifdef FREEBSD_NAMECACHE
1368         /*
1369          * Insert name into cache (as non-existent) if appropriate.
1370          */
1371         if (error == ENOENT && (cnp->cn_flags & MAKEENTRY) && nameiop != CREATE)
1372                 cache_enter(dvp, *vpp, cnp);
1373         /*
1374          * Insert name into cache if appropriate.
1375          */
1376         if (error == 0 && (cnp->cn_flags & MAKEENTRY)) {
1377                 if (!(cnp->cn_flags & ISLASTCN) ||
1378                     (nameiop != DELETE && nameiop != RENAME)) {
1379                         cache_enter(dvp, *vpp, cnp);
1380                 }
1381         }
1382 #endif
1383
1384         return (error);
1385 }
1386
1387 /*
1388  * Attempt to create a new entry in a directory.  If the entry
1389  * already exists, truncate the file if permissible, else return
1390  * an error.  Return the vp of the created or trunc'd file.
1391  *
1392  *      IN:     dvp     - vnode of directory to put new file entry in.
1393  *              name    - name of new file entry.
1394  *              vap     - attributes of new file.
1395  *              excl    - flag indicating exclusive or non-exclusive mode.
1396  *              mode    - mode to open file with.
1397  *              cr      - credentials of caller.
1398  *              flag    - large file flag [UNUSED].
1399  *              ct      - caller context
1400  *              vsecp   - ACL to be set
1401  *
1402  *      OUT:    vpp     - vnode of created or trunc'd entry.
1403  *
1404  *      RETURN: 0 if success
1405  *              error code if failure
1406  *
1407  * Timestamps:
1408  *      dvp - ctime|mtime updated if new entry created
1409  *       vp - ctime|mtime always, atime if new
1410  */
1411
1412 /* ARGSUSED */
1413 static int
1414 zfs_create(vnode_t *dvp, char *name, vattr_t *vap, int excl, int mode,
1415     vnode_t **vpp, cred_t *cr, kthread_t *td)
1416 {
1417         znode_t         *zp, *dzp = VTOZ(dvp);
1418         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1419         zilog_t         *zilog;
1420         objset_t        *os;
1421         zfs_dirlock_t   *dl;
1422         dmu_tx_t        *tx;
1423         int             error;
1424         ksid_t          *ksid;
1425         uid_t           uid;
1426         gid_t           gid = crgetgid(cr);
1427         zfs_acl_ids_t   acl_ids;
1428         boolean_t       fuid_dirtied;
1429         void            *vsecp = NULL;
1430         int             flag = 0;
1431
1432         /*
1433          * If we have an ephemeral id, ACL, or XVATTR then
1434          * make sure file system is at proper version
1435          */
1436
1437         ksid = crgetsid(cr, KSID_OWNER);
1438         if (ksid)
1439                 uid = ksid_getid(ksid);
1440         else
1441                 uid = crgetuid(cr);
1442         if (zfsvfs->z_use_fuids == B_FALSE &&
1443             (vsecp || (vap->va_mask & AT_XVATTR) ||
1444             IS_EPHEMERAL(crgetuid(cr)) || IS_EPHEMERAL(crgetgid(cr))))
1445                 return (EINVAL);
1446
1447         ZFS_ENTER(zfsvfs);
1448         ZFS_VERIFY_ZP(dzp);
1449         os = zfsvfs->z_os;
1450         zilog = zfsvfs->z_log;
1451
1452         if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1453             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1454                 ZFS_EXIT(zfsvfs);
1455                 return (EILSEQ);
1456         }
1457
1458         if (vap->va_mask & AT_XVATTR) {
1459                 if ((error = secpolicy_xvattr(dvp, (xvattr_t *)vap,
1460                     crgetuid(cr), cr, vap->va_type)) != 0) {
1461                         ZFS_EXIT(zfsvfs);
1462                         return (error);
1463                 }
1464         }
1465 top:
1466         *vpp = NULL;
1467
1468         if ((vap->va_mode & S_ISVTX) && secpolicy_vnode_stky_modify(cr))
1469                 vap->va_mode &= ~S_ISVTX;
1470
1471         if (*name == '\0') {
1472                 /*
1473                  * Null component name refers to the directory itself.
1474                  */
1475                 VN_HOLD(dvp);
1476                 zp = dzp;
1477                 dl = NULL;
1478                 error = 0;
1479         } else {
1480                 /* possible VN_HOLD(zp) */
1481                 int zflg = 0;
1482
1483                 if (flag & FIGNORECASE)
1484                         zflg |= ZCILOOK;
1485
1486                 error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1487                     NULL, NULL);
1488                 if (error) {
1489                         if (strcmp(name, "..") == 0)
1490                                 error = EISDIR;
1491                         ZFS_EXIT(zfsvfs);
1492                         return (error);
1493                 }
1494         }
1495         if (zp == NULL) {
1496                 uint64_t txtype;
1497
1498                 /*
1499                  * Create a new file object and update the directory
1500                  * to reference it.
1501                  */
1502                 if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
1503                         goto out;
1504                 }
1505
1506                 /*
1507                  * We only support the creation of regular files in
1508                  * extended attribute directories.
1509                  */
1510                 if ((dzp->z_phys->zp_flags & ZFS_XATTR) &&
1511                     (vap->va_type != VREG)) {
1512                         error = EINVAL;
1513                         goto out;
1514                 }
1515
1516
1517                 if ((error = zfs_acl_ids_create(dzp, 0, vap, cr, vsecp,
1518                     &acl_ids)) != 0)
1519                         goto out;
1520                 if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1521                         zfs_acl_ids_free(&acl_ids);
1522                         error = EDQUOT;
1523                         goto out;
1524                 }
1525
1526                 tx = dmu_tx_create(os);
1527                 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1528                 fuid_dirtied = zfsvfs->z_fuid_dirty;
1529                 if (fuid_dirtied)
1530                         zfs_fuid_txhold(zfsvfs, tx);
1531                 dmu_tx_hold_bonus(tx, dzp->z_id);
1532                 dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1533                 if (acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1534                         dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1535                             0, SPA_MAXBLOCKSIZE);
1536                 }
1537                 error = dmu_tx_assign(tx, TXG_NOWAIT);
1538                 if (error) {
1539                         zfs_acl_ids_free(&acl_ids);
1540                         zfs_dirent_unlock(dl);
1541                         if (error == ERESTART) {
1542                                 dmu_tx_wait(tx);
1543                                 dmu_tx_abort(tx);
1544                                 goto top;
1545                         }
1546                         dmu_tx_abort(tx);
1547                         ZFS_EXIT(zfsvfs);
1548                         return (error);
1549                 }
1550                 zfs_mknode(dzp, vap, tx, cr, 0, &zp, 0, &acl_ids);
1551
1552                 if (fuid_dirtied)
1553                         zfs_fuid_sync(zfsvfs, tx);
1554
1555                 (void) zfs_link_create(dl, zp, tx, ZNEW);
1556
1557                 txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1558                 if (flag & FIGNORECASE)
1559                         txtype |= TX_CI;
1560                 zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1561                     vsecp, acl_ids.z_fuidp, vap);
1562                 zfs_acl_ids_free(&acl_ids);
1563                 dmu_tx_commit(tx);
1564         } else {
1565                 int aflags = (flag & FAPPEND) ? V_APPEND : 0;
1566
1567                 /*
1568                  * A directory entry already exists for this name.
1569                  */
1570                 /*
1571                  * Can't truncate an existing file if in exclusive mode.
1572                  */
1573                 if (excl == EXCL) {
1574                         error = EEXIST;
1575                         goto out;
1576                 }
1577                 /*
1578                  * Can't open a directory for writing.
1579                  */
1580                 if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1581                         error = EISDIR;
1582                         goto out;
1583                 }
1584                 /*
1585                  * Verify requested access to file.
1586                  */
1587                 if (mode && (error = zfs_zaccess_rwx(zp, mode, aflags, cr))) {
1588                         goto out;
1589                 }
1590
1591                 mutex_enter(&dzp->z_lock);
1592                 dzp->z_seq++;
1593                 mutex_exit(&dzp->z_lock);
1594
1595                 /*
1596                  * Truncate regular files if requested.
1597                  */
1598                 if ((ZTOV(zp)->v_type == VREG) &&
1599                     (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1600                         /* we can't hold any locks when calling zfs_freesp() */
1601                         zfs_dirent_unlock(dl);
1602                         dl = NULL;
1603                         error = zfs_freesp(zp, 0, 0, mode, TRUE);
1604                         if (error == 0) {
1605                                 vnevent_create(ZTOV(zp), ct);
1606                         }
1607                 }
1608         }
1609 out:
1610         if (dl)
1611                 zfs_dirent_unlock(dl);
1612
1613         if (error) {
1614                 if (zp)
1615                         VN_RELE(ZTOV(zp));
1616         } else {
1617                 *vpp = ZTOV(zp);
1618                 error = specvp_check(vpp, cr);
1619         }
1620
1621         ZFS_EXIT(zfsvfs);
1622         return (error);
1623 }
1624
1625 /*
1626  * Remove an entry from a directory.
1627  *
1628  *      IN:     dvp     - vnode of directory to remove entry from.
1629  *              name    - name of entry to remove.
1630  *              cr      - credentials of caller.
1631  *              ct      - caller context
1632  *              flags   - case flags
1633  *
1634  *      RETURN: 0 if success
1635  *              error code if failure
1636  *
1637  * Timestamps:
1638  *      dvp - ctime|mtime
1639  *       vp - ctime (if nlink > 0)
1640  */
1641 /*ARGSUSED*/
1642 static int
1643 zfs_remove(vnode_t *dvp, char *name, cred_t *cr, caller_context_t *ct,
1644     int flags)
1645 {
1646         znode_t         *zp, *dzp = VTOZ(dvp);
1647         znode_t         *xzp = NULL;
1648         vnode_t         *vp;
1649         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1650         zilog_t         *zilog;
1651         uint64_t        acl_obj, xattr_obj;
1652         zfs_dirlock_t   *dl;
1653         dmu_tx_t        *tx;
1654         boolean_t       may_delete_now, delete_now = FALSE;
1655         boolean_t       unlinked, toobig = FALSE;
1656         uint64_t        txtype;
1657         pathname_t      *realnmp = NULL;
1658         pathname_t      realnm;
1659         int             error;
1660         int             zflg = ZEXISTS;
1661
1662         ZFS_ENTER(zfsvfs);
1663         ZFS_VERIFY_ZP(dzp);
1664         zilog = zfsvfs->z_log;
1665
1666         if (flags & FIGNORECASE) {
1667                 zflg |= ZCILOOK;
1668                 pn_alloc(&realnm);
1669                 realnmp = &realnm;
1670         }
1671
1672 top:
1673         /*
1674          * Attempt to lock directory; fail if entry doesn't exist.
1675          */
1676         if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1677             NULL, realnmp)) {
1678                 if (realnmp)
1679                         pn_free(realnmp);
1680                 ZFS_EXIT(zfsvfs);
1681                 return (error);
1682         }
1683
1684         vp = ZTOV(zp);
1685
1686         if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1687                 goto out;
1688         }
1689
1690         /*
1691          * Need to use rmdir for removing directories.
1692          */
1693         if (vp->v_type == VDIR) {
1694                 error = EPERM;
1695                 goto out;
1696         }
1697
1698         vnevent_remove(vp, dvp, name, ct);
1699
1700         if (realnmp)
1701                 dnlc_remove(dvp, realnmp->pn_buf);
1702         else
1703                 dnlc_remove(dvp, name);
1704
1705         may_delete_now = FALSE;
1706
1707         /*
1708          * We may delete the znode now, or we may put it in the unlinked set;
1709          * it depends on whether we're the last link, and on whether there are
1710          * other holds on the vnode.  So we dmu_tx_hold() the right things to
1711          * allow for either case.
1712          */
1713         tx = dmu_tx_create(zfsvfs->z_os);
1714         dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1715         dmu_tx_hold_bonus(tx, zp->z_id);
1716         if (may_delete_now) {
1717                 toobig =
1718                     zp->z_phys->zp_size > zp->z_blksz * DMU_MAX_DELETEBLKCNT;
1719                 /* if the file is too big, only hold_free a token amount */
1720                 dmu_tx_hold_free(tx, zp->z_id, 0,
1721                     (toobig ? DMU_MAX_ACCESS : DMU_OBJECT_END));
1722         }
1723
1724         /* are there any extended attributes? */
1725         if ((xattr_obj = zp->z_phys->zp_xattr) != 0) {
1726                 /* XXX - do we need this if we are deleting? */
1727                 dmu_tx_hold_bonus(tx, xattr_obj);
1728         }
1729
1730         /* are there any additional acls */
1731         if ((acl_obj = zp->z_phys->zp_acl.z_acl_extern_obj) != 0 &&
1732             may_delete_now)
1733                 dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1734
1735         /* charge as an update -- would be nice not to charge at all */
1736         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1737
1738         error = dmu_tx_assign(tx, TXG_NOWAIT);
1739         if (error) {
1740                 zfs_dirent_unlock(dl);
1741                 VN_RELE(vp);
1742                 if (error == ERESTART) {
1743                         dmu_tx_wait(tx);
1744                         dmu_tx_abort(tx);
1745                         goto top;
1746                 }
1747                 if (realnmp)
1748                         pn_free(realnmp);
1749                 dmu_tx_abort(tx);
1750                 ZFS_EXIT(zfsvfs);
1751                 return (error);
1752         }
1753
1754         /*
1755          * Remove the directory entry.
1756          */
1757         error = zfs_link_destroy(dl, zp, tx, zflg, &unlinked);
1758
1759         if (error) {
1760                 dmu_tx_commit(tx);
1761                 goto out;
1762         }
1763
1764         if (0 && unlinked) {
1765                 VI_LOCK(vp);
1766                 delete_now = may_delete_now && !toobig &&
1767                     vp->v_count == 1 && !vn_has_cached_data(vp) &&
1768                     zp->z_phys->zp_xattr == xattr_obj &&
1769                     zp->z_phys->zp_acl.z_acl_extern_obj == acl_obj;
1770                 VI_UNLOCK(vp);
1771         }
1772
1773         if (delete_now) {
1774                 if (zp->z_phys->zp_xattr) {
1775                         error = zfs_zget(zfsvfs, zp->z_phys->zp_xattr, &xzp);
1776                         ASSERT3U(error, ==, 0);
1777                         ASSERT3U(xzp->z_phys->zp_links, ==, 2);
1778                         dmu_buf_will_dirty(xzp->z_dbuf, tx);
1779                         mutex_enter(&xzp->z_lock);
1780                         xzp->z_unlinked = 1;
1781                         xzp->z_phys->zp_links = 0;
1782                         mutex_exit(&xzp->z_lock);
1783                         zfs_unlinked_add(xzp, tx);
1784                         zp->z_phys->zp_xattr = 0; /* probably unnecessary */
1785                 }
1786                 mutex_enter(&zp->z_lock);
1787                 VI_LOCK(vp);
1788                 vp->v_count--;
1789                 ASSERT3U(vp->v_count, ==, 0);
1790                 VI_UNLOCK(vp);
1791                 mutex_exit(&zp->z_lock);
1792                 zfs_znode_delete(zp, tx);
1793         } else if (unlinked) {
1794                 zfs_unlinked_add(zp, tx);
1795         }
1796
1797         txtype = TX_REMOVE;
1798         if (flags & FIGNORECASE)
1799                 txtype |= TX_CI;
1800         zfs_log_remove(zilog, tx, txtype, dzp, name);
1801
1802         dmu_tx_commit(tx);
1803 out:
1804         if (realnmp)
1805                 pn_free(realnmp);
1806
1807         zfs_dirent_unlock(dl);
1808
1809         if (!delete_now) {
1810                 VN_RELE(vp);
1811         } else if (xzp) {
1812                 /* this rele is delayed to prevent nesting transactions */
1813                 VN_RELE(ZTOV(xzp));
1814         }
1815
1816         ZFS_EXIT(zfsvfs);
1817         return (error);
1818 }
1819
1820 /*
1821  * Create a new directory and insert it into dvp using the name
1822  * provided.  Return a pointer to the inserted directory.
1823  *
1824  *      IN:     dvp     - vnode of directory to add subdir to.
1825  *              dirname - name of new directory.
1826  *              vap     - attributes of new directory.
1827  *              cr      - credentials of caller.
1828  *              ct      - caller context
1829  *              vsecp   - ACL to be set
1830  *
1831  *      OUT:    vpp     - vnode of created directory.
1832  *
1833  *      RETURN: 0 if success
1834  *              error code if failure
1835  *
1836  * Timestamps:
1837  *      dvp - ctime|mtime updated
1838  *       vp - ctime|mtime|atime updated
1839  */
1840 /*ARGSUSED*/
1841 static int
1842 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr,
1843     caller_context_t *ct, int flags, vsecattr_t *vsecp)
1844 {
1845         znode_t         *zp, *dzp = VTOZ(dvp);
1846         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1847         zilog_t         *zilog;
1848         zfs_dirlock_t   *dl;
1849         uint64_t        txtype;
1850         dmu_tx_t        *tx;
1851         int             error;
1852         int             zf = ZNEW;
1853         ksid_t          *ksid;
1854         uid_t           uid;
1855         gid_t           gid = crgetgid(cr);
1856         zfs_acl_ids_t   acl_ids;
1857         boolean_t       fuid_dirtied;
1858
1859         ASSERT(vap->va_type == VDIR);
1860
1861         /*
1862          * If we have an ephemeral id, ACL, or XVATTR then
1863          * make sure file system is at proper version
1864          */
1865
1866         ksid = crgetsid(cr, KSID_OWNER);
1867         if (ksid)
1868                 uid = ksid_getid(ksid);
1869         else
1870                 uid = crgetuid(cr);
1871         if (zfsvfs->z_use_fuids == B_FALSE &&
1872             (vsecp || (vap->va_mask & AT_XVATTR) || IS_EPHEMERAL(crgetuid(cr))||
1873             IS_EPHEMERAL(crgetgid(cr))))
1874                 return (EINVAL);
1875
1876         ZFS_ENTER(zfsvfs);
1877         ZFS_VERIFY_ZP(dzp);
1878         zilog = zfsvfs->z_log;
1879
1880         if (dzp->z_phys->zp_flags & ZFS_XATTR) {
1881                 ZFS_EXIT(zfsvfs);
1882                 return (EINVAL);
1883         }
1884
1885         if (zfsvfs->z_utf8 && u8_validate(dirname,
1886             strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1887                 ZFS_EXIT(zfsvfs);
1888                 return (EILSEQ);
1889         }
1890         if (flags & FIGNORECASE)
1891                 zf |= ZCILOOK;
1892
1893         if (vap->va_mask & AT_XVATTR)
1894                 if ((error = secpolicy_xvattr(dvp, (xvattr_t *)vap,
1895                     crgetuid(cr), cr, vap->va_type)) != 0) {
1896                         ZFS_EXIT(zfsvfs);
1897                         return (error);
1898                 }
1899
1900         /*
1901          * First make sure the new directory doesn't exist.
1902          */
1903 top:
1904         *vpp = NULL;
1905
1906         if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, zf,
1907             NULL, NULL)) {
1908                 ZFS_EXIT(zfsvfs);
1909                 return (error);
1910         }
1911
1912         if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr)) {
1913                 zfs_dirent_unlock(dl);
1914                 ZFS_EXIT(zfsvfs);
1915                 return (error);
1916         }
1917
1918         if ((error = zfs_acl_ids_create(dzp, 0, vap, cr, vsecp,
1919             &acl_ids)) != 0) {
1920                 zfs_dirent_unlock(dl);
1921                 ZFS_EXIT(zfsvfs);
1922                 return (error);
1923         }
1924         if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
1925                 zfs_acl_ids_free(&acl_ids);
1926                 zfs_dirent_unlock(dl);
1927                 ZFS_EXIT(zfsvfs);
1928                 return (EDQUOT);
1929         }
1930
1931         /*
1932          * Add a new entry to the directory.
1933          */
1934         tx = dmu_tx_create(zfsvfs->z_os);
1935         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1936         dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1937         fuid_dirtied = zfsvfs->z_fuid_dirty;
1938         if (fuid_dirtied)
1939                 zfs_fuid_txhold(zfsvfs, tx);
1940         if (acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE)
1941                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1942                     0, SPA_MAXBLOCKSIZE);
1943         error = dmu_tx_assign(tx, TXG_NOWAIT);
1944         if (error) {
1945                 zfs_acl_ids_free(&acl_ids);
1946                 zfs_dirent_unlock(dl);
1947                 if (error == ERESTART) {
1948                         dmu_tx_wait(tx);
1949                         dmu_tx_abort(tx);
1950                         goto top;
1951                 }
1952                 dmu_tx_abort(tx);
1953                 ZFS_EXIT(zfsvfs);
1954                 return (error);
1955         }
1956
1957         /*
1958          * Create new node.
1959          */
1960         zfs_mknode(dzp, vap, tx, cr, 0, &zp, 0, &acl_ids);
1961
1962         if (fuid_dirtied)
1963                 zfs_fuid_sync(zfsvfs, tx);
1964         /*
1965          * Now put new name in parent dir.
1966          */
1967         (void) zfs_link_create(dl, zp, tx, ZNEW);
1968
1969         *vpp = ZTOV(zp);
1970
1971         txtype = zfs_log_create_txtype(Z_DIR, vsecp, vap);
1972         if (flags & FIGNORECASE)
1973                 txtype |= TX_CI;
1974         zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, vsecp,
1975             acl_ids.z_fuidp, vap);
1976
1977         zfs_acl_ids_free(&acl_ids);
1978         dmu_tx_commit(tx);
1979
1980         zfs_dirent_unlock(dl);
1981
1982         ZFS_EXIT(zfsvfs);
1983         return (0);
1984 }
1985
1986 /*
1987  * Remove a directory subdir entry.  If the current working
1988  * directory is the same as the subdir to be removed, the
1989  * remove will fail.
1990  *
1991  *      IN:     dvp     - vnode of directory to remove from.
1992  *              name    - name of directory to be removed.
1993  *              cwd     - vnode of current working directory.
1994  *              cr      - credentials of caller.
1995  *              ct      - caller context
1996  *              flags   - case flags
1997  *
1998  *      RETURN: 0 if success
1999  *              error code if failure
2000  *
2001  * Timestamps:
2002  *      dvp - ctime|mtime updated
2003  */
2004 /*ARGSUSED*/
2005 static int
2006 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr,
2007     caller_context_t *ct, int flags)
2008 {
2009         znode_t         *dzp = VTOZ(dvp);
2010         znode_t         *zp;
2011         vnode_t         *vp;
2012         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
2013         zilog_t         *zilog;
2014         zfs_dirlock_t   *dl;
2015         dmu_tx_t        *tx;
2016         int             error;
2017         int             zflg = ZEXISTS;
2018
2019         ZFS_ENTER(zfsvfs);
2020         ZFS_VERIFY_ZP(dzp);
2021         zilog = zfsvfs->z_log;
2022
2023         if (flags & FIGNORECASE)
2024                 zflg |= ZCILOOK;
2025 top:
2026         zp = NULL;
2027
2028         /*
2029          * Attempt to lock directory; fail if entry doesn't exist.
2030          */
2031         if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
2032             NULL, NULL)) {
2033                 ZFS_EXIT(zfsvfs);
2034                 return (error);
2035         }
2036
2037         vp = ZTOV(zp);
2038
2039         if (error = zfs_zaccess_delete(dzp, zp, cr)) {
2040                 goto out;
2041         }
2042
2043         if (vp->v_type != VDIR) {
2044                 error = ENOTDIR;
2045                 goto out;
2046         }
2047
2048         if (vp == cwd) {
2049                 error = EINVAL;
2050                 goto out;
2051         }
2052
2053         vnevent_rmdir(vp, dvp, name, ct);
2054
2055         /*
2056          * Grab a lock on the directory to make sure that noone is
2057          * trying to add (or lookup) entries while we are removing it.
2058          */
2059         rw_enter(&zp->z_name_lock, RW_WRITER);
2060
2061         /*
2062          * Grab a lock on the parent pointer to make sure we play well
2063          * with the treewalk and directory rename code.
2064          */
2065         rw_enter(&zp->z_parent_lock, RW_WRITER);
2066
2067         tx = dmu_tx_create(zfsvfs->z_os);
2068         dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
2069         dmu_tx_hold_bonus(tx, zp->z_id);
2070         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
2071         error = dmu_tx_assign(tx, TXG_NOWAIT);
2072         if (error) {
2073                 rw_exit(&zp->z_parent_lock);
2074                 rw_exit(&zp->z_name_lock);
2075                 zfs_dirent_unlock(dl);
2076                 VN_RELE(vp);
2077                 if (error == ERESTART) {
2078                         dmu_tx_wait(tx);
2079                         dmu_tx_abort(tx);
2080                         goto top;
2081                 }
2082                 dmu_tx_abort(tx);
2083                 ZFS_EXIT(zfsvfs);
2084                 return (error);
2085         }
2086
2087 #ifdef FREEBSD_NAMECACHE
2088         cache_purge(dvp);
2089 #endif
2090
2091         error = zfs_link_destroy(dl, zp, tx, zflg, NULL);
2092
2093         if (error == 0) {
2094                 uint64_t txtype = TX_RMDIR;
2095                 if (flags & FIGNORECASE)
2096                         txtype |= TX_CI;
2097                 zfs_log_remove(zilog, tx, txtype, dzp, name);
2098         }
2099
2100         dmu_tx_commit(tx);
2101
2102         rw_exit(&zp->z_parent_lock);
2103         rw_exit(&zp->z_name_lock);
2104 #ifdef FREEBSD_NAMECACHE
2105         cache_purge(vp);
2106 #endif
2107 out:
2108         zfs_dirent_unlock(dl);
2109
2110         VN_RELE(vp);
2111
2112         ZFS_EXIT(zfsvfs);
2113         return (error);
2114 }
2115
2116 /*
2117  * Read as many directory entries as will fit into the provided
2118  * buffer from the given directory cursor position (specified in
2119  * the uio structure.
2120  *
2121  *      IN:     vp      - vnode of directory to read.
2122  *              uio     - structure supplying read location, range info,
2123  *                        and return buffer.
2124  *              cr      - credentials of caller.
2125  *              ct      - caller context
2126  *              flags   - case flags
2127  *
2128  *      OUT:    uio     - updated offset and range, buffer filled.
2129  *              eofp    - set to true if end-of-file detected.
2130  *
2131  *      RETURN: 0 if success
2132  *              error code if failure
2133  *
2134  * Timestamps:
2135  *      vp - atime updated
2136  *
2137  * Note that the low 4 bits of the cookie returned by zap is always zero.
2138  * This allows us to use the low range for "special" directory entries:
2139  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
2140  * we use the offset 2 for the '.zfs' directory.
2141  */
2142 /* ARGSUSED */
2143 static int
2144 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp, int *ncookies, u_long **cookies)
2145 {
2146         znode_t         *zp = VTOZ(vp);
2147         iovec_t         *iovp;
2148         edirent_t       *eodp;
2149         dirent64_t      *odp;
2150         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
2151         objset_t        *os;
2152         caddr_t         outbuf;
2153         size_t          bufsize;
2154         zap_cursor_t    zc;
2155         zap_attribute_t zap;
2156         uint_t          bytes_wanted;
2157         uint64_t        offset; /* must be unsigned; checks for < 1 */
2158         int             local_eof;
2159         int             outcount;
2160         int             error;
2161         uint8_t         prefetch;
2162         boolean_t       check_sysattrs;
2163         uint8_t         type;
2164         int             ncooks;
2165         u_long          *cooks = NULL;
2166         int             flags = 0;
2167
2168         ZFS_ENTER(zfsvfs);
2169         ZFS_VERIFY_ZP(zp);
2170
2171         /*
2172          * If we are not given an eof variable,
2173          * use a local one.
2174          */
2175         if (eofp == NULL)
2176                 eofp = &local_eof;
2177
2178         /*
2179          * Check for valid iov_len.
2180          */
2181         if (uio->uio_iov->iov_len <= 0) {
2182                 ZFS_EXIT(zfsvfs);
2183                 return (EINVAL);
2184         }
2185
2186         /*
2187          * Quit if directory has been removed (posix)
2188          */
2189         if ((*eofp = zp->z_unlinked) != 0) {
2190                 ZFS_EXIT(zfsvfs);
2191                 return (0);
2192         }
2193
2194         error = 0;
2195         os = zfsvfs->z_os;
2196         offset = uio->uio_loffset;
2197         prefetch = zp->z_zn_prefetch;
2198
2199         /*
2200          * Initialize the iterator cursor.
2201          */
2202         if (offset <= 3) {
2203                 /*
2204                  * Start iteration from the beginning of the directory.
2205                  */
2206                 zap_cursor_init(&zc, os, zp->z_id);
2207         } else {
2208                 /*
2209                  * The offset is a serialized cursor.
2210                  */
2211                 zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
2212         }
2213
2214         /*
2215          * Get space to change directory entries into fs independent format.
2216          */
2217         iovp = uio->uio_iov;
2218         bytes_wanted = iovp->iov_len;
2219         if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
2220                 bufsize = bytes_wanted;
2221                 outbuf = kmem_alloc(bufsize, KM_SLEEP);
2222                 odp = (struct dirent64 *)outbuf;
2223         } else {
2224                 bufsize = bytes_wanted;
2225                 odp = (struct dirent64 *)iovp->iov_base;
2226         }
2227         eodp = (struct edirent *)odp;
2228
2229         if (ncookies != NULL) {
2230                 /*
2231                  * Minimum entry size is dirent size and 1 byte for a file name.
2232                  */
2233                 ncooks = uio->uio_resid / (sizeof(struct dirent) - sizeof(((struct dirent *)NULL)->d_name) + 1);
2234                 cooks = malloc(ncooks * sizeof(u_long), M_TEMP, M_WAITOK);
2235                 *cookies = cooks;
2236                 *ncookies = ncooks;
2237         }
2238         /*
2239          * If this VFS supports the system attribute view interface; and
2240          * we're looking at an extended attribute directory; and we care
2241          * about normalization conflicts on this vfs; then we must check
2242          * for normalization conflicts with the sysattr name space.
2243          */
2244 #ifdef TODO
2245         check_sysattrs = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
2246             (vp->v_flag & V_XATTRDIR) && zfsvfs->z_norm &&
2247             (flags & V_RDDIR_ENTFLAGS);
2248 #else
2249         check_sysattrs = 0;
2250 #endif
2251
2252         /*
2253          * Transform to file-system independent format
2254          */
2255         outcount = 0;
2256         while (outcount < bytes_wanted) {
2257                 ino64_t objnum;
2258                 ushort_t reclen;
2259                 off64_t *next;
2260
2261                 /*
2262                  * Special case `.', `..', and `.zfs'.
2263                  */
2264                 if (offset == 0) {
2265                         (void) strcpy(zap.za_name, ".");
2266                         zap.za_normalization_conflict = 0;
2267                         objnum = zp->z_id;
2268                         type = DT_DIR;
2269                 } else if (offset == 1) {
2270                         (void) strcpy(zap.za_name, "..");
2271                         zap.za_normalization_conflict = 0;
2272                         objnum = zp->z_phys->zp_parent;
2273                         type = DT_DIR;
2274                 } else if (offset == 2 && zfs_show_ctldir(zp)) {
2275                         (void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
2276                         zap.za_normalization_conflict = 0;
2277                         objnum = ZFSCTL_INO_ROOT;
2278                         type = DT_DIR;
2279                 } else {
2280                         /*
2281                          * Grab next entry.
2282                          */
2283                         if (error = zap_cursor_retrieve(&zc, &zap)) {
2284                                 if ((*eofp = (error == ENOENT)) != 0)
2285                                         break;
2286                                 else
2287                                         goto update;
2288                         }
2289
2290                         if (zap.za_integer_length != 8 ||
2291                             zap.za_num_integers != 1) {
2292                                 cmn_err(CE_WARN, "zap_readdir: bad directory "
2293                                     "entry, obj = %lld, offset = %lld\n",
2294                                     (u_longlong_t)zp->z_id,
2295                                     (u_longlong_t)offset);
2296                                 error = ENXIO;
2297                                 goto update;
2298                         }
2299
2300                         objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
2301                         /*
2302                          * MacOS X can extract the object type here such as:
2303                          * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2304                          */
2305                         type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2306
2307                         if (check_sysattrs && !zap.za_normalization_conflict) {
2308 #ifdef TODO
2309                                 zap.za_normalization_conflict =
2310                                     xattr_sysattr_casechk(zap.za_name);
2311 #else
2312                                 panic("%s:%u: TODO", __func__, __LINE__);
2313 #endif
2314                         }
2315                 }
2316
2317                 if (flags & V_RDDIR_ACCFILTER) {
2318                         /*
2319                          * If we have no access at all, don't include
2320                          * this entry in the returned information
2321                          */
2322                         znode_t *ezp;
2323                         if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
2324                                 goto skip_entry;
2325                         if (!zfs_has_access(ezp, cr)) {
2326                                 VN_RELE(ZTOV(ezp));
2327                                 goto skip_entry;
2328                         }
2329                         VN_RELE(ZTOV(ezp));
2330                 }
2331
2332                 if (flags & V_RDDIR_ENTFLAGS)
2333                         reclen = EDIRENT_RECLEN(strlen(zap.za_name));
2334                 else
2335                         reclen = DIRENT64_RECLEN(strlen(zap.za_name));
2336
2337                 /*
2338                  * Will this entry fit in the buffer?
2339                  */
2340                 if (outcount + reclen > bufsize) {
2341                         /*
2342                          * Did we manage to fit anything in the buffer?
2343                          */
2344                         if (!outcount) {
2345                                 error = EINVAL;
2346                                 goto update;
2347                         }
2348                         break;
2349                 }
2350                 if (flags & V_RDDIR_ENTFLAGS) {
2351                         /*
2352                          * Add extended flag entry:
2353                          */
2354                         eodp->ed_ino = objnum;
2355                         eodp->ed_reclen = reclen;
2356                         /* NOTE: ed_off is the offset for the *next* entry */
2357                         next = &(eodp->ed_off);
2358                         eodp->ed_eflags = zap.za_normalization_conflict ?
2359                             ED_CASE_CONFLICT : 0;
2360                         (void) strncpy(eodp->ed_name, zap.za_name,
2361                             EDIRENT_NAMELEN(reclen));
2362                         eodp = (edirent_t *)((intptr_t)eodp + reclen);
2363                 } else {
2364                         /*
2365                          * Add normal entry:
2366                          */
2367                         odp->d_ino = objnum;
2368                         odp->d_reclen = reclen;
2369                         odp->d_namlen = strlen(zap.za_name);
2370                         (void) strlcpy(odp->d_name, zap.za_name, odp->d_namlen + 1);
2371                         odp->d_type = type;
2372                         odp = (dirent64_t *)((intptr_t)odp + reclen);
2373                 }
2374                 outcount += reclen;
2375
2376                 ASSERT(outcount <= bufsize);
2377
2378                 /* Prefetch znode */
2379                 if (prefetch)
2380                         dmu_prefetch(os, objnum, 0, 0);
2381
2382         skip_entry:
2383                 /*
2384                  * Move to the next entry, fill in the previous offset.
2385                  */
2386                 if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
2387                         zap_cursor_advance(&zc);
2388                         offset = zap_cursor_serialize(&zc);
2389                 } else {
2390                         offset += 1;
2391                 }
2392
2393                 if (cooks != NULL) {
2394                         *cooks++ = offset;
2395                         ncooks--;
2396                         KASSERT(ncooks >= 0, ("ncookies=%d", ncooks));
2397                 }
2398         }
2399         zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
2400
2401         /* Subtract unused cookies */
2402         if (ncookies != NULL)
2403                 *ncookies -= ncooks;
2404
2405         if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
2406                 iovp->iov_base += outcount;
2407                 iovp->iov_len -= outcount;
2408                 uio->uio_resid -= outcount;
2409         } else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
2410                 /*
2411                  * Reset the pointer.
2412                  */
2413                 offset = uio->uio_loffset;
2414         }
2415
2416 update:
2417         zap_cursor_fini(&zc);
2418         if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
2419                 kmem_free(outbuf, bufsize);
2420
2421         if (error == ENOENT)
2422                 error = 0;
2423
2424         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2425
2426         uio->uio_loffset = offset;
2427         ZFS_EXIT(zfsvfs);
2428         if (error != 0 && cookies != NULL) {
2429                 free(*cookies, M_TEMP);
2430                 *cookies = NULL;
2431                 *ncookies = 0;
2432         }
2433         return (error);
2434 }
2435
2436 ulong_t zfs_fsync_sync_cnt = 4;
2437
2438 static int
2439 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
2440 {
2441         znode_t *zp = VTOZ(vp);
2442         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2443
2444         (void) tsd_set(zfs_fsyncer_key, (void *)zfs_fsync_sync_cnt);
2445
2446         ZFS_ENTER(zfsvfs);
2447         ZFS_VERIFY_ZP(zp);
2448         zil_commit(zfsvfs->z_log, zp->z_last_itx, zp->z_id);
2449         ZFS_EXIT(zfsvfs);
2450         return (0);
2451 }
2452
2453
2454 /*
2455  * Get the requested file attributes and place them in the provided
2456  * vattr structure.
2457  *
2458  *      IN:     vp      - vnode of file.
2459  *              vap     - va_mask identifies requested attributes.
2460  *                        If AT_XVATTR set, then optional attrs are requested
2461  *              flags   - ATTR_NOACLCHECK (CIFS server context)
2462  *              cr      - credentials of caller.
2463  *              ct      - caller context
2464  *
2465  *      OUT:    vap     - attribute values.
2466  *
2467  *      RETURN: 0 (always succeeds)
2468  */
2469 /* ARGSUSED */
2470 static int
2471 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2472     caller_context_t *ct)
2473 {
2474         znode_t *zp = VTOZ(vp);
2475         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2476         znode_phys_t *pzp;
2477         int     error = 0;
2478         uint32_t blksize;
2479         u_longlong_t nblocks;
2480         uint64_t links;
2481         xvattr_t *xvap = (xvattr_t *)vap;       /* vap may be an xvattr_t * */
2482         xoptattr_t *xoap = NULL;
2483         boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2484
2485         ZFS_ENTER(zfsvfs);
2486         ZFS_VERIFY_ZP(zp);
2487         pzp = zp->z_phys;
2488
2489         /*
2490          * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2491          * Also, if we are the owner don't bother, since owner should
2492          * always be allowed to read basic attributes of file.
2493          */
2494         if (!(pzp->zp_flags & ZFS_ACL_TRIVIAL) &&
2495             (pzp->zp_uid != crgetuid(cr))) {
2496                 if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2497                     skipaclchk, cr)) {
2498                         ZFS_EXIT(zfsvfs);
2499                         return (error);
2500                 }
2501         }
2502
2503         /*
2504          * Return all attributes.  It's cheaper to provide the answer
2505          * than to determine whether we were asked the question.
2506          */
2507
2508         mutex_enter(&zp->z_lock);
2509         vap->va_type = IFTOVT(pzp->zp_mode);
2510         vap->va_mode = pzp->zp_mode & ~S_IFMT;
2511         zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
2512 //      vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
2513         vap->va_nodeid = zp->z_id;
2514         if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp))
2515                 links = pzp->zp_links + 1;
2516         else
2517                 links = pzp->zp_links;
2518         vap->va_nlink = MIN(links, UINT32_MAX); /* nlink_t limit! */
2519         vap->va_size = pzp->zp_size;
2520         vap->va_fsid = vp->v_mount->mnt_stat.f_fsid.val[0];
2521         vap->va_rdev = zfs_cmpldev(pzp->zp_rdev);
2522         vap->va_seq = zp->z_seq;
2523         vap->va_flags = 0;      /* FreeBSD: Reset chflags(2) flags. */
2524
2525         /*
2526          * Add in any requested optional attributes and the create time.
2527          * Also set the corresponding bits in the returned attribute bitmap.
2528          */
2529         if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2530                 if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2531                         xoap->xoa_archive =
2532                             ((pzp->zp_flags & ZFS_ARCHIVE) != 0);
2533                         XVA_SET_RTN(xvap, XAT_ARCHIVE);
2534                 }
2535
2536                 if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2537                         xoap->xoa_readonly =
2538                             ((pzp->zp_flags & ZFS_READONLY) != 0);
2539                         XVA_SET_RTN(xvap, XAT_READONLY);
2540                 }
2541
2542                 if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2543                         xoap->xoa_system =
2544                             ((pzp->zp_flags & ZFS_SYSTEM) != 0);
2545                         XVA_SET_RTN(xvap, XAT_SYSTEM);
2546                 }
2547
2548                 if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2549                         xoap->xoa_hidden =
2550                             ((pzp->zp_flags & ZFS_HIDDEN) != 0);
2551                         XVA_SET_RTN(xvap, XAT_HIDDEN);
2552                 }
2553
2554                 if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2555                         xoap->xoa_nounlink =
2556                             ((pzp->zp_flags & ZFS_NOUNLINK) != 0);
2557                         XVA_SET_RTN(xvap, XAT_NOUNLINK);
2558                 }
2559
2560                 if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2561                         xoap->xoa_immutable =
2562                             ((pzp->zp_flags & ZFS_IMMUTABLE) != 0);
2563                         XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2564                 }
2565
2566                 if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2567                         xoap->xoa_appendonly =
2568                             ((pzp->zp_flags & ZFS_APPENDONLY) != 0);
2569                         XVA_SET_RTN(xvap, XAT_APPENDONLY);
2570                 }
2571
2572                 if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2573                         xoap->xoa_nodump =
2574                             ((pzp->zp_flags & ZFS_NODUMP) != 0);
2575                         XVA_SET_RTN(xvap, XAT_NODUMP);
2576                 }
2577
2578                 if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2579                         xoap->xoa_opaque =
2580                             ((pzp->zp_flags & ZFS_OPAQUE) != 0);
2581                         XVA_SET_RTN(xvap, XAT_OPAQUE);
2582                 }
2583
2584                 if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2585                         xoap->xoa_av_quarantined =
2586                             ((pzp->zp_flags & ZFS_AV_QUARANTINED) != 0);
2587                         XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2588                 }
2589
2590                 if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2591                         xoap->xoa_av_modified =
2592                             ((pzp->zp_flags & ZFS_AV_MODIFIED) != 0);
2593                         XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2594                 }
2595
2596                 if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2597                     vp->v_type == VREG &&
2598                     (pzp->zp_flags & ZFS_BONUS_SCANSTAMP)) {
2599                         size_t len;
2600                         dmu_object_info_t doi;
2601
2602                         /*
2603                          * Only VREG files have anti-virus scanstamps, so we
2604                          * won't conflict with symlinks in the bonus buffer.
2605                          */
2606                         dmu_object_info_from_db(zp->z_dbuf, &doi);
2607                         len = sizeof (xoap->xoa_av_scanstamp) +
2608                             sizeof (znode_phys_t);
2609                         if (len <= doi.doi_bonus_size) {
2610                                 /*
2611                                  * pzp points to the start of the
2612                                  * znode_phys_t. pzp + 1 points to the
2613                                  * first byte after the znode_phys_t.
2614                                  */
2615                                 (void) memcpy(xoap->xoa_av_scanstamp,
2616                                     pzp + 1,
2617                                     sizeof (xoap->xoa_av_scanstamp));
2618                                 XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
2619                         }
2620                 }
2621
2622                 if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
2623                         ZFS_TIME_DECODE(&xoap->xoa_createtime, pzp->zp_crtime);
2624                         XVA_SET_RTN(xvap, XAT_CREATETIME);
2625                 }
2626         }
2627
2628         ZFS_TIME_DECODE(&vap->va_atime, pzp->zp_atime);
2629         ZFS_TIME_DECODE(&vap->va_mtime, pzp->zp_mtime);
2630         ZFS_TIME_DECODE(&vap->va_ctime, pzp->zp_ctime);
2631         ZFS_TIME_DECODE(&vap->va_birthtime, pzp->zp_crtime);
2632
2633         mutex_exit(&zp->z_lock);
2634
2635         dmu_object_size_from_db(zp->z_dbuf, &blksize, &nblocks);
2636         vap->va_blksize = blksize;
2637         vap->va_bytes = nblocks << 9;   /* nblocks * 512 */
2638
2639         if (zp->z_blksz == 0) {
2640                 /*
2641                  * Block size hasn't been set; suggest maximal I/O transfers.
2642                  */
2643                 vap->va_blksize = zfsvfs->z_max_blksz;
2644         }
2645
2646         ZFS_EXIT(zfsvfs);
2647         return (0);
2648 }
2649
2650 /*
2651  * Set the file attributes to the values contained in the
2652  * vattr structure.
2653  *
2654  *      IN:     vp      - vnode of file to be modified.
2655  *              vap     - new attribute values.
2656  *                        If AT_XVATTR set, then optional attrs are being set
2657  *              flags   - ATTR_UTIME set if non-default time values provided.
2658  *                      - ATTR_NOACLCHECK (CIFS context only).
2659  *              cr      - credentials of caller.
2660  *              ct      - caller context
2661  *
2662  *      RETURN: 0 if success
2663  *              error code if failure
2664  *
2665  * Timestamps:
2666  *      vp - ctime updated, mtime updated if size changed.
2667  */
2668 /* ARGSUSED */
2669 static int
2670 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2671         caller_context_t *ct)
2672 {
2673         znode_t         *zp = VTOZ(vp);
2674         znode_phys_t    *pzp;
2675         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
2676         zilog_t         *zilog;
2677         dmu_tx_t        *tx;
2678         vattr_t         oldva;
2679         xvattr_t        tmpxvattr;
2680         uint_t          mask = vap->va_mask;
2681         uint_t          saved_mask;
2682         uint64_t        saved_mode;
2683         int             trim_mask = 0;
2684         uint64_t        new_mode;
2685         uint64_t        new_uid, new_gid;
2686         znode_t         *attrzp;
2687         int             need_policy = FALSE;
2688         int             err;
2689         zfs_fuid_info_t *fuidp = NULL;
2690         xvattr_t *xvap = (xvattr_t *)vap;       /* vap may be an xvattr_t * */
2691         xoptattr_t      *xoap;
2692         zfs_acl_t       *aclp = NULL;
2693         boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2694         boolean_t fuid_dirtied = B_FALSE;
2695
2696         if (mask == 0)
2697                 return (0);
2698
2699         if (mask & AT_NOSET)
2700                 return (EINVAL);
2701
2702         ZFS_ENTER(zfsvfs);
2703         ZFS_VERIFY_ZP(zp);
2704
2705         pzp = zp->z_phys;
2706         zilog = zfsvfs->z_log;
2707
2708         /*
2709          * Make sure that if we have ephemeral uid/gid or xvattr specified
2710          * that file system is at proper version level
2711          */
2712
2713         if (zfsvfs->z_use_fuids == B_FALSE &&
2714             (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2715             ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2716             (mask & AT_XVATTR))) {
2717                 ZFS_EXIT(zfsvfs);
2718                 return (EINVAL);
2719         }
2720
2721         if (mask & AT_SIZE && vp->v_type == VDIR) {
2722                 ZFS_EXIT(zfsvfs);
2723                 return (EISDIR);
2724         }
2725
2726         if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2727                 ZFS_EXIT(zfsvfs);
2728                 return (EINVAL);
2729         }
2730
2731         /*
2732          * If this is an xvattr_t, then get a pointer to the structure of
2733          * optional attributes.  If this is NULL, then we have a vattr_t.
2734          */
2735         xoap = xva_getxoptattr(xvap);
2736
2737         xva_init(&tmpxvattr);
2738
2739         /*
2740          * Immutable files can only alter immutable bit and atime
2741          */
2742         if ((pzp->zp_flags & ZFS_IMMUTABLE) &&
2743             ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2744             ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2745                 ZFS_EXIT(zfsvfs);
2746                 return (EPERM);
2747         }
2748
2749         if ((mask & AT_SIZE) && (pzp->zp_flags & ZFS_READONLY)) {
2750                 ZFS_EXIT(zfsvfs);
2751                 return (EPERM);
2752         }
2753
2754         /*
2755          * Verify timestamps doesn't overflow 32 bits.
2756          * ZFS can handle large timestamps, but 32bit syscalls can't
2757          * handle times greater than 2039.  This check should be removed
2758          * once large timestamps are fully supported.
2759          */
2760         if (mask & (AT_ATIME | AT_MTIME)) {
2761                 if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2762                     ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2763                         ZFS_EXIT(zfsvfs);
2764                         return (EOVERFLOW);
2765                 }
2766         }
2767
2768 top:
2769         attrzp = NULL;
2770
2771         /* Can this be moved to before the top label? */
2772         if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2773                 ZFS_EXIT(zfsvfs);
2774                 return (EROFS);
2775         }
2776
2777         /*
2778          * First validate permissions
2779          */
2780
2781         if (mask & AT_SIZE) {
2782                 err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, skipaclchk, cr);
2783                 if (err) {
2784                         ZFS_EXIT(zfsvfs);
2785                         return (err);
2786                 }
2787                 /*
2788                  * XXX - Note, we are not providing any open
2789                  * mode flags here (like FNDELAY), so we may
2790                  * block if there are locks present... this
2791                  * should be addressed in openat().
2792                  */
2793                 /* XXX - would it be OK to generate a log record here? */
2794                 err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2795                 if (err) {
2796                         ZFS_EXIT(zfsvfs);
2797                         return (err);
2798                 }
2799         }
2800
2801         if (mask & (AT_ATIME|AT_MTIME) ||
2802             ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2803             XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2804             XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2805             XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2806             XVA_ISSET_REQ(xvap, XAT_SYSTEM))))
2807                 need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2808                     skipaclchk, cr);
2809
2810         if (mask & (AT_UID|AT_GID)) {
2811                 int     idmask = (mask & (AT_UID|AT_GID));
2812                 int     take_owner;
2813                 int     take_group;
2814
2815                 /*
2816                  * NOTE: even if a new mode is being set,
2817                  * we may clear S_ISUID/S_ISGID bits.
2818                  */
2819
2820                 if (!(mask & AT_MODE))
2821                         vap->va_mode = pzp->zp_mode;
2822
2823                 /*
2824                  * Take ownership or chgrp to group we are a member of
2825                  */
2826
2827                 take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2828                 take_group = (mask & AT_GID) &&
2829                     zfs_groupmember(zfsvfs, vap->va_gid, cr);
2830
2831                 /*
2832                  * If both AT_UID and AT_GID are set then take_owner and
2833                  * take_group must both be set in order to allow taking
2834                  * ownership.
2835                  *
2836                  * Otherwise, send the check through secpolicy_vnode_setattr()
2837                  *
2838                  */
2839
2840                 if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2841                     ((idmask == AT_UID) && take_owner) ||
2842                     ((idmask == AT_GID) && take_group)) {
2843                         if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2844                             skipaclchk, cr) == 0) {
2845                                 /*
2846                                  * Remove setuid/setgid for non-privileged users
2847                                  */
2848                                 secpolicy_setid_clear(vap, vp, cr);
2849                                 trim_mask = (mask & (AT_UID|AT_GID));
2850                         } else {
2851                                 need_policy =  TRUE;
2852                         }
2853                 } else {
2854                         need_policy =  TRUE;
2855                 }
2856         }
2857
2858         mutex_enter(&zp->z_lock);
2859         oldva.va_mode = pzp->zp_mode;
2860         zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
2861         if (mask & AT_XVATTR) {
2862                 /*
2863                  * Update xvattr mask to include only those attributes
2864                  * that are actually changing.
2865                  *
2866                  * the bits will be restored prior to actually setting
2867                  * the attributes so the caller thinks they were set.
2868                  */
2869                 if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2870                         if (xoap->xoa_appendonly !=
2871                             ((pzp->zp_flags & ZFS_APPENDONLY) != 0)) {
2872                                 need_policy = TRUE;
2873                         } else {
2874                                 XVA_CLR_REQ(xvap, XAT_APPENDONLY);
2875                                 XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
2876                         }
2877                 }
2878
2879                 if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2880                         if (xoap->xoa_nounlink !=
2881                             ((pzp->zp_flags & ZFS_NOUNLINK) != 0)) {
2882                                 need_policy = TRUE;
2883                         } else {
2884                                 XVA_CLR_REQ(xvap, XAT_NOUNLINK);
2885                                 XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
2886                         }
2887                 }
2888
2889                 if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2890                         if (xoap->xoa_immutable !=
2891                             ((pzp->zp_flags & ZFS_IMMUTABLE) != 0)) {
2892                                 need_policy = TRUE;
2893                         } else {
2894                                 XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
2895                                 XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
2896                         }
2897                 }
2898
2899                 if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2900                         if (xoap->xoa_nodump !=
2901                             ((pzp->zp_flags & ZFS_NODUMP) != 0)) {
2902                                 need_policy = TRUE;
2903                         } else {
2904                                 XVA_CLR_REQ(xvap, XAT_NODUMP);
2905                                 XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
2906                         }
2907                 }
2908
2909                 if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2910                         if (xoap->xoa_av_modified !=
2911                             ((pzp->zp_flags & ZFS_AV_MODIFIED) != 0)) {
2912                                 need_policy = TRUE;
2913                         } else {
2914                                 XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
2915                                 XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
2916                         }
2917                 }
2918
2919                 if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2920                         if ((vp->v_type != VREG &&
2921                             xoap->xoa_av_quarantined) ||
2922                             xoap->xoa_av_quarantined !=
2923                             ((pzp->zp_flags & ZFS_AV_QUARANTINED) != 0)) {
2924                                 need_policy = TRUE;
2925                         } else {
2926                                 XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
2927                                 XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
2928                         }
2929                 }
2930
2931                 if (need_policy == FALSE &&
2932                     (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
2933                     XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
2934                         need_policy = TRUE;
2935                 }
2936         }
2937
2938         mutex_exit(&zp->z_lock);
2939
2940         if (mask & AT_MODE) {
2941                 if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
2942                         err = secpolicy_setid_setsticky_clear(vp, vap,
2943                             &oldva, cr);
2944                         if (err) {
2945                                 ZFS_EXIT(zfsvfs);
2946                                 return (err);
2947                         }
2948                         trim_mask |= AT_MODE;
2949                 } else {
2950                         need_policy = TRUE;
2951                 }
2952         }
2953
2954         if (need_policy) {
2955                 /*
2956                  * If trim_mask is set then take ownership
2957                  * has been granted or write_acl is present and user
2958                  * has the ability to modify mode.  In that case remove
2959                  * UID|GID and or MODE from mask so that
2960                  * secpolicy_vnode_setattr() doesn't revoke it.
2961                  */
2962
2963                 if (trim_mask) {
2964                         saved_mask = vap->va_mask;
2965                         vap->va_mask &= ~trim_mask;
2966                         if (trim_mask & AT_MODE) {
2967                                 /*
2968                                  * Save the mode, as secpolicy_vnode_setattr()
2969                                  * will overwrite it with ova.va_mode.
2970                                  */
2971                                 saved_mode = vap->va_mode;
2972                         }
2973                 }
2974                 err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
2975                     (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
2976                 if (err) {
2977                         ZFS_EXIT(zfsvfs);
2978                         return (err);
2979                 }
2980
2981                 if (trim_mask) {
2982                         vap->va_mask |= saved_mask;
2983                         if (trim_mask & AT_MODE) {
2984                                 /*
2985                                  * Recover the mode after
2986                                  * secpolicy_vnode_setattr().
2987                                  */
2988                                 vap->va_mode = saved_mode;
2989                         }
2990                 }
2991         }
2992
2993         /*
2994          * secpolicy_vnode_setattr, or take ownership may have
2995          * changed va_mask
2996          */
2997         mask = vap->va_mask;
2998
2999         tx = dmu_tx_create(zfsvfs->z_os);
3000         dmu_tx_hold_bonus(tx, zp->z_id);
3001
3002         if (mask & AT_MODE) {
3003                 uint64_t pmode = pzp->zp_mode;
3004
3005                 new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
3006
3007                 if (err = zfs_acl_chmod_setattr(zp, &aclp, new_mode))
3008                         goto out;
3009                 if (pzp->zp_acl.z_acl_extern_obj) {
3010                         /* Are we upgrading ACL from old V0 format to new V1 */
3011                         if (zfsvfs->z_version <= ZPL_VERSION_FUID &&
3012                             pzp->zp_acl.z_acl_version ==
3013                             ZFS_ACL_VERSION_INITIAL) {
3014                                 dmu_tx_hold_free(tx,
3015                                     pzp->zp_acl.z_acl_extern_obj, 0,
3016                                     DMU_OBJECT_END);
3017                                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3018                                     0, aclp->z_acl_bytes);
3019                         } else {
3020                                 dmu_tx_hold_write(tx,
3021                                     pzp->zp_acl.z_acl_extern_obj, 0,
3022                                     aclp->z_acl_bytes);
3023                         }
3024                 } else if (aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3025                         dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
3026                             0, aclp->z_acl_bytes);
3027                 }
3028         }
3029
3030         if (mask & (AT_UID | AT_GID)) {
3031                 if (pzp->zp_xattr) {
3032                         err = zfs_zget(zp->z_zfsvfs, pzp->zp_xattr, &attrzp);
3033                         if (err)
3034                                 goto out;
3035                         dmu_tx_hold_bonus(tx, attrzp->z_id);
3036                 }
3037                 if (mask & AT_UID) {
3038                         new_uid = zfs_fuid_create(zfsvfs,
3039                             (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
3040                         if (new_uid != pzp->zp_uid &&
3041                             zfs_usergroup_overquota(zfsvfs, B_FALSE, new_uid)) {
3042                                 err = EDQUOT;
3043                                 goto out;
3044                         }
3045                 }
3046
3047                 if (mask & AT_GID) {
3048                         new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
3049                             cr, ZFS_GROUP, &fuidp);
3050                         if (new_gid != pzp->zp_gid &&
3051                             zfs_usergroup_overquota(zfsvfs, B_TRUE, new_gid)) {
3052                                 err = EDQUOT;
3053                                 goto out;
3054                         }
3055                 }
3056                 fuid_dirtied = zfsvfs->z_fuid_dirty;
3057                 if (fuid_dirtied) {
3058                         if (zfsvfs->z_fuid_obj == 0) {
3059                                 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
3060                                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3061                                     FUID_SIZE_ESTIMATE(zfsvfs));
3062                                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ,
3063                                     FALSE, NULL);
3064                         } else {
3065                                 dmu_tx_hold_bonus(tx, zfsvfs->z_fuid_obj);
3066                                 dmu_tx_hold_write(tx, zfsvfs->z_fuid_obj, 0,
3067                                     FUID_SIZE_ESTIMATE(zfsvfs));
3068                         }
3069                 }
3070         }
3071
3072         err = dmu_tx_assign(tx, TXG_NOWAIT);
3073         if (err) {
3074                 if (err == ERESTART)
3075                         dmu_tx_wait(tx);
3076                 goto out;
3077         }
3078
3079         dmu_buf_will_dirty(zp->z_dbuf, tx);
3080
3081         /*
3082          * Set each attribute requested.
3083          * We group settings according to the locks they need to acquire.
3084          *
3085          * Note: you cannot set ctime directly, although it will be
3086          * updated as a side-effect of calling this function.
3087          */
3088
3089         mutex_enter(&zp->z_lock);
3090
3091         if (mask & AT_MODE) {
3092                 mutex_enter(&zp->z_acl_lock);
3093                 zp->z_phys->zp_mode = new_mode;
3094                 err = zfs_aclset_common(zp, aclp, cr, tx);
3095                 ASSERT3U(err, ==, 0);
3096                 zp->z_acl_cached = aclp;
3097                 aclp = NULL;
3098                 mutex_exit(&zp->z_acl_lock);
3099         }
3100
3101         if (attrzp)
3102                 mutex_enter(&attrzp->z_lock);
3103
3104         if (mask & AT_UID) {
3105                 pzp->zp_uid = new_uid;
3106                 if (attrzp)
3107                         attrzp->z_phys->zp_uid = new_uid;
3108         }
3109
3110         if (mask & AT_GID) {
3111                 pzp->zp_gid = new_gid;
3112                 if (attrzp)
3113                         attrzp->z_phys->zp_gid = new_gid;
3114         }
3115
3116         if (attrzp)
3117                 mutex_exit(&attrzp->z_lock);
3118
3119         if (mask & AT_ATIME)
3120                 ZFS_TIME_ENCODE(&vap->va_atime, pzp->zp_atime);
3121
3122         if (mask & AT_MTIME)
3123                 ZFS_TIME_ENCODE(&vap->va_mtime, pzp->zp_mtime);
3124
3125         /* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
3126         if (mask & AT_SIZE)
3127                 zfs_time_stamper_locked(zp, CONTENT_MODIFIED, tx);
3128         else if (mask != 0)
3129                 zfs_time_stamper_locked(zp, STATE_CHANGED, tx);
3130         /*
3131          * Do this after setting timestamps to prevent timestamp
3132          * update from toggling bit
3133          */
3134
3135         if (xoap && (mask & AT_XVATTR)) {
3136
3137                 /*
3138                  * restore trimmed off masks
3139                  * so that return masks can be set for caller.
3140                  */
3141
3142                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
3143                         XVA_SET_REQ(xvap, XAT_APPENDONLY);
3144                 }
3145                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
3146                         XVA_SET_REQ(xvap, XAT_NOUNLINK);
3147                 }
3148                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
3149                         XVA_SET_REQ(xvap, XAT_IMMUTABLE);
3150                 }
3151                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
3152                         XVA_SET_REQ(xvap, XAT_NODUMP);
3153                 }
3154                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
3155                         XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
3156                 }
3157                 if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
3158                         XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
3159                 }
3160
3161                 if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
3162                         size_t len;
3163                         dmu_object_info_t doi;
3164
3165                         ASSERT(vp->v_type == VREG);
3166
3167                         /* Grow the bonus buffer if necessary. */
3168                         dmu_object_info_from_db(zp->z_dbuf, &doi);
3169                         len = sizeof (xoap->xoa_av_scanstamp) +
3170                             sizeof (znode_phys_t);
3171                         if (len > doi.doi_bonus_size)
3172                                 VERIFY(dmu_set_bonus(zp->z_dbuf, len, tx) == 0);
3173                 }
3174                 zfs_xvattr_set(zp, xvap);
3175         }
3176
3177         if (fuid_dirtied)
3178                 zfs_fuid_sync(zfsvfs, tx);
3179
3180         if (mask != 0)
3181                 zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
3182
3183         mutex_exit(&zp->z_lock);
3184
3185 out:
3186         if (attrzp)
3187                 VN_RELE(ZTOV(attrzp));
3188
3189         if (aclp)
3190                 zfs_acl_free(aclp);
3191
3192         if (fuidp) {
3193                 zfs_fuid_info_free(fuidp);
3194                 fuidp = NULL;
3195         }
3196
3197         if (err)
3198                 dmu_tx_abort(tx);
3199         else
3200                 dmu_tx_commit(tx);
3201
3202         if (err == ERESTART)
3203                 goto top;
3204
3205         ZFS_EXIT(zfsvfs);
3206         return (err);
3207 }
3208
3209 typedef struct zfs_zlock {
3210         krwlock_t       *zl_rwlock;     /* lock we acquired */
3211         znode_t         *zl_znode;      /* znode we held */
3212         struct zfs_zlock *zl_next;      /* next in list */
3213 } zfs_zlock_t;
3214
3215 /*
3216  * Drop locks and release vnodes that were held by zfs_rename_lock().
3217  */
3218 static void
3219 zfs_rename_unlock(zfs_zlock_t **zlpp)
3220 {
3221         zfs_zlock_t *zl;
3222
3223         while ((zl = *zlpp) != NULL) {
3224                 if (zl->zl_znode != NULL)
3225                         VN_RELE(ZTOV(zl->zl_znode));
3226                 rw_exit(zl->zl_rwlock);
3227                 *zlpp = zl->zl_next;
3228                 kmem_free(zl, sizeof (*zl));
3229         }
3230 }
3231
3232 /*
3233  * Search back through the directory tree, using the ".." entries.
3234  * Lock each directory in the chain to prevent concurrent renames.
3235  * Fail any attempt to move a directory into one of its own descendants.
3236  * XXX - z_parent_lock can overlap with map or grow locks
3237  */
3238 static int
3239 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
3240 {
3241         zfs_zlock_t     *zl;
3242         znode_t         *zp = tdzp;
3243         uint64_t        rootid = zp->z_zfsvfs->z_root;
3244         uint64_t        *oidp = &zp->z_id;
3245         krwlock_t       *rwlp = &szp->z_parent_lock;
3246         krw_t           rw = RW_WRITER;
3247
3248         /*
3249          * First pass write-locks szp and compares to zp->z_id.
3250          * Later passes read-lock zp and compare to zp->z_parent.
3251          */
3252         do {
3253                 if (!rw_tryenter(rwlp, rw)) {
3254                         /*
3255                          * Another thread is renaming in this path.
3256                          * Note that if we are a WRITER, we don't have any
3257                          * parent_locks held yet.
3258                          */
3259                         if (rw == RW_READER && zp->z_id > szp->z_id) {
3260                                 /*
3261                                  * Drop our locks and restart
3262                                  */
3263                                 zfs_rename_unlock(&zl);
3264                                 *zlpp = NULL;
3265                                 zp = tdzp;
3266                                 oidp = &zp->z_id;
3267                                 rwlp = &szp->z_parent_lock;
3268                                 rw = RW_WRITER;
3269                                 continue;
3270                         } else {
3271                                 /*
3272                                  * Wait for other thread to drop its locks
3273                                  */
3274                                 rw_enter(rwlp, rw);
3275                         }
3276                 }
3277
3278                 zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
3279                 zl->zl_rwlock = rwlp;
3280                 zl->zl_znode = NULL;
3281                 zl->zl_next = *zlpp;
3282                 *zlpp = zl;
3283
3284                 if (*oidp == szp->z_id)         /* We're a descendant of szp */
3285                         return (EINVAL);
3286
3287                 if (*oidp == rootid)            /* We've hit the top */
3288                         return (0);
3289
3290                 if (rw == RW_READER) {          /* i.e. not the first pass */
3291                         int error = zfs_zget(zp->z_zfsvfs, *oidp, &zp);
3292                         if (error)
3293                                 return (error);
3294                         zl->zl_znode = zp;
3295                 }
3296                 oidp = &zp->z_phys->zp_parent;
3297                 rwlp = &zp->z_parent_lock;
3298                 rw = RW_READER;
3299
3300         } while (zp->z_id != sdzp->z_id);
3301
3302         return (0);
3303 }
3304
3305 /*
3306  * Move an entry from the provided source directory to the target
3307  * directory.  Change the entry name as indicated.
3308  *
3309  *      IN:     sdvp    - Source directory containing the "old entry".
3310  *              snm     - Old entry name.
3311  *              tdvp    - Target directory to contain the "new entry".
3312  *              tnm     - New entry name.
3313  *              cr      - credentials of caller.
3314  *              ct      - caller context
3315  *              flags   - case flags
3316  *
3317  *      RETURN: 0 if success
3318  *              error code if failure
3319  *
3320  * Timestamps:
3321  *      sdvp,tdvp - ctime|mtime updated
3322  */
3323 /*ARGSUSED*/
3324 static int
3325 zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr,
3326     caller_context_t *ct, int flags)
3327 {
3328         znode_t         *tdzp, *szp, *tzp;
3329         znode_t         *sdzp = VTOZ(sdvp);
3330         zfsvfs_t        *zfsvfs = sdzp->z_zfsvfs;
3331         zilog_t         *zilog;
3332         vnode_t         *realvp;
3333         zfs_dirlock_t   *sdl, *tdl;
3334         dmu_tx_t        *tx;
3335         zfs_zlock_t     *zl;
3336         int             cmp, serr, terr;
3337         int             error = 0;
3338         int             zflg = 0;
3339
3340         ZFS_ENTER(zfsvfs);
3341         ZFS_VERIFY_ZP(sdzp);
3342         zilog = zfsvfs->z_log;
3343
3344         /*
3345          * Make sure we have the real vp for the target directory.
3346          */
3347         if (VOP_REALVP(tdvp, &realvp, ct) == 0)
3348                 tdvp = realvp;
3349
3350         if (tdvp->v_vfsp != sdvp->v_vfsp || zfsctl_is_node(tdvp)) {
3351                 ZFS_EXIT(zfsvfs);
3352                 return (EXDEV);
3353         }
3354
3355         tdzp = VTOZ(tdvp);
3356         ZFS_VERIFY_ZP(tdzp);
3357         if (zfsvfs->z_utf8 && u8_validate(tnm,
3358             strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3359                 ZFS_EXIT(zfsvfs);
3360                 return (EILSEQ);
3361         }
3362
3363         if (flags & FIGNORECASE)
3364                 zflg |= ZCILOOK;
3365
3366 top:
3367         szp = NULL;
3368         tzp = NULL;
3369         zl = NULL;
3370
3371         /*
3372          * This is to prevent the creation of links into attribute space
3373          * by renaming a linked file into/outof an attribute directory.
3374          * See the comment in zfs_link() for why this is considered bad.
3375          */
3376         if ((tdzp->z_phys->zp_flags & ZFS_XATTR) !=
3377             (sdzp->z_phys->zp_flags & ZFS_XATTR)) {
3378                 ZFS_EXIT(zfsvfs);
3379                 return (EINVAL);
3380         }
3381
3382         /*
3383          * Lock source and target directory entries.  To prevent deadlock,
3384          * a lock ordering must be defined.  We lock the directory with
3385          * the smallest object id first, or if it's a tie, the one with
3386          * the lexically first name.
3387          */
3388         if (sdzp->z_id < tdzp->z_id) {
3389                 cmp = -1;
3390         } else if (sdzp->z_id > tdzp->z_id) {
3391                 cmp = 1;
3392         } else {
3393                 /*
3394                  * First compare the two name arguments without
3395                  * considering any case folding.
3396                  */
3397                 int nofold = (zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER);
3398
3399                 cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
3400                 ASSERT(error == 0 || !zfsvfs->z_utf8);
3401                 if (cmp == 0) {
3402                         /*
3403                          * POSIX: "If the old argument and the new argument
3404                          * both refer to links to the same existing file,
3405                          * the rename() function shall return successfully
3406                          * and perform no other action."
3407                          */
3408                         ZFS_EXIT(zfsvfs);
3409                         return (0);
3410                 }
3411                 /*
3412                  * If the file system is case-folding, then we may
3413                  * have some more checking to do.  A case-folding file
3414                  * system is either supporting mixed case sensitivity
3415                  * access or is completely case-insensitive.  Note
3416                  * that the file system is always case preserving.
3417                  *
3418                  * In mixed sensitivity mode case sensitive behavior
3419                  * is the default.  FIGNORECASE must be used to
3420                  * explicitly request case insensitive behavior.
3421                  *
3422                  * If the source and target names provided differ only
3423                  * by case (e.g., a request to rename 'tim' to 'Tim'),
3424                  * we will treat this as a special case in the
3425                  * case-insensitive mode: as long as the source name
3426                  * is an exact match, we will allow this to proceed as
3427                  * a name-change request.
3428                  */
3429                 if ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
3430                     (zfsvfs->z_case == ZFS_CASE_MIXED &&
3431                     flags & FIGNORECASE)) &&
3432                     u8_strcmp(snm, tnm, 0, zfsvfs->z_norm, U8_UNICODE_LATEST,
3433                     &error) == 0) {
3434                         /*
3435                          * case preserving rename request, require exact
3436                          * name matches
3437                          */
3438                         zflg |= ZCIEXACT;
3439                         zflg &= ~ZCILOOK;
3440                 }
3441         }
3442
3443         /*
3444          * If the source and destination directories are the same, we should
3445          * grab the z_name_lock of that directory only once.
3446          */
3447         if (sdzp == tdzp) {
3448                 zflg |= ZHAVELOCK;
3449                 rw_enter(&sdzp->z_name_lock, RW_READER);
3450         }
3451
3452         if (cmp < 0) {
3453                 serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
3454                     ZEXISTS | zflg, NULL, NULL);
3455                 terr = zfs_dirent_lock(&tdl,
3456                     tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
3457         } else {
3458                 terr = zfs_dirent_lock(&tdl,
3459                     tdzp, tnm, &tzp, zflg, NULL, NULL);
3460                 serr = zfs_dirent_lock(&sdl,
3461                     sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
3462                     NULL, NULL);
3463         }
3464
3465         if (serr) {
3466                 /*
3467                  * Source entry invalid or not there.
3468                  */
3469                 if (!terr) {
3470                         zfs_dirent_unlock(tdl);
3471                         if (tzp)
3472                                 VN_RELE(ZTOV(tzp));
3473                 }
3474
3475                 if (sdzp == tdzp)
3476                         rw_exit(&sdzp->z_name_lock);
3477
3478                 if (strcmp(snm, ".") == 0 || strcmp(snm, "..") == 0)
3479                         serr = EINVAL;
3480                 ZFS_EXIT(zfsvfs);
3481                 return (serr);
3482         }
3483         if (terr) {
3484                 zfs_dirent_unlock(sdl);
3485                 VN_RELE(ZTOV(szp));
3486
3487                 if (sdzp == tdzp)
3488                         rw_exit(&sdzp->z_name_lock);
3489
3490                 if (strcmp(tnm, "..") == 0)
3491                         terr = EINVAL;
3492                 ZFS_EXIT(zfsvfs);
3493                 return (terr);
3494         }
3495
3496         /*
3497          * Must have write access at the source to remove the old entry
3498          * and write access at the target to create the new entry.
3499          * Note that if target and source are the same, this can be
3500          * done in a single check.
3501          */
3502
3503         if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
3504                 goto out;
3505
3506         if (ZTOV(szp)->v_type == VDIR) {
3507                 /*
3508                  * Check to make sure rename is valid.
3509                  * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3510                  */
3511                 if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
3512                         goto out;
3513         }
3514
3515         /*
3516          * Does target exist?
3517          */
3518         if (tzp) {
3519                 /*
3520                  * Source and target must be the same type.
3521                  */
3522                 if (ZTOV(szp)->v_type == VDIR) {
3523                         if (ZTOV(tzp)->v_type != VDIR) {
3524                                 error = ENOTDIR;
3525                                 goto out;
3526                         }
3527                 } else {
3528                         if (ZTOV(tzp)->v_type == VDIR) {
3529                                 error = EISDIR;
3530                                 goto out;
3531                         }
3532                 }
3533                 /*
3534                  * POSIX dictates that when the source and target
3535                  * entries refer to the same file object, rename
3536                  * must do nothing and exit without error.
3537                  */
3538                 if (szp->z_id == tzp->z_id) {
3539                         error = 0;
3540                         goto out;
3541                 }
3542         }
3543
3544         vnevent_rename_src(ZTOV(szp), sdvp, snm, ct);
3545         if (tzp)
3546                 vnevent_rename_dest(ZTOV(tzp), tdvp, tnm, ct);
3547
3548         /*
3549          * notify the target directory if it is not the same
3550          * as source directory.
3551          */
3552         if (tdvp != sdvp) {
3553                 vnevent_rename_dest_dir(tdvp, ct);
3554         }
3555
3556         tx = dmu_tx_create(zfsvfs->z_os);
3557         dmu_tx_hold_bonus(tx, szp->z_id);       /* nlink changes */
3558         dmu_tx_hold_bonus(tx, sdzp->z_id);      /* nlink changes */
3559         dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3560         dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3561         if (sdzp != tdzp)
3562                 dmu_tx_hold_bonus(tx, tdzp->z_id);      /* nlink changes */
3563         if (tzp)
3564                 dmu_tx_hold_bonus(tx, tzp->z_id);       /* parent changes */
3565         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3566         error = dmu_tx_assign(tx, TXG_NOWAIT);
3567         if (error) {
3568                 if (zl != NULL)
3569                         zfs_rename_unlock(&zl);
3570                 zfs_dirent_unlock(sdl);
3571                 zfs_dirent_unlock(tdl);
3572
3573                 if (sdzp == tdzp)
3574                         rw_exit(&sdzp->z_name_lock);
3575
3576                 VN_RELE(ZTOV(szp));
3577                 if (tzp)
3578                         VN_RELE(ZTOV(tzp));
3579                 if (error == ERESTART) {
3580                         dmu_tx_wait(tx);
3581                         dmu_tx_abort(tx);
3582                         goto top;
3583                 }
3584                 dmu_tx_abort(tx);
3585                 ZFS_EXIT(zfsvfs);
3586                 return (error);
3587         }
3588
3589         if (tzp)        /* Attempt to remove the existing target */
3590                 error = zfs_link_destroy(tdl, tzp, tx, zflg, NULL);
3591
3592         if (error == 0) {
3593                 error = zfs_link_create(tdl, szp, tx, ZRENAMING);
3594                 if (error == 0) {
3595                         szp->z_phys->zp_flags |= ZFS_AV_MODIFIED;
3596
3597                         error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
3598                         ASSERT(error == 0);
3599
3600                         zfs_log_rename(zilog, tx,
3601                             TX_RENAME | (flags & FIGNORECASE ? TX_CI : 0),
3602                             sdzp, sdl->dl_name, tdzp, tdl->dl_name, szp);
3603
3604                         /* Update path information for the target vnode */
3605                         vn_renamepath(tdvp, ZTOV(szp), tnm, strlen(tnm));
3606                 }
3607 #ifdef FREEBSD_NAMECACHE
3608                 if (error == 0) {
3609                         cache_purge(sdvp);
3610                         cache_purge(tdvp);
3611                 }
3612 #endif
3613         }
3614
3615         dmu_tx_commit(tx);
3616 out:
3617         if (zl != NULL)
3618                 zfs_rename_unlock(&zl);
3619
3620         zfs_dirent_unlock(sdl);
3621         zfs_dirent_unlock(tdl);
3622
3623         if (sdzp == tdzp)
3624                 rw_exit(&sdzp->z_name_lock);
3625
3626         VN_RELE(ZTOV(szp));
3627         if (tzp)
3628                 VN_RELE(ZTOV(tzp));
3629
3630         ZFS_EXIT(zfsvfs);
3631
3632         return (error);
3633 }
3634
3635 /*
3636  * Insert the indicated symbolic reference entry into the directory.
3637  *
3638  *      IN:     dvp     - Directory to contain new symbolic link.
3639  *              link    - Name for new symlink entry.
3640  *              vap     - Attributes of new entry.
3641  *              target  - Target path of new symlink.
3642  *              cr      - credentials of caller.
3643  *              ct      - caller context
3644  *              flags   - case flags
3645  *
3646  *      RETURN: 0 if success
3647  *              error code if failure
3648  *
3649  * Timestamps:
3650  *      dvp - ctime|mtime updated
3651  */
3652 /*ARGSUSED*/
3653 static int
3654 zfs_symlink(vnode_t *dvp, vnode_t **vpp, char *name, vattr_t *vap, char *link,
3655     cred_t *cr, kthread_t *td)
3656 {
3657         znode_t         *zp, *dzp = VTOZ(dvp);
3658         zfs_dirlock_t   *dl;
3659         dmu_tx_t        *tx;
3660         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
3661         zilog_t         *zilog;
3662         int             len = strlen(link);
3663         int             error;
3664         int             zflg = ZNEW;
3665         zfs_acl_ids_t   acl_ids;
3666         boolean_t       fuid_dirtied;
3667         int             flags = 0;
3668
3669         ASSERT(vap->va_type == VLNK);
3670
3671         ZFS_ENTER(zfsvfs);
3672         ZFS_VERIFY_ZP(dzp);
3673         zilog = zfsvfs->z_log;
3674
3675         if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
3676             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3677                 ZFS_EXIT(zfsvfs);
3678                 return (EILSEQ);
3679         }
3680         if (flags & FIGNORECASE)
3681                 zflg |= ZCILOOK;
3682 top:
3683         if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
3684                 ZFS_EXIT(zfsvfs);
3685                 return (error);
3686         }
3687
3688         if (len > MAXPATHLEN) {
3689                 ZFS_EXIT(zfsvfs);
3690                 return (ENAMETOOLONG);
3691         }
3692
3693         /*
3694          * Attempt to lock directory; fail if entry already exists.
3695          */
3696         error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
3697         if (error) {
3698                 ZFS_EXIT(zfsvfs);
3699                 return (error);
3700         }
3701
3702         VERIFY(0 == zfs_acl_ids_create(dzp, 0, vap, cr, NULL, &acl_ids));
3703         if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
3704                 zfs_acl_ids_free(&acl_ids);
3705                 zfs_dirent_unlock(dl);
3706                 ZFS_EXIT(zfsvfs);
3707                 return (EDQUOT);
3708         }
3709         tx = dmu_tx_create(zfsvfs->z_os);
3710         fuid_dirtied = zfsvfs->z_fuid_dirty;
3711         dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3712         dmu_tx_hold_bonus(tx, dzp->z_id);
3713         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3714         if (acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE)
3715                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, SPA_MAXBLOCKSIZE);
3716         if (fuid_dirtied)
3717                 zfs_fuid_txhold(zfsvfs, tx);
3718         error = dmu_tx_assign(tx, TXG_NOWAIT);
3719         if (error) {
3720                 zfs_acl_ids_free(&acl_ids);
3721                 zfs_dirent_unlock(dl);
3722                 if (error == ERESTART) {
3723                         dmu_tx_wait(tx);
3724                         dmu_tx_abort(tx);
3725                         goto top;
3726                 }
3727                 dmu_tx_abort(tx);
3728                 ZFS_EXIT(zfsvfs);
3729                 return (error);
3730         }
3731
3732         dmu_buf_will_dirty(dzp->z_dbuf, tx);
3733
3734         /*
3735          * Create a new object for the symlink.
3736          * Put the link content into bonus buffer if it will fit;
3737          * otherwise, store it just like any other file data.
3738          */
3739         if (sizeof (znode_phys_t) + len <= dmu_bonus_max()) {
3740                 zfs_mknode(dzp, vap, tx, cr, 0, &zp, len, &acl_ids);
3741                 if (len != 0)
3742                         bcopy(link, zp->z_phys + 1, len);
3743         } else {
3744                 dmu_buf_t *dbp;
3745
3746                 zfs_mknode(dzp, vap, tx, cr, 0, &zp, 0, &acl_ids);
3747
3748                 if (fuid_dirtied)
3749                         zfs_fuid_sync(zfsvfs, tx);
3750                 /*
3751                  * Nothing can access the znode yet so no locking needed
3752                  * for growing the znode's blocksize.
3753                  */
3754                 zfs_grow_blocksize(zp, len, tx);
3755
3756                 VERIFY(0 == dmu_buf_hold(zfsvfs->z_os,
3757                     zp->z_id, 0, FTAG, &dbp));
3758                 dmu_buf_will_dirty(dbp, tx);
3759
3760                 ASSERT3U(len, <=, dbp->db_size);
3761                 bcopy(link, dbp->db_data, len);
3762                 dmu_buf_rele(dbp, FTAG);
3763         }
3764         zp->z_phys->zp_size = len;
3765
3766         /*
3767          * Insert the new object into the directory.
3768          */
3769         (void) zfs_link_create(dl, zp, tx, ZNEW);
3770         if (error == 0) {
3771                 uint64_t txtype = TX_SYMLINK;
3772                 if (flags & FIGNORECASE)
3773                         txtype |= TX_CI;
3774                 zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3775                 *vpp = ZTOV(zp);
3776         }
3777
3778         zfs_acl_ids_free(&acl_ids);
3779
3780         dmu_tx_commit(tx);
3781
3782         zfs_dirent_unlock(dl);
3783
3784         ZFS_EXIT(zfsvfs);
3785         return (error);
3786 }
3787
3788 /*
3789  * Return, in the buffer contained in the provided uio structure,
3790  * the symbolic path referred to by vp.
3791  *
3792  *      IN:     vp      - vnode of symbolic link.
3793  *              uoip    - structure to contain the link path.
3794  *              cr      - credentials of caller.
3795  *              ct      - caller context
3796  *
3797  *      OUT:    uio     - structure to contain the link path.
3798  *
3799  *      RETURN: 0 if success
3800  *              error code if failure
3801  *
3802  * Timestamps:
3803  *      vp - atime updated
3804  */
3805 /* ARGSUSED */
3806 static int
3807 zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr, caller_context_t *ct)
3808 {
3809         znode_t         *zp = VTOZ(vp);
3810         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
3811         size_t          bufsz;
3812         int             error;
3813
3814         ZFS_ENTER(zfsvfs);
3815         ZFS_VERIFY_ZP(zp);
3816
3817         bufsz = (size_t)zp->z_phys->zp_size;
3818         if (bufsz + sizeof (znode_phys_t) <= zp->z_dbuf->db_size) {
3819                 error = uiomove(zp->z_phys + 1,
3820                     MIN((size_t)bufsz, uio->uio_resid), UIO_READ, uio);
3821         } else {
3822                 dmu_buf_t *dbp;
3823                 error = dmu_buf_hold(zfsvfs->z_os, zp->z_id, 0, FTAG, &dbp);
3824                 if (error) {
3825                         ZFS_EXIT(zfsvfs);
3826                         return (error);
3827                 }
3828                 error = uiomove(dbp->db_data,
3829                     MIN((size_t)bufsz, uio->uio_resid), UIO_READ, uio);
3830                 dmu_buf_rele(dbp, FTAG);
3831         }
3832
3833         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
3834         ZFS_EXIT(zfsvfs);
3835         return (error);
3836 }
3837
3838 /*
3839  * Insert a new entry into directory tdvp referencing svp.
3840  *
3841  *      IN:     tdvp    - Directory to contain new entry.
3842  *              svp     - vnode of new entry.
3843  *              name    - name of new entry.
3844  *              cr      - credentials of caller.
3845  *              ct      - caller context
3846  *
3847  *      RETURN: 0 if success
3848  *              error code if failure
3849  *
3850  * Timestamps:
3851  *      tdvp - ctime|mtime updated
3852  *       svp - ctime updated
3853  */
3854 /* ARGSUSED */
3855 static int
3856 zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
3857     caller_context_t *ct, int flags)
3858 {
3859         znode_t         *dzp = VTOZ(tdvp);
3860         znode_t         *tzp, *szp;
3861         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
3862         zilog_t         *zilog;
3863         zfs_dirlock_t   *dl;
3864         dmu_tx_t        *tx;
3865         vnode_t         *realvp;
3866         int             error;
3867         int             zf = ZNEW;
3868         uint64_t        parent;
3869         uid_t           owner;
3870
3871         ASSERT(tdvp->v_type == VDIR);
3872
3873         ZFS_ENTER(zfsvfs);
3874         ZFS_VERIFY_ZP(dzp);
3875         zilog = zfsvfs->z_log;
3876
3877         if (VOP_REALVP(svp, &realvp, ct) == 0)
3878                 svp = realvp;
3879
3880         /*
3881          * POSIX dictates that we return EPERM here.
3882          * Better choices include ENOTSUP or EISDIR.
3883          */
3884         if (svp->v_type == VDIR) {
3885                 ZFS_EXIT(zfsvfs);
3886                 return (EPERM);
3887         }
3888
3889         if (svp->v_vfsp != tdvp->v_vfsp || zfsctl_is_node(svp)) {
3890                 ZFS_EXIT(zfsvfs);
3891                 return (EXDEV);
3892         }
3893
3894         szp = VTOZ(svp);
3895         ZFS_VERIFY_ZP(szp);
3896
3897         /* Prevent links to .zfs/shares files */
3898
3899         if (szp->z_phys->zp_parent == zfsvfs->z_shares_dir) {
3900                 ZFS_EXIT(zfsvfs);
3901                 return (EPERM);
3902         }
3903
3904         if (zfsvfs->z_utf8 && u8_validate(name,
3905             strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3906                 ZFS_EXIT(zfsvfs);
3907                 return (EILSEQ);
3908         }
3909         if (flags & FIGNORECASE)
3910                 zf |= ZCILOOK;
3911
3912         /*
3913          * We do not support links between attributes and non-attributes
3914          * because of the potential security risk of creating links
3915          * into "normal" file space in order to circumvent restrictions
3916          * imposed in attribute space.
3917          */
3918         if ((szp->z_phys->zp_flags & ZFS_XATTR) !=
3919             (dzp->z_phys->zp_flags & ZFS_XATTR)) {
3920                 ZFS_EXIT(zfsvfs);
3921                 return (EINVAL);
3922         }
3923
3924
3925         owner = zfs_fuid_map_id(zfsvfs, szp->z_phys->zp_uid, cr, ZFS_OWNER);
3926         if (owner != crgetuid(cr) &&
3927             secpolicy_basic_link(svp, cr) != 0) {
3928                 ZFS_EXIT(zfsvfs);
3929                 return (EPERM);
3930         }
3931
3932         if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
3933                 ZFS_EXIT(zfsvfs);
3934                 return (error);
3935         }
3936
3937 top:
3938         /*
3939          * Attempt to lock directory; fail if entry already exists.
3940          */
3941         error = zfs_dirent_lock(&dl, dzp, name, &tzp, zf, NULL, NULL);
3942         if (error) {
3943                 ZFS_EXIT(zfsvfs);
3944                 return (error);
3945         }
3946
3947         tx = dmu_tx_create(zfsvfs->z_os);
3948         dmu_tx_hold_bonus(tx, szp->z_id);
3949         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3950         error = dmu_tx_assign(tx, TXG_NOWAIT);
3951         if (error) {
3952                 zfs_dirent_unlock(dl);
3953                 if (error == ERESTART) {
3954                         dmu_tx_wait(tx);
3955                         dmu_tx_abort(tx);
3956                         goto top;
3957                 }
3958                 dmu_tx_abort(tx);
3959                 ZFS_EXIT(zfsvfs);
3960                 return (error);
3961         }
3962
3963         error = zfs_link_create(dl, szp, tx, 0);
3964
3965         if (error == 0) {
3966                 uint64_t txtype = TX_LINK;
3967                 if (flags & FIGNORECASE)
3968                         txtype |= TX_CI;
3969                 zfs_log_link(zilog, tx, txtype, dzp, szp, name);
3970         }
3971
3972         dmu_tx_commit(tx);
3973
3974         zfs_dirent_unlock(dl);
3975
3976         if (error == 0) {
3977                 vnevent_link(svp, ct);
3978         }
3979
3980         ZFS_EXIT(zfsvfs);
3981         return (error);
3982 }
3983
3984 /*ARGSUSED*/
3985 void
3986 zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
3987 {
3988         znode_t *zp = VTOZ(vp);
3989         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3990         int error;
3991
3992         rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
3993         if (zp->z_dbuf == NULL) {
3994                 /*
3995                  * The fs has been unmounted, or we did a
3996                  * suspend/resume and this file no longer exists.
3997                  */
3998                 VI_LOCK(vp);
3999                 vp->v_count = 0; /* count arrives as 1 */
4000                 VI_UNLOCK(vp);
4001                 vrecycle(vp, curthread);
4002                 rw_exit(&zfsvfs->z_teardown_inactive_lock);
4003                 return;
4004         }
4005
4006         if (zp->z_atime_dirty && zp->z_unlinked == 0) {
4007                 dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
4008
4009                 dmu_tx_hold_bonus(tx, zp->z_id);
4010                 error = dmu_tx_assign(tx, TXG_WAIT);
4011                 if (error) {
4012                         dmu_tx_abort(tx);
4013                 } else {
4014                         dmu_buf_will_dirty(zp->z_dbuf, tx);
4015                         mutex_enter(&zp->z_lock);
4016                         zp->z_atime_dirty = 0;
4017                         mutex_exit(&zp->z_lock);
4018                         dmu_tx_commit(tx);
4019                 }
4020         }
4021
4022         zfs_zinactive(zp);
4023         rw_exit(&zfsvfs->z_teardown_inactive_lock);
4024 }
4025
4026 CTASSERT(sizeof(struct zfid_short) <= sizeof(struct fid));
4027 CTASSERT(sizeof(struct zfid_long) <= sizeof(struct fid));
4028
4029 /*ARGSUSED*/
4030 static int
4031 zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
4032 {
4033         znode_t         *zp = VTOZ(vp);
4034         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4035         uint32_t        gen;
4036         uint64_t        object = zp->z_id;
4037         zfid_short_t    *zfid;
4038         int             size, i;
4039
4040         ZFS_ENTER(zfsvfs);
4041         ZFS_VERIFY_ZP(zp);
4042         gen = (uint32_t)zp->z_gen;
4043
4044         size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
4045         fidp->fid_len = size;
4046
4047         zfid = (zfid_short_t *)fidp;
4048
4049         zfid->zf_len = size;
4050
4051         for (i = 0; i < sizeof (zfid->zf_object); i++)
4052                 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
4053
4054         /* Must have a non-zero generation number to distinguish from .zfs */
4055         if (gen == 0)
4056                 gen = 1;
4057         for (i = 0; i < sizeof (zfid->zf_gen); i++)
4058                 zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
4059
4060         if (size == LONG_FID_LEN) {
4061                 uint64_t        objsetid = dmu_objset_id(zfsvfs->z_os);
4062                 zfid_long_t     *zlfid;
4063
4064                 zlfid = (zfid_long_t *)fidp;
4065
4066                 for (i = 0; i < sizeof (zlfid->zf_setid); i++)
4067                         zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
4068
4069                 /* XXX - this should be the generation number for the objset */
4070                 for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
4071                         zlfid->zf_setgen[i] = 0;
4072         }
4073
4074         ZFS_EXIT(zfsvfs);
4075         return (0);
4076 }
4077
4078 static int
4079 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
4080     caller_context_t *ct)
4081 {
4082         znode_t         *zp, *xzp;
4083         zfsvfs_t        *zfsvfs;
4084         zfs_dirlock_t   *dl;
4085         int             error;
4086
4087         switch (cmd) {
4088         case _PC_LINK_MAX:
4089                 *valp = INT_MAX;
4090                 return (0);
4091
4092         case _PC_FILESIZEBITS:
4093                 *valp = 64;
4094                 return (0);
4095
4096 #if 0
4097         case _PC_XATTR_EXISTS:
4098                 zp = VTOZ(vp);
4099                 zfsvfs = zp->z_zfsvfs;
4100                 ZFS_ENTER(zfsvfs);
4101                 ZFS_VERIFY_ZP(zp);
4102                 *valp = 0;
4103                 error = zfs_dirent_lock(&dl, zp, "", &xzp,
4104                     ZXATTR | ZEXISTS | ZSHARED, NULL, NULL);
4105                 if (error == 0) {
4106                         zfs_dirent_unlock(dl);
4107                         if (!zfs_dirempty(xzp))
4108                                 *valp = 1;
4109                         VN_RELE(ZTOV(xzp));
4110                 } else if (error == ENOENT) {
4111                         /*
4112                          * If there aren't extended attributes, it's the
4113                          * same as having zero of them.
4114                          */
4115                         error = 0;
4116                 }
4117                 ZFS_EXIT(zfsvfs);
4118                 return (error);
4119 #endif
4120
4121         case _PC_ACL_EXTENDED:
4122                 *valp = 0;
4123                 return (0);
4124
4125         case _PC_ACL_NFS4:
4126                 *valp = 1;
4127                 return (0);
4128
4129         case _PC_ACL_PATH_MAX:
4130                 *valp = ACL_MAX_ENTRIES;
4131                 return (0);
4132
4133         case _PC_MIN_HOLE_SIZE:
4134                 *valp = (int)SPA_MINBLOCKSIZE;
4135                 return (0);
4136
4137         default:
4138                 return (EOPNOTSUPP);
4139         }
4140 }
4141
4142 /*ARGSUSED*/
4143 static int
4144 zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
4145     caller_context_t *ct)
4146 {
4147         znode_t *zp = VTOZ(vp);
4148         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4149         int error;
4150         boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
4151
4152         ZFS_ENTER(zfsvfs);
4153         ZFS_VERIFY_ZP(zp);
4154         error = zfs_getacl(zp, vsecp, skipaclchk, cr);
4155         ZFS_EXIT(zfsvfs);
4156
4157         return (error);
4158 }
4159
4160 /*ARGSUSED*/
4161 static int
4162 zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr,
4163     caller_context_t *ct)
4164 {
4165         znode_t *zp = VTOZ(vp);
4166         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4167         int error;
4168         boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
4169
4170         ZFS_ENTER(zfsvfs);
4171         ZFS_VERIFY_ZP(zp);
4172         error = zfs_setacl(zp, vsecp, skipaclchk, cr);
4173         ZFS_EXIT(zfsvfs);
4174         return (error);
4175 }
4176
4177 static int
4178 zfs_freebsd_open(ap)
4179         struct vop_open_args /* {
4180                 struct vnode *a_vp;
4181                 int a_mode;
4182                 struct ucred *a_cred;
4183                 struct thread *a_td;
4184         } */ *ap;
4185 {
4186         vnode_t *vp = ap->a_vp;
4187         znode_t *zp = VTOZ(vp);
4188         int error;
4189
4190         error = zfs_open(&vp, ap->a_mode, ap->a_cred, NULL);
4191         if (error == 0)
4192                 vnode_create_vobject(vp, zp->z_phys->zp_size, ap->a_td);
4193         return (error);
4194 }
4195
4196 static int
4197 zfs_freebsd_close(ap)
4198         struct vop_close_args /* {
4199                 struct vnode *a_vp;
4200                 int  a_fflag;
4201                 struct ucred *a_cred;
4202                 struct thread *a_td;
4203         } */ *ap;
4204 {
4205
4206         return (zfs_close(ap->a_vp, ap->a_fflag, 0, 0, ap->a_cred, NULL));
4207 }
4208
4209 static int
4210 zfs_freebsd_ioctl(ap)
4211         struct vop_ioctl_args /* {
4212                 struct vnode *a_vp;
4213                 u_long a_command;
4214                 caddr_t a_data;
4215                 int a_fflag;
4216                 struct ucred *cred;
4217                 struct thread *td;
4218         } */ *ap;
4219 {
4220
4221         return (zfs_ioctl(ap->a_vp, ap->a_command, (intptr_t)ap->a_data,
4222             ap->a_fflag, ap->a_cred, NULL, NULL));
4223 }
4224
4225 static int
4226 zfs_freebsd_read(ap)
4227         struct vop_read_args /* {
4228                 struct vnode *a_vp;
4229                 struct uio *a_uio;
4230                 int a_ioflag;
4231                 struct ucred *a_cred;
4232         } */ *ap;
4233 {
4234
4235         return (zfs_read(ap->a_vp, ap->a_uio, ap->a_ioflag, ap->a_cred, NULL));
4236 }
4237
4238 static int
4239 zfs_freebsd_write(ap)
4240         struct vop_write_args /* {
4241                 struct vnode *a_vp;
4242                 struct uio *a_uio;
4243                 int a_ioflag;
4244                 struct ucred *a_cred;
4245         } */ *ap;
4246 {
4247
4248         return (zfs_write(ap->a_vp, ap->a_uio, ap->a_ioflag, ap->a_cred, NULL));
4249 }
4250
4251 static int
4252 zfs_freebsd_access(ap)
4253         struct vop_access_args /* {
4254                 struct vnode *a_vp;
4255                 accmode_t a_accmode;
4256                 struct ucred *a_cred;
4257                 struct thread *a_td;
4258         } */ *ap;
4259 {
4260         accmode_t accmode;
4261         int error = 0;
4262
4263         /*
4264          * ZFS itself only knowns about VREAD, VWRITE, VEXEC and VAPPEND,
4265          */
4266         accmode = ap->a_accmode & (VREAD|VWRITE|VEXEC|VAPPEND);
4267         if (accmode != 0)
4268                 error = zfs_access(ap->a_vp, accmode, 0, ap->a_cred, NULL);
4269
4270         /*
4271          * VADMIN has to be handled by vaccess().
4272          */
4273         if (error == 0) {
4274                 accmode = ap->a_accmode & ~(VREAD|VWRITE|VEXEC|VAPPEND);
4275                 if (accmode != 0) {
4276                         vnode_t *vp = ap->a_vp;
4277                         znode_t *zp = VTOZ(vp);
4278                         znode_phys_t *zphys = zp->z_phys;
4279
4280                         error = vaccess(vp->v_type, zphys->zp_mode,
4281                             zphys->zp_uid, zphys->zp_gid, accmode, ap->a_cred,
4282                             NULL);
4283                 }
4284         }
4285
4286         return (error);
4287 }
4288
4289 static int
4290 zfs_freebsd_lookup(ap)
4291         struct vop_lookup_args /* {
4292                 struct vnode *a_dvp;
4293                 struct vnode **a_vpp;
4294                 struct componentname *a_cnp;
4295         } */ *ap;
4296 {
4297         struct componentname *cnp = ap->a_cnp;
4298         char nm[NAME_MAX + 1];
4299
4300         ASSERT(cnp->cn_namelen < sizeof(nm));
4301         strlcpy(nm, cnp->cn_nameptr, MIN(cnp->cn_namelen + 1, sizeof(nm)));
4302
4303         return (zfs_lookup(ap->a_dvp, nm, ap->a_vpp, cnp, cnp->cn_nameiop,
4304             cnp->cn_cred, cnp->cn_thread, 0));
4305 }
4306
4307 static int
4308 zfs_freebsd_create(ap)
4309         struct vop_create_args /* {
4310                 struct vnode *a_dvp;
4311                 struct vnode **a_vpp;
4312                 struct componentname *a_cnp;
4313                 struct vattr *a_vap;
4314         } */ *ap;
4315 {
4316         struct componentname *cnp = ap->a_cnp;
4317         vattr_t *vap = ap->a_vap;
4318         int mode;
4319
4320         ASSERT(cnp->cn_flags & SAVENAME);
4321
4322         vattr_init_mask(vap);
4323         mode = vap->va_mode & ALLPERMS;
4324
4325         return (zfs_create(ap->a_dvp, cnp->cn_nameptr, vap, !EXCL, mode,
4326             ap->a_vpp, cnp->cn_cred, cnp->cn_thread));
4327 }
4328
4329 static int
4330 zfs_freebsd_remove(ap)
4331         struct vop_remove_args /* {
4332                 struct vnode *a_dvp;
4333                 struct vnode *a_vp;
4334                 struct componentname *a_cnp;
4335         } */ *ap;
4336 {
4337
4338         ASSERT(ap->a_cnp->cn_flags & SAVENAME);
4339
4340         return (zfs_remove(ap->a_dvp, ap->a_cnp->cn_nameptr,
4341             ap->a_cnp->cn_cred, NULL, 0));
4342 }
4343
4344 static int
4345 zfs_freebsd_mkdir(ap)
4346         struct vop_mkdir_args /* {
4347                 struct vnode *a_dvp;
4348                 struct vnode **a_vpp;
4349                 struct componentname *a_cnp;
4350                 struct vattr *a_vap;
4351         } */ *ap;
4352 {
4353         vattr_t *vap = ap->a_vap;
4354
4355         ASSERT(ap->a_cnp->cn_flags & SAVENAME);
4356
4357         vattr_init_mask(vap);
4358
4359         return (zfs_mkdir(ap->a_dvp, ap->a_cnp->cn_nameptr, vap, ap->a_vpp,
4360             ap->a_cnp->cn_cred, NULL, 0, NULL));
4361 }
4362
4363 static int
4364 zfs_freebsd_rmdir(ap)
4365         struct vop_rmdir_args /* {
4366                 struct vnode *a_dvp;
4367                 struct vnode *a_vp;
4368                 struct componentname *a_cnp;
4369         } */ *ap;
4370 {
4371         struct componentname *cnp = ap->a_cnp;
4372
4373         ASSERT(cnp->cn_flags & SAVENAME);
4374
4375         return (zfs_rmdir(ap->a_dvp, cnp->cn_nameptr, NULL, cnp->cn_cred, NULL, 0));
4376 }
4377
4378 static int
4379 zfs_freebsd_readdir(ap)
4380         struct vop_readdir_args /* {
4381                 struct vnode *a_vp;
4382                 struct uio *a_uio;
4383                 struct ucred *a_cred;
4384                 int *a_eofflag;
4385                 int *a_ncookies;
4386                 u_long **a_cookies;
4387         } */ *ap;
4388 {
4389
4390         return (zfs_readdir(ap->a_vp, ap->a_uio, ap->a_cred, ap->a_eofflag,
4391             ap->a_ncookies, ap->a_cookies));
4392 }
4393
4394 static int
4395 zfs_freebsd_fsync(ap)
4396         struct vop_fsync_args /* {
4397                 struct vnode *a_vp;
4398                 int a_waitfor;
4399                 struct thread *a_td;
4400         } */ *ap;
4401 {
4402
4403         vop_stdfsync(ap);
4404         return (zfs_fsync(ap->a_vp, 0, ap->a_td->td_ucred, NULL));
4405 }
4406
4407 static int
4408 zfs_freebsd_getattr(ap)
4409         struct vop_getattr_args /* {
4410                 struct vnode *a_vp;
4411                 struct vattr *a_vap;
4412                 struct ucred *a_cred;
4413                 struct thread *a_td;
4414         } */ *ap;
4415 {
4416         vattr_t *vap = ap->a_vap;
4417         xvattr_t xvap;
4418         u_long fflags = 0;
4419         int error;
4420
4421         xva_init(&xvap);
4422         xvap.xva_vattr = *vap;
4423         xvap.xva_vattr.va_mask |= AT_XVATTR;
4424
4425         /* Convert chflags into ZFS-type flags. */
4426         /* XXX: what about SF_SETTABLE?. */
4427         XVA_SET_REQ(&xvap, XAT_IMMUTABLE);
4428         XVA_SET_REQ(&xvap, XAT_APPENDONLY);
4429         XVA_SET_REQ(&xvap, XAT_NOUNLINK);
4430         XVA_SET_REQ(&xvap, XAT_NODUMP);
4431         error = zfs_getattr(ap->a_vp, (vattr_t *)&xvap, 0, ap->a_cred, NULL);
4432         if (error != 0)
4433                 return (error);
4434
4435         /* Convert ZFS xattr into chflags. */
4436 #define FLAG_CHECK(fflag, xflag, xfield)        do {                    \
4437         if (XVA_ISSET_RTN(&xvap, (xflag)) && (xfield) != 0)             \
4438                 fflags |= (fflag);                                      \
4439 } while (0)
4440         FLAG_CHECK(SF_IMMUTABLE, XAT_IMMUTABLE,
4441             xvap.xva_xoptattrs.xoa_immutable);
4442         FLAG_CHECK(SF_APPEND, XAT_APPENDONLY,
4443             xvap.xva_xoptattrs.xoa_appendonly);
4444         FLAG_CHECK(SF_NOUNLINK, XAT_NOUNLINK,
4445             xvap.xva_xoptattrs.xoa_nounlink);
4446         FLAG_CHECK(UF_NODUMP, XAT_NODUMP,
4447             xvap.xva_xoptattrs.xoa_nodump);
4448 #undef  FLAG_CHECK
4449         *vap = xvap.xva_vattr;
4450         vap->va_flags = fflags;
4451         return (0);
4452 }
4453
4454 static int
4455 zfs_freebsd_setattr(ap)
4456         struct vop_setattr_args /* {
4457                 struct vnode *a_vp;
4458                 struct vattr *a_vap;
4459                 struct ucred *a_cred;
4460                 struct thread *a_td;
4461         } */ *ap;
4462 {
4463         vnode_t *vp = ap->a_vp;
4464         vattr_t *vap = ap->a_vap;
4465         cred_t *cred = ap->a_cred;
4466         xvattr_t xvap;
4467         u_long fflags;
4468         uint64_t zflags;
4469
4470         vattr_init_mask(vap);
4471         vap->va_mask &= ~AT_NOSET;
4472
4473         xva_init(&xvap);
4474         xvap.xva_vattr = *vap;
4475
4476         zflags = VTOZ(vp)->z_phys->zp_flags;
4477
4478         if (vap->va_flags != VNOVAL) {
4479                 zfsvfs_t *zfsvfs = VTOZ(vp)->z_zfsvfs;
4480                 int error;
4481
4482                 if (zfsvfs->z_use_fuids == B_FALSE)
4483                         return (EOPNOTSUPP);
4484
4485                 fflags = vap->va_flags;
4486                 if ((fflags & ~(SF_IMMUTABLE|SF_APPEND|SF_NOUNLINK|UF_NODUMP)) != 0)
4487                         return (EOPNOTSUPP);
4488                 /*
4489                  * Unprivileged processes are not permitted to unset system
4490                  * flags, or modify flags if any system flags are set.
4491                  * Privileged non-jail processes may not modify system flags
4492                  * if securelevel > 0 and any existing system flags are set.
4493                  * Privileged jail processes behave like privileged non-jail
4494                  * processes if the security.jail.chflags_allowed sysctl is
4495                  * is non-zero; otherwise, they behave like unprivileged
4496                  * processes.
4497                  */
4498                 if (secpolicy_fs_owner(vp->v_mount, cred) == 0 ||
4499                     priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0) == 0) {
4500                         if (zflags &
4501                             (ZFS_IMMUTABLE | ZFS_APPENDONLY | ZFS_NOUNLINK)) {
4502                                 error = securelevel_gt(cred, 0);
4503                                 if (error != 0)
4504                                         return (error);
4505                         }
4506                 } else {
4507                         /*
4508                          * Callers may only modify the file flags on objects they
4509                          * have VADMIN rights for.
4510                          */
4511                         if ((error = VOP_ACCESS(vp, VADMIN, cred, curthread)) != 0)
4512                                 return (error);
4513                         if (zflags &
4514                             (ZFS_IMMUTABLE | ZFS_APPENDONLY | ZFS_NOUNLINK)) {
4515                                 return (EPERM);
4516                         }
4517                         if (fflags &
4518                             (SF_IMMUTABLE | SF_APPEND | SF_NOUNLINK)) {
4519                                 return (EPERM);
4520                         }
4521                 }
4522
4523 #define FLAG_CHANGE(fflag, zflag, xflag, xfield)        do {            \
4524         if (((fflags & (fflag)) && !(zflags & (zflag))) ||              \
4525             ((zflags & (zflag)) && !(fflags & (fflag)))) {              \
4526                 XVA_SET_REQ(&xvap, (xflag));                            \
4527                 (xfield) = ((fflags & (fflag)) != 0);                   \
4528         }                                                               \
4529 } while (0)
4530                 /* Convert chflags into ZFS-type flags. */
4531                 /* XXX: what about SF_SETTABLE?. */
4532                 FLAG_CHANGE(SF_IMMUTABLE, ZFS_IMMUTABLE, XAT_IMMUTABLE,
4533                     xvap.xva_xoptattrs.xoa_immutable);
4534                 FLAG_CHANGE(SF_APPEND, ZFS_APPENDONLY, XAT_APPENDONLY,
4535                     xvap.xva_xoptattrs.xoa_appendonly);
4536                 FLAG_CHANGE(SF_NOUNLINK, ZFS_NOUNLINK, XAT_NOUNLINK,
4537                     xvap.xva_xoptattrs.xoa_nounlink);
4538                 FLAG_CHANGE(UF_NODUMP, ZFS_NODUMP, XAT_NODUMP,
4539                     xvap.xva_xoptattrs.xoa_nodump);
4540 #undef  FLAG_CHANGE
4541         }
4542         return (zfs_setattr(vp, (vattr_t *)&xvap, 0, cred, NULL));
4543 }
4544
4545 static int
4546 zfs_freebsd_rename(ap)
4547         struct vop_rename_args  /* {
4548                 struct vnode *a_fdvp;
4549                 struct vnode *a_fvp;
4550                 struct componentname *a_fcnp;
4551                 struct vnode *a_tdvp;
4552                 struct vnode *a_tvp;
4553                 struct componentname *a_tcnp;
4554         } */ *ap;
4555 {
4556         vnode_t *fdvp = ap->a_fdvp;
4557         vnode_t *fvp = ap->a_fvp;
4558         vnode_t *tdvp = ap->a_tdvp;
4559         vnode_t *tvp = ap->a_tvp;
4560         int error;
4561
4562         ASSERT(ap->a_fcnp->cn_flags & (SAVENAME|SAVESTART));
4563         ASSERT(ap->a_tcnp->cn_flags & (SAVENAME|SAVESTART));
4564
4565         error = zfs_rename(fdvp, ap->a_fcnp->cn_nameptr, tdvp,
4566             ap->a_tcnp->cn_nameptr, ap->a_fcnp->cn_cred, NULL, 0);
4567
4568         if (tdvp == tvp)
4569                 VN_RELE(tdvp);
4570         else
4571                 VN_URELE(tdvp);
4572         if (tvp)
4573                 VN_URELE(tvp);
4574         VN_RELE(fdvp);
4575         VN_RELE(fvp);
4576
4577         return (error);
4578 }
4579
4580 static int
4581 zfs_freebsd_symlink(ap)
4582         struct vop_symlink_args /* {
4583                 struct vnode *a_dvp;
4584                 struct vnode **a_vpp;
4585                 struct componentname *a_cnp;
4586                 struct vattr *a_vap;
4587                 char *a_target;
4588         } */ *ap;
4589 {
4590         struct componentname *cnp = ap->a_cnp;
4591         vattr_t *vap = ap->a_vap;
4592
4593         ASSERT(cnp->cn_flags & SAVENAME);
4594
4595         vap->va_type = VLNK;    /* FreeBSD: Syscall only sets va_mode. */
4596         vattr_init_mask(vap);
4597
4598         return (zfs_symlink(ap->a_dvp, ap->a_vpp, cnp->cn_nameptr, vap,
4599             ap->a_target, cnp->cn_cred, cnp->cn_thread));
4600 }
4601
4602 static int
4603 zfs_freebsd_readlink(ap)
4604         struct vop_readlink_args /* {
4605                 struct vnode *a_vp;
4606                 struct uio *a_uio;
4607                 struct ucred *a_cred;
4608         } */ *ap;
4609 {
4610
4611         return (zfs_readlink(ap->a_vp, ap->a_uio, ap->a_cred, NULL));
4612 }
4613
4614 static int
4615 zfs_freebsd_link(ap)
4616         struct vop_link_args /* {
4617                 struct vnode *a_tdvp;
4618                 struct vnode *a_vp;
4619                 struct componentname *a_cnp;
4620         } */ *ap;
4621 {
4622         struct componentname *cnp = ap->a_cnp;
4623
4624         ASSERT(cnp->cn_flags & SAVENAME);
4625
4626         return (zfs_link(ap->a_tdvp, ap->a_vp, cnp->cn_nameptr, cnp->cn_cred, NULL, 0));
4627 }
4628
4629 static int
4630 zfs_freebsd_inactive(ap)
4631         struct vop_inactive_args /* {
4632                 struct vnode *a_vp;
4633                 struct thread *a_td;
4634         } */ *ap;
4635 {
4636         vnode_t *vp = ap->a_vp;
4637
4638         zfs_inactive(vp, ap->a_td->td_ucred, NULL);
4639         return (0);
4640 }
4641
4642 static void
4643 zfs_reclaim_complete(void *arg, int pending)
4644 {
4645         znode_t *zp = arg;
4646         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4647
4648         rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
4649         if (zp->z_dbuf != NULL) {
4650                 ZFS_OBJ_HOLD_ENTER(zfsvfs, zp->z_id);
4651                 zfs_znode_dmu_fini(zp);
4652                 ZFS_OBJ_HOLD_EXIT(zfsvfs, zp->z_id);
4653         }
4654         zfs_znode_free(zp);
4655         rw_exit(&zfsvfs->z_teardown_inactive_lock);
4656         /*
4657          * If the file system is being unmounted, there is a process waiting
4658          * for us, wake it up.
4659          */
4660         if (zfsvfs->z_unmounted)
4661                 wakeup_one(zfsvfs);
4662 }
4663
4664 static int
4665 zfs_freebsd_reclaim(ap)
4666         struct vop_reclaim_args /* {
4667                 struct vnode *a_vp;
4668                 struct thread *a_td;
4669         } */ *ap;
4670 {
4671         vnode_t *vp = ap->a_vp;
4672         znode_t *zp = VTOZ(vp);
4673         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4674
4675         rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
4676
4677         ASSERT(zp != NULL);
4678
4679         /*
4680          * Destroy the vm object and flush associated pages.
4681          */
4682         vnode_destroy_vobject(vp);
4683
4684         mutex_enter(&zp->z_lock);
4685         ASSERT(zp->z_phys != NULL);
4686         zp->z_vnode = NULL;
4687         mutex_exit(&zp->z_lock);
4688
4689         if (zp->z_unlinked)
4690                 ;       /* Do nothing. */
4691         else if (zp->z_dbuf == NULL)
4692                 zfs_znode_free(zp);
4693         else /* if (!zp->z_unlinked && zp->z_dbuf != NULL) */ {
4694                 int locked;
4695
4696                 locked = MUTEX_HELD(ZFS_OBJ_MUTEX(zfsvfs, zp->z_id)) ? 2 :
4697                     ZFS_OBJ_HOLD_TRYENTER(zfsvfs, zp->z_id);
4698                 if (locked == 0) {
4699                         /*
4700                          * Lock can't be obtained due to deadlock possibility,
4701                          * so defer znode destruction.
4702                          */
4703                         TASK_INIT(&zp->z_task, 0, zfs_reclaim_complete, zp);
4704                         taskqueue_enqueue(taskqueue_thread, &zp->z_task);
4705                 } else {
4706                         zfs_znode_dmu_fini(zp);
4707                         if (locked == 1)
4708                                 ZFS_OBJ_HOLD_EXIT(zfsvfs, zp->z_id);
4709                         zfs_znode_free(zp);
4710                 }
4711         }
4712         VI_LOCK(vp);
4713         vp->v_data = NULL;
4714         ASSERT(vp->v_holdcnt >= 1);
4715         VI_UNLOCK(vp);
4716         rw_exit(&zfsvfs->z_teardown_inactive_lock);
4717         return (0);
4718 }
4719
4720 static int
4721 zfs_freebsd_fid(ap)
4722         struct vop_fid_args /* {
4723                 struct vnode *a_vp;
4724                 struct fid *a_fid;
4725         } */ *ap;
4726 {
4727
4728         return (zfs_fid(ap->a_vp, (void *)ap->a_fid, NULL));
4729 }
4730
4731 static int
4732 zfs_freebsd_pathconf(ap)
4733         struct vop_pathconf_args /* {
4734                 struct vnode *a_vp;
4735                 int a_name;
4736                 register_t *a_retval;
4737         } */ *ap;
4738 {
4739         ulong_t val;
4740         int error;
4741
4742         error = zfs_pathconf(ap->a_vp, ap->a_name, &val, curthread->td_ucred, NULL);
4743         if (error == 0)
4744                 *ap->a_retval = val;
4745         else if (error == EOPNOTSUPP)
4746                 error = vop_stdpathconf(ap);
4747         return (error);
4748 }
4749
4750 static int
4751 zfs_freebsd_fifo_pathconf(ap)
4752         struct vop_pathconf_args /* {
4753                 struct vnode *a_vp;
4754                 int a_name;
4755                 register_t *a_retval;
4756         } */ *ap;
4757 {
4758
4759         switch (ap->a_name) {
4760         case _PC_ACL_EXTENDED:
4761         case _PC_ACL_NFS4:
4762         case _PC_ACL_PATH_MAX:
4763         case _PC_MAC_PRESENT:
4764                 return (zfs_freebsd_pathconf(ap));
4765         default:
4766                 return (fifo_specops.vop_pathconf(ap));
4767         }
4768 }
4769
4770 /*
4771  * FreeBSD's extended attributes namespace defines file name prefix for ZFS'
4772  * extended attribute name:
4773  *
4774  *      NAMESPACE       PREFIX  
4775  *      system          freebsd:system:
4776  *      user            (none, can be used to access ZFS fsattr(5) attributes
4777  *                      created on Solaris)
4778  */
4779 static int
4780 zfs_create_attrname(int attrnamespace, const char *name, char *attrname,
4781     size_t size)
4782 {
4783         const char *namespace, *prefix, *suffix;
4784
4785         /* We don't allow '/' character in attribute name. */
4786         if (strchr(name, '/') != NULL)
4787                 return (EINVAL);
4788         /* We don't allow attribute names that start with "freebsd:" string. */
4789         if (strncmp(name, "freebsd:", 8) == 0)
4790                 return (EINVAL);
4791
4792         bzero(attrname, size);
4793
4794         switch (attrnamespace) {
4795         case EXTATTR_NAMESPACE_USER:
4796 #if 0
4797                 prefix = "freebsd:";
4798                 namespace = EXTATTR_NAMESPACE_USER_STRING;
4799                 suffix = ":";
4800 #else
4801                 /*
4802                  * This is the default namespace by which we can access all
4803                  * attributes created on Solaris.
4804                  */
4805                 prefix = namespace = suffix = "";
4806 #endif
4807                 break;
4808         case EXTATTR_NAMESPACE_SYSTEM:
4809                 prefix = "freebsd:";
4810                 namespace = EXTATTR_NAMESPACE_SYSTEM_STRING;
4811                 suffix = ":";
4812                 break;
4813         case EXTATTR_NAMESPACE_EMPTY:
4814         default:
4815                 return (EINVAL);
4816         }
4817         if (snprintf(attrname, size, "%s%s%s%s", prefix, namespace, suffix,
4818             name) >= size) {
4819                 return (ENAMETOOLONG);
4820         }
4821         return (0);
4822 }
4823
4824 /*
4825  * Vnode operating to retrieve a named extended attribute.
4826  */
4827 static int
4828 zfs_getextattr(struct vop_getextattr_args *ap)
4829 /*
4830 vop_getextattr {
4831         IN struct vnode *a_vp;
4832         IN int a_attrnamespace;
4833         IN const char *a_name;
4834         INOUT struct uio *a_uio;
4835         OUT size_t *a_size;
4836         IN struct ucred *a_cred;
4837         IN struct thread *a_td;
4838 };
4839 */
4840 {
4841         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
4842         struct thread *td = ap->a_td;
4843         struct nameidata nd;
4844         char attrname[255];
4845         struct vattr va;
4846         vnode_t *xvp = NULL, *vp;
4847         int error, flags;
4848
4849         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
4850             ap->a_cred, ap->a_td, VREAD);
4851         if (error != 0)
4852                 return (error);
4853
4854         error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
4855             sizeof(attrname));
4856         if (error != 0)
4857                 return (error);
4858
4859         ZFS_ENTER(zfsvfs);
4860
4861         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
4862             LOOKUP_XATTR);
4863         if (error != 0) {
4864                 ZFS_EXIT(zfsvfs);
4865                 return (error);
4866         }
4867
4868         flags = FREAD;
4869         NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, attrname,
4870             xvp, td);
4871         error = vn_open_cred(&nd, &flags, 0, 0, ap->a_cred, NULL);
4872         vp = nd.ni_vp;
4873         NDFREE(&nd, NDF_ONLY_PNBUF);
4874         if (error != 0) {
4875                 ZFS_EXIT(zfsvfs);
4876                 if (error == ENOENT)
4877                         error = ENOATTR;
4878                 return (error);
4879         }
4880
4881         if (ap->a_size != NULL) {
4882                 error = VOP_GETATTR(vp, &va, ap->a_cred);
4883                 if (error == 0)
4884                         *ap->a_size = (size_t)va.va_size;
4885         } else if (ap->a_uio != NULL)
4886                 error = VOP_READ(vp, ap->a_uio, IO_UNIT | IO_SYNC, ap->a_cred);
4887
4888         VOP_UNLOCK(vp, 0);
4889         vn_close(vp, flags, ap->a_cred, td);
4890         ZFS_EXIT(zfsvfs);
4891
4892         return (error);
4893 }
4894
4895 /*
4896  * Vnode operation to remove a named attribute.
4897  */
4898 int
4899 zfs_deleteextattr(struct vop_deleteextattr_args *ap)
4900 /*
4901 vop_deleteextattr {
4902         IN struct vnode *a_vp;
4903         IN int a_attrnamespace;
4904         IN const char *a_name;
4905         IN struct ucred *a_cred;
4906         IN struct thread *a_td;
4907 };
4908 */
4909 {
4910         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
4911         struct thread *td = ap->a_td;
4912         struct nameidata nd;
4913         char attrname[255];
4914         struct vattr va;
4915         vnode_t *xvp = NULL, *vp;
4916         int error, flags;
4917
4918         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
4919             ap->a_cred, ap->a_td, VWRITE);
4920         if (error != 0)
4921                 return (error);
4922
4923         error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
4924             sizeof(attrname));
4925         if (error != 0)
4926                 return (error);
4927
4928         ZFS_ENTER(zfsvfs);
4929
4930         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
4931             LOOKUP_XATTR);
4932         if (error != 0) {
4933                 ZFS_EXIT(zfsvfs);
4934                 return (error);
4935         }
4936
4937         NDINIT_ATVP(&nd, DELETE, NOFOLLOW | LOCKPARENT | LOCKLEAF | MPSAFE,
4938             UIO_SYSSPACE, attrname, xvp, td);
4939         error = namei(&nd);
4940         vp = nd.ni_vp;
4941         NDFREE(&nd, NDF_ONLY_PNBUF);
4942         if (error != 0) {
4943                 ZFS_EXIT(zfsvfs);
4944                 if (error == ENOENT)
4945                         error = ENOATTR;
4946                 return (error);
4947         }
4948         error = VOP_REMOVE(nd.ni_dvp, vp, &nd.ni_cnd);
4949
4950         vput(nd.ni_dvp);
4951         if (vp == nd.ni_dvp)
4952                 vrele(vp);
4953         else
4954                 vput(vp);
4955         ZFS_EXIT(zfsvfs);
4956
4957         return (error);
4958 }
4959
4960 /*
4961  * Vnode operation to set a named attribute.
4962  */
4963 static int
4964 zfs_setextattr(struct vop_setextattr_args *ap)
4965 /*
4966 vop_setextattr {
4967         IN struct vnode *a_vp;
4968         IN int a_attrnamespace;
4969         IN const char *a_name;
4970         INOUT struct uio *a_uio;
4971         IN struct ucred *a_cred;
4972         IN struct thread *a_td;
4973 };
4974 */
4975 {
4976         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
4977         struct thread *td = ap->a_td;
4978         struct nameidata nd;
4979         char attrname[255];
4980         struct vattr va;
4981         vnode_t *xvp = NULL, *vp;
4982         int error, flags;
4983
4984         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
4985             ap->a_cred, ap->a_td, VWRITE);
4986         if (error != 0)
4987                 return (error);
4988
4989         error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
4990             sizeof(attrname));
4991         if (error != 0)
4992                 return (error);
4993
4994         ZFS_ENTER(zfsvfs);
4995
4996         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
4997             LOOKUP_XATTR | CREATE_XATTR_DIR);
4998         if (error != 0) {
4999                 ZFS_EXIT(zfsvfs);
5000                 return (error);
5001         }
5002
5003         flags = FFLAGS(O_WRONLY | O_CREAT);
5004         NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, attrname,
5005             xvp, td);
5006         error = vn_open_cred(&nd, &flags, 0600, 0, ap->a_cred, NULL);
5007         vp = nd.ni_vp;
5008         NDFREE(&nd, NDF_ONLY_PNBUF);
5009         if (error != 0) {
5010                 ZFS_EXIT(zfsvfs);
5011                 return (error);
5012         }
5013
5014         VATTR_NULL(&va);
5015         va.va_size = 0;
5016         error = VOP_SETATTR(vp, &va, ap->a_cred);
5017         if (error == 0)
5018                 VOP_WRITE(vp, ap->a_uio, IO_UNIT | IO_SYNC, ap->a_cred);
5019
5020         VOP_UNLOCK(vp, 0);
5021         vn_close(vp, flags, ap->a_cred, td);
5022         ZFS_EXIT(zfsvfs);
5023
5024         return (error);
5025 }
5026
5027 /*
5028  * Vnode operation to retrieve extended attributes on a vnode.
5029  */
5030 static int
5031 zfs_listextattr(struct vop_listextattr_args *ap)
5032 /*
5033 vop_listextattr {
5034         IN struct vnode *a_vp;
5035         IN int a_attrnamespace;
5036         INOUT struct uio *a_uio;
5037         OUT size_t *a_size;
5038         IN struct ucred *a_cred;
5039         IN struct thread *a_td;
5040 };
5041 */
5042 {
5043         zfsvfs_t *zfsvfs = VTOZ(ap->a_vp)->z_zfsvfs;
5044         struct thread *td = ap->a_td;
5045         struct nameidata nd;
5046         char attrprefix[16];
5047         u_char dirbuf[sizeof(struct dirent)];
5048         struct dirent *dp;
5049         struct iovec aiov;
5050         struct uio auio, *uio = ap->a_uio;
5051         size_t *sizep = ap->a_size;
5052         size_t plen;
5053         vnode_t *xvp = NULL, *vp;
5054         int done, error, eof, pos;
5055
5056         error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
5057             ap->a_cred, ap->a_td, VREAD);
5058         if (error != 0)
5059                 return (error);
5060
5061         error = zfs_create_attrname(ap->a_attrnamespace, "", attrprefix,
5062             sizeof(attrprefix));
5063         if (error != 0)
5064                 return (error);
5065         plen = strlen(attrprefix);
5066
5067         ZFS_ENTER(zfsvfs);
5068
5069         if (sizep != NULL)
5070                 *sizep = 0;
5071
5072         error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred, td,
5073             LOOKUP_XATTR);
5074         if (error != 0) {
5075                 ZFS_EXIT(zfsvfs);
5076                 /*
5077                  * ENOATTR means that the EA directory does not yet exist,
5078                  * i.e. there are no extended attributes there.
5079                  */
5080                 if (error == ENOATTR)
5081                         error = 0;
5082                 return (error);
5083         }
5084
5085         NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | LOCKLEAF | LOCKSHARED | MPSAFE,
5086             UIO_SYSSPACE, ".", xvp, td);
5087         error = namei(&nd);
5088         vp = nd.ni_vp;
5089         NDFREE(&nd, NDF_ONLY_PNBUF);
5090         if (error != 0) {
5091                 ZFS_EXIT(zfsvfs);
5092                 return (error);
5093         }
5094
5095         auio.uio_iov = &aiov;
5096         auio.uio_iovcnt = 1;
5097         auio.uio_segflg = UIO_SYSSPACE;
5098         auio.uio_td = td;
5099         auio.uio_rw = UIO_READ;
5100         auio.uio_offset = 0;
5101
5102         do {
5103                 u_char nlen;
5104
5105                 aiov.iov_base = (void *)dirbuf;
5106                 aiov.iov_len = sizeof(dirbuf);
5107                 auio.uio_resid = sizeof(dirbuf);
5108                 error = VOP_READDIR(vp, &auio, ap->a_cred, &eof, NULL, NULL);
5109                 done = sizeof(dirbuf) - auio.uio_resid;
5110                 if (error != 0)
5111                         break;
5112                 for (pos = 0; pos < done;) {
5113                         dp = (struct dirent *)(dirbuf + pos);
5114                         pos += dp->d_reclen;
5115                         /*
5116                          * XXX: Temporarily we also accept DT_UNKNOWN, as this
5117                          * is what we get when attribute was created on Solaris.
5118                          */
5119                         if (dp->d_type != DT_REG && dp->d_type != DT_UNKNOWN)
5120                                 continue;
5121                         if (plen == 0 && strncmp(dp->d_name, "freebsd:", 8) == 0)
5122                                 continue;
5123                         else if (strncmp(dp->d_name, attrprefix, plen) != 0)
5124                                 continue;
5125                         nlen = dp->d_namlen - plen;
5126                         if (sizep != NULL)
5127                                 *sizep += 1 + nlen;
5128                         else if (uio != NULL) {
5129                                 /*
5130                                  * Format of extattr name entry is one byte for
5131                                  * length and the rest for name.
5132                                  */
5133                                 error = uiomove(&nlen, 1, uio->uio_rw, uio);
5134                                 if (error == 0) {
5135                                         error = uiomove(dp->d_name + plen, nlen,
5136                                             uio->uio_rw, uio);
5137                                 }
5138                                 if (error != 0)
5139                                         break;
5140                         }
5141                 }
5142         } while (!eof && error == 0);
5143
5144         vput(vp);
5145         ZFS_EXIT(zfsvfs);
5146
5147         return (error);
5148 }
5149
5150 int
5151 zfs_freebsd_getacl(ap)
5152         struct vop_getacl_args /* {
5153                 struct vnode *vp;
5154                 acl_type_t type;
5155                 struct acl *aclp;
5156                 struct ucred *cred;
5157                 struct thread *td;
5158         } */ *ap;
5159 {
5160         int             error;
5161         vsecattr_t      vsecattr;
5162
5163         if (ap->a_type != ACL_TYPE_NFS4)
5164                 return (EINVAL);
5165
5166         vsecattr.vsa_mask = VSA_ACE | VSA_ACECNT;
5167         if (error = zfs_getsecattr(ap->a_vp, &vsecattr, 0, ap->a_cred, NULL))
5168                 return (error);
5169
5170         error = acl_from_aces(ap->a_aclp, vsecattr.vsa_aclentp, vsecattr.vsa_aclcnt);
5171         if (vsecattr.vsa_aclentp != NULL)
5172                 kmem_free(vsecattr.vsa_aclentp, vsecattr.vsa_aclentsz);
5173
5174         return (error);
5175 }
5176
5177 int
5178 zfs_freebsd_setacl(ap)
5179         struct vop_setacl_args /* {
5180                 struct vnode *vp;
5181                 acl_type_t type;
5182                 struct acl *aclp;
5183                 struct ucred *cred;
5184                 struct thread *td;
5185         } */ *ap;
5186 {
5187         int             error;
5188         vsecattr_t      vsecattr;
5189         int             aclbsize;       /* size of acl list in bytes */
5190         aclent_t        *aaclp;
5191
5192         if (ap->a_type != ACL_TYPE_NFS4)
5193                 return (EINVAL);
5194
5195         if (ap->a_aclp->acl_cnt < 1 || ap->a_aclp->acl_cnt > MAX_ACL_ENTRIES)
5196                 return (EINVAL);
5197
5198         /*
5199          * With NFSv4 ACLs, chmod(2) may need to add additional entries,
5200          * splitting every entry into two and appending "canonical six"
5201          * entries at the end.  Don't allow for setting an ACL that would
5202          * cause chmod(2) to run out of ACL entries.
5203          */
5204         if (ap->a_aclp->acl_cnt * 2 + 6 > ACL_MAX_ENTRIES)
5205                 return (ENOSPC);
5206
5207         error = acl_nfs4_check(ap->a_aclp, ap->a_vp->v_type == VDIR);
5208         if (error != 0)
5209                 return (error);
5210
5211         vsecattr.vsa_mask = VSA_ACE;
5212         aclbsize = ap->a_aclp->acl_cnt * sizeof(ace_t);
5213         vsecattr.vsa_aclentp = kmem_alloc(aclbsize, KM_SLEEP);
5214         aaclp = vsecattr.vsa_aclentp;
5215         vsecattr.vsa_aclentsz = aclbsize;
5216
5217         aces_from_acl(vsecattr.vsa_aclentp, &vsecattr.vsa_aclcnt, ap->a_aclp);
5218         error = zfs_setsecattr(ap->a_vp, &vsecattr, 0, ap->a_cred, NULL);
5219         kmem_free(aaclp, aclbsize);
5220
5221         return (error);
5222 }
5223
5224 int
5225 zfs_freebsd_aclcheck(ap)
5226         struct vop_aclcheck_args /* {
5227                 struct vnode *vp;
5228                 acl_type_t type;
5229                 struct acl *aclp;
5230                 struct ucred *cred;
5231                 struct thread *td;
5232         } */ *ap;
5233 {
5234
5235         return (EOPNOTSUPP);
5236 }
5237
5238 struct vop_vector zfs_vnodeops;
5239 struct vop_vector zfs_fifoops;
5240 struct vop_vector zfs_shareops;
5241
5242 struct vop_vector zfs_vnodeops = {
5243         .vop_default =          &default_vnodeops,
5244         .vop_inactive =         zfs_freebsd_inactive,
5245         .vop_reclaim =          zfs_freebsd_reclaim,
5246         .vop_access =           zfs_freebsd_access,
5247 #ifdef FREEBSD_NAMECACHE
5248         .vop_lookup =           vfs_cache_lookup,
5249         .vop_cachedlookup =     zfs_freebsd_lookup,
5250 #else
5251         .vop_lookup =           zfs_freebsd_lookup,
5252 #endif
5253         .vop_getattr =          zfs_freebsd_getattr,
5254         .vop_setattr =          zfs_freebsd_setattr,
5255         .vop_create =           zfs_freebsd_create,
5256         .vop_mknod =            zfs_freebsd_create,
5257         .vop_mkdir =            zfs_freebsd_mkdir,
5258         .vop_readdir =          zfs_freebsd_readdir,
5259         .vop_fsync =            zfs_freebsd_fsync,
5260         .vop_open =             zfs_freebsd_open,
5261         .vop_close =            zfs_freebsd_close,
5262         .vop_rmdir =            zfs_freebsd_rmdir,
5263         .vop_ioctl =            zfs_freebsd_ioctl,
5264         .vop_link =             zfs_freebsd_link,
5265         .vop_symlink =          zfs_freebsd_symlink,
5266         .vop_readlink =         zfs_freebsd_readlink,
5267         .vop_read =             zfs_freebsd_read,
5268         .vop_write =            zfs_freebsd_write,
5269         .vop_remove =           zfs_freebsd_remove,
5270         .vop_rename =           zfs_freebsd_rename,
5271         .vop_pathconf =         zfs_freebsd_pathconf,
5272         .vop_bmap =             VOP_EOPNOTSUPP,
5273         .vop_fid =              zfs_freebsd_fid,
5274         .vop_getextattr =       zfs_getextattr,
5275         .vop_deleteextattr =    zfs_deleteextattr,
5276         .vop_setextattr =       zfs_setextattr,
5277         .vop_listextattr =      zfs_listextattr,
5278         .vop_getacl =           zfs_freebsd_getacl,
5279         .vop_setacl =           zfs_freebsd_setacl,
5280         .vop_aclcheck =         zfs_freebsd_aclcheck,
5281 };
5282
5283 struct vop_vector zfs_fifoops = {
5284         .vop_default =          &fifo_specops,
5285         .vop_fsync =            zfs_freebsd_fsync,
5286         .vop_access =           zfs_freebsd_access,
5287         .vop_getattr =          zfs_freebsd_getattr,
5288         .vop_inactive =         zfs_freebsd_inactive,
5289         .vop_read =             VOP_PANIC,
5290         .vop_reclaim =          zfs_freebsd_reclaim,
5291         .vop_setattr =          zfs_freebsd_setattr,
5292         .vop_write =            VOP_PANIC,
5293         .vop_pathconf =         zfs_freebsd_fifo_pathconf,
5294         .vop_fid =              zfs_freebsd_fid,
5295         .vop_getacl =           zfs_freebsd_getacl,
5296         .vop_setacl =           zfs_freebsd_setacl,
5297         .vop_aclcheck =         zfs_freebsd_aclcheck,
5298 };
5299
5300 /*
5301  * special share hidden files vnode operations template
5302  */
5303 struct vop_vector zfs_shareops = {
5304         .vop_default =          &default_vnodeops,
5305         .vop_access =           zfs_freebsd_access,
5306         .vop_inactive =         zfs_freebsd_inactive,
5307         .vop_reclaim =          zfs_freebsd_reclaim,
5308         .vop_fid =              zfs_freebsd_fid,
5309         .vop_pathconf =         zfs_freebsd_pathconf,
5310 };