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