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