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