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