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