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