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