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