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