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