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