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