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