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