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