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