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