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