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