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