]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.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 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25
26 /* Portions Copyright 2007 Jeremy Teo */
27
28 #pragma ident   "%Z%%M% %I%     %E% SMI"
29
30 #include <sys/types.h>
31 #include <sys/param.h>
32 #include <sys/time.h>
33 #include <sys/systm.h>
34 #include <sys/sysmacros.h>
35 #include <sys/resource.h>
36 #include <sys/vfs.h>
37 #include <sys/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_vfsops.h>
50 #include <sys/zfs_dir.h>
51 #include <sys/zfs_acl.h>
52 #include <sys/zfs_ioctl.h>
53 #include <sys/fs/zfs.h>
54 #include <sys/dmu.h>
55 #include <sys/spa.h>
56 #include <sys/txg.h>
57 #include <sys/dbuf.h>
58 #include <sys/zap.h>
59 #include <sys/dirent.h>
60 #include <sys/policy.h>
61 #include <sys/sunddi.h>
62 #include <sys/filio.h>
63 #include <sys/zfs_ctldir.h>
64 #include <sys/dnlc.h>
65 #include <sys/zfs_rlock.h>
66 #include <sys/bio.h>
67 #include <sys/buf.h>
68 #include <sys/sf_buf.h>
69 #include <sys/sched.h>
70
71 /*
72  * Programming rules.
73  *
74  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
75  * properly lock its in-core state, create a DMU transaction, do the work,
76  * record this work in the intent log (ZIL), commit the DMU transaction,
77  * and wait the the intent log to commit if it's is a synchronous operation.
78  * Morover, the vnode ops must work in both normal and log replay context.
79  * The ordering of events is important to avoid deadlocks and references
80  * to freed memory.  The example below illustrates the following Big Rules:
81  *
82  *  (1) A check must be made in each zfs thread for a mounted file system.
83  *      This is done avoiding races using ZFS_ENTER(zfsvfs).
84  *      A ZFS_EXIT(zfsvfs) is needed before all returns.
85  *
86  *  (2) VN_RELE() should always be the last thing except for zil_commit()
87  *      (if necessary) and ZFS_EXIT(). This is for 3 reasons:
88  *      First, if it's the last reference, the vnode/znode
89  *      can be freed, so the zp may point to freed memory.  Second, the last
90  *      reference will call zfs_zinactive(), which may induce a lot of work --
91  *      pushing cached pages (which acquires range locks) and syncing out
92  *      cached atime changes.  Third, zfs_zinactive() may require a new tx,
93  *      which could deadlock the system if you were already holding one.
94  *
95  *  (3) All range locks must be grabbed before calling dmu_tx_assign(),
96  *      as they can span dmu_tx_assign() calls.
97  *
98  *  (4) Always pass zfsvfs->z_assign as the second argument to dmu_tx_assign().
99  *      In normal operation, this will be TXG_NOWAIT.  During ZIL replay,
100  *      it will be a specific txg.  Either way, dmu_tx_assign() never blocks.
101  *      This is critical because we don't want to block while holding locks.
102  *      Note, in particular, that if a lock is sometimes acquired before
103  *      the tx assigns, and sometimes after (e.g. z_lock), then failing to
104  *      use a non-blocking assign can deadlock the system.  The scenario:
105  *
106  *      Thread A has grabbed a lock before calling dmu_tx_assign().
107  *      Thread B is in an already-assigned tx, and blocks for this lock.
108  *      Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
109  *      forever, because the previous txg can't quiesce until B's tx commits.
110  *
111  *      If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
112  *      then drop all locks, call dmu_tx_wait(), and try again.
113  *
114  *  (5) If the operation succeeded, generate the intent log entry for it
115  *      before dropping locks.  This ensures that the ordering of events
116  *      in the intent log matches the order in which they actually occurred.
117  *
118  *  (6) At the end of each vnode op, the DMU tx must always commit,
119  *      regardless of whether there were any errors.
120  *
121  *  (7) After dropping all locks, invoke zil_commit(zilog, seq, foid)
122  *      to ensure that synchronous semantics are provided when necessary.
123  *
124  * In general, this is how things should be ordered in each vnode op:
125  *
126  *      ZFS_ENTER(zfsvfs);              // exit if unmounted
127  * top:
128  *      zfs_dirent_lock(&dl, ...)       // lock directory entry (may VN_HOLD())
129  *      rw_enter(...);                  // grab any other locks you need
130  *      tx = dmu_tx_create(...);        // get DMU tx
131  *      dmu_tx_hold_*();                // hold each object you might modify
132  *      error = dmu_tx_assign(tx, zfsvfs->z_assign);    // try to assign
133  *      if (error) {
134  *              rw_exit(...);           // drop locks
135  *              zfs_dirent_unlock(dl);  // unlock directory entry
136  *              VN_RELE(...);           // release held vnodes
137  *              if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
138  *                      dmu_tx_wait(tx);
139  *                      dmu_tx_abort(tx);
140  *                      goto top;
141  *              }
142  *              dmu_tx_abort(tx);       // abort DMU tx
143  *              ZFS_EXIT(zfsvfs);       // finished in zfs
144  *              return (error);         // really out of space
145  *      }
146  *      error = do_real_work();         // do whatever this VOP does
147  *      if (error == 0)
148  *              zfs_log_*(...);         // on success, make ZIL entry
149  *      dmu_tx_commit(tx);              // commit DMU tx -- error or not
150  *      rw_exit(...);                   // drop locks
151  *      zfs_dirent_unlock(dl);          // unlock directory entry
152  *      VN_RELE(...);                   // release held vnodes
153  *      zil_commit(zilog, seq, foid);   // synchronous when necessary
154  *      ZFS_EXIT(zfsvfs);               // finished in zfs
155  *      return (error);                 // done, report error
156  */
157 /* ARGSUSED */
158 static int
159 zfs_open(vnode_t **vpp, int flag, cred_t *cr)
160 {
161         znode_t *zp = VTOZ(*vpp);
162
163         /* Keep a count of the synchronous opens in the znode */
164         if (flag & (FSYNC | FDSYNC))
165                 atomic_inc_32(&zp->z_sync_cnt);
166         return (0);
167 }
168
169 /* ARGSUSED */
170 static int
171 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr)
172 {
173         znode_t *zp = VTOZ(vp);
174
175         /* Decrement the synchronous opens in the znode */
176         if (flag & (FSYNC | FDSYNC))
177                 atomic_dec_32(&zp->z_sync_cnt);
178
179         /*
180          * Clean up any locks held by this process on the vp.
181          */
182         cleanlocks(vp, ddi_get_pid(), 0);
183         cleanshares(vp, ddi_get_pid());
184
185         return (0);
186 }
187
188 /*
189  * Lseek support for finding holes (cmd == _FIO_SEEK_HOLE) and
190  * data (cmd == _FIO_SEEK_DATA). "off" is an in/out parameter.
191  */
192 static int
193 zfs_holey(vnode_t *vp, u_long cmd, offset_t *off)
194 {
195         znode_t *zp = VTOZ(vp);
196         uint64_t noff = (uint64_t)*off; /* new offset */
197         uint64_t file_sz;
198         int error;
199         boolean_t hole;
200
201         file_sz = zp->z_phys->zp_size;
202         if (noff >= file_sz)  {
203                 return (ENXIO);
204         }
205
206         if (cmd == _FIO_SEEK_HOLE)
207                 hole = B_TRUE;
208         else
209                 hole = B_FALSE;
210
211         error = dmu_offset_next(zp->z_zfsvfs->z_os, zp->z_id, hole, &noff);
212
213         /* end of file? */
214         if ((error == ESRCH) || (noff > file_sz)) {
215                 /*
216                  * Handle the virtual hole at the end of file.
217                  */
218                 if (hole) {
219                         *off = file_sz;
220                         return (0);
221                 }
222                 return (ENXIO);
223         }
224
225         if (noff < *off)
226                 return (error);
227         *off = noff;
228         return (error);
229 }
230
231 /* ARGSUSED */
232 static int
233 zfs_ioctl(vnode_t *vp, u_long com, intptr_t data, int flag, cred_t *cred,
234     int *rvalp)
235 {
236         offset_t off;
237         int error;
238         zfsvfs_t *zfsvfs;
239
240         switch (com) {
241             case _FIOFFS:
242                 return (0);
243
244                 /*
245                  * The following two ioctls are used by bfu.  Faking out,
246                  * necessary to avoid bfu errors.
247                  */
248             case _FIOGDIO:
249             case _FIOSDIO:
250                 return (0);
251
252             case _FIO_SEEK_DATA:
253             case _FIO_SEEK_HOLE:
254                 if (ddi_copyin((void *)data, &off, sizeof (off), flag))
255                         return (EFAULT);
256
257                 zfsvfs = VTOZ(vp)->z_zfsvfs;
258                 ZFS_ENTER(zfsvfs);
259
260                 /* offset parameter is in/out */
261                 error = zfs_holey(vp, com, &off);
262                 ZFS_EXIT(zfsvfs);
263                 if (error)
264                         return (error);
265                 if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
266                         return (EFAULT);
267                 return (0);
268         }
269         return (ENOTTY);
270 }
271
272 /*
273  * When a file is memory mapped, we must keep the IO data synchronized
274  * between the DMU cache and the memory mapped pages.  What this means:
275  *
276  * On Write:    If we find a memory mapped page, we write to *both*
277  *              the page and the dmu buffer.
278  *
279  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
280  *      the file is memory mapped.
281  */
282 static int
283 mappedwrite(vnode_t *vp, int nbytes, uio_t *uio, dmu_tx_t *tx)
284 {
285         znode_t *zp = VTOZ(vp);
286         objset_t *os = zp->z_zfsvfs->z_os;
287         vm_object_t obj;
288         vm_page_t m;
289         struct sf_buf *sf;
290         int64_t start, off;
291         int len = nbytes;
292         int error = 0;
293         uint64_t dirbytes;
294
295         ASSERT(vp->v_mount != NULL);
296         obj = vp->v_object;
297         ASSERT(obj != NULL);
298
299         start = uio->uio_loffset;
300         off = start & PAGEOFFSET;
301         dirbytes = 0;
302         VM_OBJECT_LOCK(obj);
303         for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
304                 uint64_t bytes = MIN(PAGESIZE - off, len);
305                 uint64_t fsize;
306
307 again:
308                 if ((m = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
309                     vm_page_is_valid(m, (vm_offset_t)off, bytes)) {
310                         uint64_t woff;
311                         caddr_t va;
312
313                         if (vm_page_sleep_if_busy(m, FALSE, "zfsmwb"))
314                                 goto again;
315                         fsize = obj->un_pager.vnp.vnp_size;
316                         vm_page_busy(m);
317                         vm_page_lock_queues();
318                         vm_page_undirty(m);
319                         vm_page_unlock_queues();
320                         VM_OBJECT_UNLOCK(obj);
321                         if (dirbytes > 0) {
322                                 error = dmu_write_uio(os, zp->z_id, uio,
323                                     dirbytes, tx);
324                                 dirbytes = 0;
325                         }
326                         if (error == 0) {
327                                 sched_pin();
328                                 sf = sf_buf_alloc(m, SFB_CPUPRIVATE);
329                                 va = (caddr_t)sf_buf_kva(sf);
330                                 woff = uio->uio_loffset - off;
331                                 error = uiomove(va + off, bytes, UIO_WRITE, uio);
332                                 /*
333                                  * The uiomove() above could have been partially
334                                  * successful, that's why we call dmu_write()
335                                  * below unconditionally. The page was marked
336                                  * non-dirty above and we would lose the changes
337                                  * without doing so. If the uiomove() failed
338                                  * entirely, well, we just write what we got
339                                  * before one more time.
340                                  */
341                                 dmu_write(os, zp->z_id, woff,
342                                     MIN(PAGESIZE, fsize - woff), va, tx);
343                                 sf_buf_free(sf);
344                                 sched_unpin();
345                         }
346                         VM_OBJECT_LOCK(obj);
347                         vm_page_wakeup(m);
348                 } else {
349                         if (__predict_false(obj->cache != NULL)) {
350                                 vm_page_cache_free(obj, OFF_TO_IDX(start),
351                                     OFF_TO_IDX(start) + 1);
352                         }
353                         dirbytes += bytes;
354                 }
355                 len -= bytes;
356                 off = 0;
357                 if (error)
358                         break;
359         }
360         VM_OBJECT_UNLOCK(obj);
361         if (error == 0 && dirbytes > 0)
362                 error = dmu_write_uio(os, zp->z_id, uio, dirbytes, tx);
363         return (error);
364 }
365
366 /*
367  * When a file is memory mapped, we must keep the IO data synchronized
368  * between the DMU cache and the memory mapped pages.  What this means:
369  *
370  * On Read:     We "read" preferentially from memory mapped pages,
371  *              else we default from the dmu buffer.
372  *
373  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
374  *      the file is memory mapped.
375  */
376 static int
377 mappedread(vnode_t *vp, int nbytes, uio_t *uio)
378 {
379         znode_t *zp = VTOZ(vp);
380         objset_t *os = zp->z_zfsvfs->z_os;
381         vm_object_t obj;
382         vm_page_t m;
383         struct sf_buf *sf;
384         int64_t start, off;
385         caddr_t va;
386         int len = nbytes;
387         int error = 0;
388         uint64_t dirbytes;
389
390         ASSERT(vp->v_mount != NULL);
391         obj = vp->v_object;
392         ASSERT(obj != NULL);
393
394         start = uio->uio_loffset;
395         off = start & PAGEOFFSET;
396         dirbytes = 0;
397         VM_OBJECT_LOCK(obj);
398         for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
399                 uint64_t bytes = MIN(PAGESIZE - off, len);
400
401 again:
402                 if ((m = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
403                     vm_page_is_valid(m, (vm_offset_t)off, bytes)) {
404                         if (vm_page_sleep_if_busy(m, FALSE, "zfsmrb"))
405                                 goto again;
406                         vm_page_busy(m);
407                         VM_OBJECT_UNLOCK(obj);
408                         if (dirbytes > 0) {
409                                 error = dmu_read_uio(os, zp->z_id, uio,
410                                     dirbytes);
411                                 dirbytes = 0;
412                         }
413                         if (error == 0) {
414                                 sched_pin();
415                                 sf = sf_buf_alloc(m, SFB_CPUPRIVATE);
416                                 va = (caddr_t)sf_buf_kva(sf);
417                                 error = uiomove(va + off, bytes, UIO_READ, uio);
418                                 sf_buf_free(sf);
419                                 sched_unpin();
420                         }
421                         VM_OBJECT_LOCK(obj);
422                         vm_page_wakeup(m);
423                 } else if (m != NULL && uio->uio_segflg == UIO_NOCOPY) {
424                         /*
425                          * The code below is here to make sendfile(2) work
426                          * correctly with ZFS. As pointed out by ups@
427                          * sendfile(2) should be changed to use VOP_GETPAGES(),
428                          * but it pessimize performance of sendfile/UFS, that's
429                          * why I handle this special case in ZFS code.
430                          */
431                         if (vm_page_sleep_if_busy(m, FALSE, "zfsmrb"))
432                                 goto again;
433                         vm_page_busy(m);
434                         VM_OBJECT_UNLOCK(obj);
435                         if (dirbytes > 0) {
436                                 error = dmu_read_uio(os, zp->z_id, uio,
437                                     dirbytes);
438                                 dirbytes = 0;
439                         }
440                         if (error == 0) {
441                                 sched_pin();
442                                 sf = sf_buf_alloc(m, SFB_CPUPRIVATE);
443                                 va = (caddr_t)sf_buf_kva(sf);
444                                 error = dmu_read(os, zp->z_id, start + off,
445                                     bytes, (void *)(va + off));
446                                 sf_buf_free(sf);
447                                 sched_unpin();
448                         }
449                         VM_OBJECT_LOCK(obj);
450                         vm_page_wakeup(m);
451                         if (error == 0)
452                                 uio->uio_resid -= bytes;
453                 } else {
454                         dirbytes += bytes;
455                 }
456                 len -= bytes;
457                 off = 0;
458                 if (error)
459                         break;
460         }
461         VM_OBJECT_UNLOCK(obj);
462         if (error == 0 && dirbytes > 0)
463                 error = dmu_read_uio(os, zp->z_id, uio, dirbytes);
464         return (error);
465 }
466
467 offset_t zfs_read_chunk_size = 1024 * 1024; /* Tunable */
468
469 /*
470  * Read bytes from specified file into supplied buffer.
471  *
472  *      IN:     vp      - vnode of file to be read from.
473  *              uio     - structure supplying read location, range info,
474  *                        and return buffer.
475  *              ioflag  - SYNC flags; used to provide FRSYNC semantics.
476  *              cr      - credentials of caller.
477  *
478  *      OUT:    uio     - updated offset and range, buffer filled.
479  *
480  *      RETURN: 0 if success
481  *              error code if failure
482  *
483  * Side Effects:
484  *      vp - atime updated if byte count > 0
485  */
486 /* ARGSUSED */
487 static int
488 zfs_read(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
489 {
490         znode_t         *zp = VTOZ(vp);
491         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
492         objset_t        *os = zfsvfs->z_os;
493         ssize_t         n, nbytes;
494         int             error;
495         rl_t            *rl;
496
497         ZFS_ENTER(zfsvfs);
498
499         /*
500          * Validate file offset
501          */
502         if (uio->uio_loffset < (offset_t)0) {
503                 ZFS_EXIT(zfsvfs);
504                 return (EINVAL);
505         }
506
507         /*
508          * Fasttrack empty reads
509          */
510         if (uio->uio_resid == 0) {
511                 ZFS_EXIT(zfsvfs);
512                 return (0);
513         }
514
515         /*
516          * Check for mandatory locks
517          */
518         if (MANDMODE((mode_t)zp->z_phys->zp_mode)) {
519                 if (error = chklock(vp, FREAD,
520                     uio->uio_loffset, uio->uio_resid, uio->uio_fmode, ct)) {
521                         ZFS_EXIT(zfsvfs);
522                         return (error);
523                 }
524         }
525
526         /*
527          * If we're in FRSYNC mode, sync out this znode before reading it.
528          */
529         if (ioflag & FRSYNC)
530                 zil_commit(zfsvfs->z_log, zp->z_last_itx, zp->z_id);
531
532         /*
533          * Lock the range against changes.
534          */
535         rl = zfs_range_lock(zp, uio->uio_loffset, uio->uio_resid, RL_READER);
536
537         /*
538          * If we are reading past end-of-file we can skip
539          * to the end; but we might still need to set atime.
540          */
541         if (uio->uio_loffset >= zp->z_phys->zp_size) {
542                 error = 0;
543                 goto out;
544         }
545
546         ASSERT(uio->uio_loffset < zp->z_phys->zp_size);
547         n = MIN(uio->uio_resid, zp->z_phys->zp_size - uio->uio_loffset);
548
549         while (n > 0) {
550                 nbytes = MIN(n, zfs_read_chunk_size -
551                     P2PHASE(uio->uio_loffset, zfs_read_chunk_size));
552
553                 if (vn_has_cached_data(vp))
554                         error = mappedread(vp, nbytes, uio);
555                 else
556                         error = dmu_read_uio(os, zp->z_id, uio, nbytes);
557                 if (error)
558                         break;
559
560                 n -= nbytes;
561         }
562
563 out:
564         zfs_range_unlock(rl);
565
566         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
567         ZFS_EXIT(zfsvfs);
568         return (error);
569 }
570
571 /*
572  * Fault in the pages of the first n bytes specified by the uio structure.
573  * 1 byte in each page is touched and the uio struct is unmodified.
574  * Any error will exit this routine as this is only a best
575  * attempt to get the pages resident. This is a copy of ufs_trans_touch().
576  */
577 static void
578 zfs_prefault_write(ssize_t n, struct uio *uio)
579 {
580         struct iovec *iov;
581         ulong_t cnt, incr;
582         caddr_t p;
583
584         if (uio->uio_segflg != UIO_USERSPACE)
585                 return;
586
587         iov = uio->uio_iov;
588
589         while (n) {
590                 cnt = MIN(iov->iov_len, n);
591                 if (cnt == 0) {
592                         /* empty iov entry */
593                         iov++;
594                         continue;
595                 }
596                 n -= cnt;
597                 /*
598                  * touch each page in this segment.
599                  */
600                 p = iov->iov_base;
601                 while (cnt) {
602                         if (fubyte(p) == -1)
603                                 return;
604                         incr = MIN(cnt, PAGESIZE);
605                         p += incr;
606                         cnt -= incr;
607                 }
608                 /*
609                  * touch the last byte in case it straddles a page.
610                  */
611                 p--;
612                 if (fubyte(p) == -1)
613                         return;
614                 iov++;
615         }
616 }
617
618 /*
619  * Write the bytes to a file.
620  *
621  *      IN:     vp      - vnode of file to be written to.
622  *              uio     - structure supplying write location, range info,
623  *                        and data buffer.
624  *              ioflag  - IO_APPEND flag set if in append mode.
625  *              cr      - credentials of caller.
626  *
627  *      OUT:    uio     - updated offset and range.
628  *
629  *      RETURN: 0 if success
630  *              error code if failure
631  *
632  * Timestamps:
633  *      vp - ctime|mtime updated if byte count > 0
634  */
635 /* ARGSUSED */
636 static int
637 zfs_write(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
638 {
639         znode_t         *zp = VTOZ(vp);
640         rlim64_t        limit = MAXOFFSET_T;
641         ssize_t         start_resid = uio->uio_resid;
642         ssize_t         tx_bytes;
643         uint64_t        end_size;
644         dmu_tx_t        *tx;
645         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
646         zilog_t         *zilog = zfsvfs->z_log;
647         offset_t        woff;
648         ssize_t         n, nbytes;
649         rl_t            *rl;
650         int             max_blksz = zfsvfs->z_max_blksz;
651         int             error;
652
653         /*
654          * Fasttrack empty write
655          */
656         n = start_resid;
657         if (n == 0)
658                 return (0);
659
660         if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
661                 limit = MAXOFFSET_T;
662
663         ZFS_ENTER(zfsvfs);
664
665         /*
666          * Pre-fault the pages to ensure slow (eg NFS) pages
667          * don't hold up txg.
668          */
669         zfs_prefault_write(n, uio);
670
671         /*
672          * If in append mode, set the io offset pointer to eof.
673          */
674         if (ioflag & IO_APPEND) {
675                 /*
676                  * Range lock for a file append:
677                  * The value for the start of range will be determined by
678                  * zfs_range_lock() (to guarantee append semantics).
679                  * If this write will cause the block size to increase,
680                  * zfs_range_lock() will lock the entire file, so we must
681                  * later reduce the range after we grow the block size.
682                  */
683                 rl = zfs_range_lock(zp, 0, n, RL_APPEND);
684                 if (rl->r_len == UINT64_MAX) {
685                         /* overlocked, zp_size can't change */
686                         woff = uio->uio_loffset = zp->z_phys->zp_size;
687                 } else {
688                         woff = uio->uio_loffset = rl->r_off;
689                 }
690         } else {
691                 woff = uio->uio_loffset;
692                 /*
693                  * Validate file offset
694                  */
695                 if (woff < 0) {
696                         ZFS_EXIT(zfsvfs);
697                         return (EINVAL);
698                 }
699
700                 /*
701                  * If we need to grow the block size then zfs_range_lock()
702                  * will lock a wider range than we request here.
703                  * Later after growing the block size we reduce the range.
704                  */
705                 rl = zfs_range_lock(zp, woff, n, RL_WRITER);
706         }
707
708         if (woff >= limit) {
709                 zfs_range_unlock(rl);
710                 ZFS_EXIT(zfsvfs);
711                 return (EFBIG);
712         }
713
714         if ((woff + n) > limit || woff > (limit - n))
715                 n = limit - woff;
716
717         /*
718          * Check for mandatory locks
719          */
720         if (MANDMODE((mode_t)zp->z_phys->zp_mode) &&
721             (error = chklock(vp, FWRITE, woff, n, uio->uio_fmode, ct)) != 0) {
722                 zfs_range_unlock(rl);
723                 ZFS_EXIT(zfsvfs);
724                 return (error);
725         }
726         end_size = MAX(zp->z_phys->zp_size, woff + n);
727
728         /*
729          * Write the file in reasonable size chunks.  Each chunk is written
730          * in a separate transaction; this keeps the intent log records small
731          * and allows us to do more fine-grained space accounting.
732          */
733         while (n > 0) {
734                 /*
735                  * Start a transaction.
736                  */
737                 woff = uio->uio_loffset;
738                 tx = dmu_tx_create(zfsvfs->z_os);
739                 dmu_tx_hold_bonus(tx, zp->z_id);
740                 dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
741                 error = dmu_tx_assign(tx, zfsvfs->z_assign);
742                 if (error) {
743                         if (error == ERESTART &&
744                             zfsvfs->z_assign == TXG_NOWAIT) {
745                                 dmu_tx_wait(tx);
746                                 dmu_tx_abort(tx);
747                                 continue;
748                         }
749                         dmu_tx_abort(tx);
750                         break;
751                 }
752
753                 /*
754                  * If zfs_range_lock() over-locked we grow the blocksize
755                  * and then reduce the lock range.  This will only happen
756                  * on the first iteration since zfs_range_reduce() will
757                  * shrink down r_len to the appropriate size.
758                  */
759                 if (rl->r_len == UINT64_MAX) {
760                         uint64_t new_blksz;
761
762                         if (zp->z_blksz > max_blksz) {
763                                 ASSERT(!ISP2(zp->z_blksz));
764                                 new_blksz = MIN(end_size, SPA_MAXBLOCKSIZE);
765                         } else {
766                                 new_blksz = MIN(end_size, max_blksz);
767                         }
768                         zfs_grow_blocksize(zp, new_blksz, tx);
769                         zfs_range_reduce(rl, woff, n);
770                 }
771
772                 /*
773                  * XXX - should we really limit each write to z_max_blksz?
774                  * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
775                  */
776                 nbytes = MIN(n, max_blksz - P2PHASE(woff, max_blksz));
777
778                 if (woff + nbytes > zp->z_phys->zp_size)
779                         vnode_pager_setsize(vp, woff + nbytes);
780
781                 rw_enter(&zp->z_map_lock, RW_READER);
782
783                 tx_bytes = uio->uio_resid;
784                 if (vn_has_cached_data(vp)) {
785                         rw_exit(&zp->z_map_lock);
786                         error = mappedwrite(vp, nbytes, uio, tx);
787                 } else {
788                         error = dmu_write_uio(zfsvfs->z_os, zp->z_id,
789                             uio, nbytes, tx);
790                         rw_exit(&zp->z_map_lock);
791                 }
792                 tx_bytes -= uio->uio_resid;
793
794                 /*
795                  * If we made no progress, we're done.  If we made even
796                  * partial progress, update the znode and ZIL accordingly.
797                  */
798                 if (tx_bytes == 0) {
799                         dmu_tx_commit(tx);
800                         ASSERT(error != 0);
801                         break;
802                 }
803
804                 /*
805                  * Clear Set-UID/Set-GID bits on successful write if not
806                  * privileged and at least one of the excute bits is set.
807                  *
808                  * It would be nice to to this after all writes have
809                  * been done, but that would still expose the ISUID/ISGID
810                  * to another app after the partial write is committed.
811                  */
812                 mutex_enter(&zp->z_acl_lock);
813                 if ((zp->z_phys->zp_mode & (S_IXUSR | (S_IXUSR >> 3) |
814                     (S_IXUSR >> 6))) != 0 &&
815                     (zp->z_phys->zp_mode & (S_ISUID | S_ISGID)) != 0 &&
816                     secpolicy_vnode_setid_retain(cr,
817                     (zp->z_phys->zp_mode & S_ISUID) != 0 &&
818                     zp->z_phys->zp_uid == 0) != 0) {
819                             zp->z_phys->zp_mode &= ~(S_ISUID | S_ISGID);
820                 }
821                 mutex_exit(&zp->z_acl_lock);
822
823                 /*
824                  * Update time stamp.  NOTE: This marks the bonus buffer as
825                  * dirty, so we don't have to do it again for zp_size.
826                  */
827                 zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
828
829                 /*
830                  * Update the file size (zp_size) if it has changed;
831                  * account for possible concurrent updates.
832                  */
833                 while ((end_size = zp->z_phys->zp_size) < uio->uio_loffset)
834                         (void) atomic_cas_64(&zp->z_phys->zp_size, end_size,
835                             uio->uio_loffset);
836                 zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, ioflag);
837                 dmu_tx_commit(tx);
838
839                 if (error != 0)
840                         break;
841                 ASSERT(tx_bytes == nbytes);
842                 n -= nbytes;
843         }
844
845         zfs_range_unlock(rl);
846
847         /*
848          * If we're in replay mode, or we made no progress, return error.
849          * Otherwise, it's at least a partial write, so it's successful.
850          */
851         if (zfsvfs->z_assign >= TXG_INITIAL || uio->uio_resid == start_resid) {
852                 ZFS_EXIT(zfsvfs);
853                 return (error);
854         }
855
856         if (ioflag & (FSYNC | FDSYNC))
857                 zil_commit(zilog, zp->z_last_itx, zp->z_id);
858
859         ZFS_EXIT(zfsvfs);
860         return (0);
861 }
862
863 void
864 zfs_get_done(dmu_buf_t *db, void *vzgd)
865 {
866         zgd_t *zgd = (zgd_t *)vzgd;
867         rl_t *rl = zgd->zgd_rl;
868         vnode_t *vp = ZTOV(rl->r_zp);
869         int vfslocked;
870
871         vfslocked = VFS_LOCK_GIANT(vp->v_vfsp);
872         dmu_buf_rele(db, vzgd);
873         zfs_range_unlock(rl);
874         VN_RELE(vp);
875         zil_add_vdev(zgd->zgd_zilog, DVA_GET_VDEV(BP_IDENTITY(zgd->zgd_bp)));
876         kmem_free(zgd, sizeof (zgd_t));
877         VFS_UNLOCK_GIANT(vfslocked);
878 }
879
880 /*
881  * Get data to generate a TX_WRITE intent log record.
882  */
883 int
884 zfs_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
885 {
886         zfsvfs_t *zfsvfs = arg;
887         objset_t *os = zfsvfs->z_os;
888         znode_t *zp;
889         uint64_t off = lr->lr_offset;
890         dmu_buf_t *db;
891         rl_t *rl;
892         zgd_t *zgd;
893         int dlen = lr->lr_length;               /* length of user data */
894         int error = 0;
895
896         ASSERT(zio);
897         ASSERT(dlen != 0);
898
899         /*
900          * Nothing to do if the file has been removed
901          */
902         if (zfs_zget(zfsvfs, lr->lr_foid, &zp) != 0)
903                 return (ENOENT);
904         if (zp->z_unlinked) {
905                 VN_RELE(ZTOV(zp));
906                 return (ENOENT);
907         }
908
909         /*
910          * Write records come in two flavors: immediate and indirect.
911          * For small writes it's cheaper to store the data with the
912          * log record (immediate); for large writes it's cheaper to
913          * sync the data and get a pointer to it (indirect) so that
914          * we don't have to write the data twice.
915          */
916         if (buf != NULL) { /* immediate write */
917                 rl = zfs_range_lock(zp, off, dlen, RL_READER);
918                 /* test for truncation needs to be done while range locked */
919                 if (off >= zp->z_phys->zp_size) {
920                         error = ENOENT;
921                         goto out;
922                 }
923                 VERIFY(0 == dmu_read(os, lr->lr_foid, off, dlen, buf));
924         } else { /* indirect write */
925                 uint64_t boff; /* block starting offset */
926
927                 /*
928                  * Have to lock the whole block to ensure when it's
929                  * written out and it's checksum is being calculated
930                  * that no one can change the data. We need to re-check
931                  * blocksize after we get the lock in case it's changed!
932                  */
933                 for (;;) {
934                         if (ISP2(zp->z_blksz)) {
935                                 boff = P2ALIGN_TYPED(off, zp->z_blksz,
936                                     uint64_t);
937                         } else {
938                                 boff = 0;
939                         }
940                         dlen = zp->z_blksz;
941                         rl = zfs_range_lock(zp, boff, dlen, RL_READER);
942                         if (zp->z_blksz == dlen)
943                                 break;
944                         zfs_range_unlock(rl);
945                 }
946                 /* test for truncation needs to be done while range locked */
947                 if (off >= zp->z_phys->zp_size) {
948                         error = ENOENT;
949                         goto out;
950                 }
951                 zgd = (zgd_t *)kmem_alloc(sizeof (zgd_t), KM_SLEEP);
952                 zgd->zgd_rl = rl;
953                 zgd->zgd_zilog = zfsvfs->z_log;
954                 zgd->zgd_bp = &lr->lr_blkptr;
955                 VERIFY(0 == dmu_buf_hold(os, lr->lr_foid, boff, zgd, &db));
956                 ASSERT(boff == db->db_offset);
957                 lr->lr_blkoff = off - boff;
958                 error = dmu_sync(zio, db, &lr->lr_blkptr,
959                     lr->lr_common.lrc_txg, zfs_get_done, zgd);
960                 ASSERT(error == EEXIST || lr->lr_length <= zp->z_blksz);
961                 if (error == 0) {
962                         zil_add_vdev(zfsvfs->z_log,
963                             DVA_GET_VDEV(BP_IDENTITY(&lr->lr_blkptr)));
964                 }
965                 /*
966                  * If we get EINPROGRESS, then we need to wait for a
967                  * write IO initiated by dmu_sync() to complete before
968                  * we can release this dbuf.  We will finish everything
969                  * up in the zfs_get_done() callback.
970                  */
971                 if (error == EINPROGRESS)
972                         return (0);
973                 dmu_buf_rele(db, zgd);
974                 kmem_free(zgd, sizeof (zgd_t));
975         }
976 out:
977         zfs_range_unlock(rl);
978         VN_RELE(ZTOV(zp));
979         return (error);
980 }
981
982 /*ARGSUSED*/
983 static int
984 zfs_access(vnode_t *vp, int mode, int flags, cred_t *cr)
985 {
986         znode_t *zp = VTOZ(vp);
987         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
988         int error;
989
990         ZFS_ENTER(zfsvfs);
991         error = zfs_zaccess_rwx(zp, mode, cr);
992         ZFS_EXIT(zfsvfs);
993         return (error);
994 }
995
996 /*
997  * Lookup an entry in a directory, or an extended attribute directory.
998  * If it exists, return a held vnode reference for it.
999  *
1000  *      IN:     dvp     - vnode of directory to search.
1001  *              nm      - name of entry to lookup.
1002  *              pnp     - full pathname to lookup [UNUSED].
1003  *              flags   - LOOKUP_XATTR set if looking for an attribute.
1004  *              rdir    - root directory vnode [UNUSED].
1005  *              cr      - credentials of caller.
1006  *
1007  *      OUT:    vpp     - vnode of located entry, NULL if not found.
1008  *
1009  *      RETURN: 0 if success
1010  *              error code if failure
1011  *
1012  * Timestamps:
1013  *      NA
1014  */
1015 /* ARGSUSED */
1016 static int
1017 zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct componentname *cnp,
1018     int nameiop, cred_t *cr, kthread_t *td)
1019 {
1020
1021         znode_t *zdp = VTOZ(dvp);
1022         zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
1023         int     error;
1024
1025         ZFS_ENTER(zfsvfs);
1026
1027         *vpp = NULL;
1028
1029 #ifdef TODO
1030         if (flags & LOOKUP_XATTR) {
1031                 /*
1032                  * If the xattr property is off, refuse the lookup request.
1033                  */
1034                 if (!(zfsvfs->z_vfs->vfs_flag & VFS_XATTR)) {
1035                         ZFS_EXIT(zfsvfs);
1036                         return (EINVAL);
1037                 }
1038
1039                 /*
1040                  * We don't allow recursive attributes..
1041                  * Maybe someday we will.
1042                  */
1043                 if (zdp->z_phys->zp_flags & ZFS_XATTR) {
1044                         ZFS_EXIT(zfsvfs);
1045                         return (EINVAL);
1046                 }
1047
1048                 if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr, flags)) {
1049                         ZFS_EXIT(zfsvfs);
1050                         return (error);
1051                 }
1052
1053                 /*
1054                  * Do we have permission to get into attribute directory?
1055                  */
1056
1057                 if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, cr)) {
1058                         VN_RELE(*vpp);
1059                 }
1060
1061                 ZFS_EXIT(zfsvfs);
1062                 return (error);
1063         }
1064 #endif  /* TODO */
1065
1066         if (dvp->v_type != VDIR) {
1067                 ZFS_EXIT(zfsvfs);
1068                 return (ENOTDIR);
1069         }
1070
1071         /*
1072          * Check accessibility of directory.
1073          */
1074
1075         if (error = zfs_zaccess(zdp, ACE_EXECUTE, cr)) {
1076                 ZFS_EXIT(zfsvfs);
1077                 return (error);
1078         }
1079
1080         if ((error = zfs_dirlook(zdp, nm, vpp)) == 0) {
1081
1082                 /*
1083                  * Convert device special files
1084                  */
1085                 if (IS_DEVVP(*vpp)) {
1086                         vnode_t *svp;
1087
1088                         svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1089                         VN_RELE(*vpp);
1090                         if (svp == NULL)
1091                                 error = ENOSYS;
1092                         else
1093                                 *vpp = svp;
1094                 }
1095         }
1096
1097         ZFS_EXIT(zfsvfs);
1098
1099         /* Translate errors and add SAVENAME when needed. */
1100         if (cnp->cn_flags & ISLASTCN) {
1101                 switch (nameiop) {
1102                 case CREATE:
1103                 case RENAME:
1104                         if (error == ENOENT) {
1105                                 error = EJUSTRETURN;
1106                                 cnp->cn_flags |= SAVENAME;
1107                                 break;
1108                         }
1109                         /* FALLTHROUGH */
1110                 case DELETE:
1111                         if (error == 0)
1112                                 cnp->cn_flags |= SAVENAME;
1113                         break;
1114                 }
1115         }
1116         if (error == 0 && (nm[0] != '.' || nm[1] != '\0')) {
1117                 int ltype = 0;
1118
1119                 if (cnp->cn_flags & ISDOTDOT) {
1120                         ltype = VOP_ISLOCKED(dvp, td);
1121                         VOP_UNLOCK(dvp, 0, td);
1122                 }
1123                 error = vn_lock(*vpp, cnp->cn_lkflags, td);
1124                 if (cnp->cn_flags & ISDOTDOT)
1125                         vn_lock(dvp, ltype | LK_RETRY, td);
1126                 if (error != 0) {
1127                         VN_RELE(*vpp);
1128                         *vpp = NULL;
1129                         return (error);
1130                 }
1131         }
1132
1133 #ifdef FREEBSD_NAMECACHE
1134         /*
1135          * Insert name into cache (as non-existent) if appropriate.
1136          */
1137         if (error == ENOENT && (cnp->cn_flags & MAKEENTRY) && nameiop != CREATE)
1138                 cache_enter(dvp, *vpp, cnp);
1139         /*
1140          * Insert name into cache if appropriate.
1141          */
1142         if (error == 0 && (cnp->cn_flags & MAKEENTRY)) {
1143                 if (!(cnp->cn_flags & ISLASTCN) ||
1144                     (nameiop != DELETE && nameiop != RENAME)) {
1145                         cache_enter(dvp, *vpp, cnp);
1146                 }
1147         }
1148 #endif
1149
1150         return (error);
1151 }
1152
1153 /*
1154  * Attempt to create a new entry in a directory.  If the entry
1155  * already exists, truncate the file if permissible, else return
1156  * an error.  Return the vp of the created or trunc'd file.
1157  *
1158  *      IN:     dvp     - vnode of directory to put new file entry in.
1159  *              name    - name of new file entry.
1160  *              vap     - attributes of new file.
1161  *              excl    - flag indicating exclusive or non-exclusive mode.
1162  *              mode    - mode to open file with.
1163  *              cr      - credentials of caller.
1164  *              flag    - large file flag [UNUSED].
1165  *
1166  *      OUT:    vpp     - vnode of created or trunc'd entry.
1167  *
1168  *      RETURN: 0 if success
1169  *              error code if failure
1170  *
1171  * Timestamps:
1172  *      dvp - ctime|mtime updated if new entry created
1173  *       vp - ctime|mtime always, atime if new
1174  */
1175 /* ARGSUSED */
1176 static int
1177 zfs_create(vnode_t *dvp, char *name, vattr_t *vap, int excl, int mode,
1178     vnode_t **vpp, cred_t *cr, kthread_t *td)
1179 {
1180         znode_t         *zp, *dzp = VTOZ(dvp);
1181         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1182         zilog_t         *zilog = zfsvfs->z_log;
1183         objset_t        *os = zfsvfs->z_os;
1184         zfs_dirlock_t   *dl;
1185         dmu_tx_t        *tx;
1186         int             error;
1187         uint64_t        zoid;
1188
1189         ZFS_ENTER(zfsvfs);
1190
1191 top:
1192         *vpp = NULL;
1193
1194         if ((vap->va_mode & VSVTX) && secpolicy_vnode_stky_modify(cr))
1195                 vap->va_mode &= ~VSVTX;
1196
1197         if (*name == '\0') {
1198                 /*
1199                  * Null component name refers to the directory itself.
1200                  */
1201                 VN_HOLD(dvp);
1202                 zp = dzp;
1203                 dl = NULL;
1204                 error = 0;
1205         } else {
1206                 /* possible VN_HOLD(zp) */
1207                 if (error = zfs_dirent_lock(&dl, dzp, name, &zp, 0)) {
1208                         if (strcmp(name, "..") == 0)
1209                                 error = EISDIR;
1210                         ZFS_EXIT(zfsvfs);
1211                         return (error);
1212                 }
1213         }
1214
1215         zoid = zp ? zp->z_id : -1ULL;
1216
1217         if (zp == NULL) {
1218                 /*
1219                  * Create a new file object and update the directory
1220                  * to reference it.
1221                  */
1222                 if (error = zfs_zaccess(dzp, ACE_ADD_FILE, cr)) {
1223                         goto out;
1224                 }
1225
1226                 /*
1227                  * We only support the creation of regular files in
1228                  * extended attribute directories.
1229                  */
1230                 if ((dzp->z_phys->zp_flags & ZFS_XATTR) &&
1231                     (vap->va_type != VREG)) {
1232                         error = EINVAL;
1233                         goto out;
1234                 }
1235
1236                 tx = dmu_tx_create(os);
1237                 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1238                 dmu_tx_hold_bonus(tx, dzp->z_id);
1239                 dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1240                 if (dzp->z_phys->zp_flags & ZFS_INHERIT_ACE)
1241                         dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1242                             0, SPA_MAXBLOCKSIZE);
1243                 error = dmu_tx_assign(tx, zfsvfs->z_assign);
1244                 if (error) {
1245                         zfs_dirent_unlock(dl);
1246                         if (error == ERESTART &&
1247                             zfsvfs->z_assign == TXG_NOWAIT) {
1248                                 dmu_tx_wait(tx);
1249                                 dmu_tx_abort(tx);
1250                                 goto top;
1251                         }
1252                         dmu_tx_abort(tx);
1253                         ZFS_EXIT(zfsvfs);
1254                         return (error);
1255                 }
1256                 zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, 0);
1257                 ASSERT(zp->z_id == zoid);
1258                 (void) zfs_link_create(dl, zp, tx, ZNEW);
1259                 zfs_log_create(zilog, tx, TX_CREATE, dzp, zp, name);
1260                 dmu_tx_commit(tx);
1261         } else {
1262                 /*
1263                  * A directory entry already exists for this name.
1264                  */
1265                 /*
1266                  * Can't truncate an existing file if in exclusive mode.
1267                  */
1268                 if (excl == EXCL) {
1269                         error = EEXIST;
1270                         goto out;
1271                 }
1272                 /*
1273                  * Can't open a directory for writing.
1274                  */
1275                 if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1276                         error = EISDIR;
1277                         goto out;
1278                 }
1279                 /*
1280                  * Verify requested access to file.
1281                  */
1282                 if (mode && (error = zfs_zaccess_rwx(zp, mode, cr))) {
1283                         goto out;
1284                 }
1285
1286                 mutex_enter(&dzp->z_lock);
1287                 dzp->z_seq++;
1288                 mutex_exit(&dzp->z_lock);
1289
1290                 /*
1291                  * Truncate regular files if requested.
1292                  */
1293                 if ((ZTOV(zp)->v_type == VREG) &&
1294                     (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1295                         error = zfs_freesp(zp, 0, 0, mode, TRUE);
1296                         if (error == ERESTART &&
1297                             zfsvfs->z_assign == TXG_NOWAIT) {
1298                                 /* NB: we already did dmu_tx_wait() */
1299                                 zfs_dirent_unlock(dl);
1300                                 VN_RELE(ZTOV(zp));
1301                                 goto top;
1302                         }
1303                 }
1304         }
1305 out:
1306         if (dl)
1307                 zfs_dirent_unlock(dl);
1308
1309         if (error) {
1310                 if (zp)
1311                         VN_RELE(ZTOV(zp));
1312         } else {
1313                 *vpp = ZTOV(zp);
1314                 /*
1315                  * If vnode is for a device return a specfs vnode instead.
1316                  */
1317                 if (IS_DEVVP(*vpp)) {
1318                         struct vnode *svp;
1319
1320                         svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1321                         VN_RELE(*vpp);
1322                         if (svp == NULL) {
1323                                 error = ENOSYS;
1324                         }
1325                         *vpp = svp;
1326                 }
1327         }
1328
1329         ZFS_EXIT(zfsvfs);
1330         return (error);
1331 }
1332
1333 /*
1334  * Remove an entry from a directory.
1335  *
1336  *      IN:     dvp     - vnode of directory to remove entry from.
1337  *              name    - name of entry to remove.
1338  *              cr      - credentials of caller.
1339  *
1340  *      RETURN: 0 if success
1341  *              error code if failure
1342  *
1343  * Timestamps:
1344  *      dvp - ctime|mtime
1345  *       vp - ctime (if nlink > 0)
1346  */
1347 static int
1348 zfs_remove(vnode_t *dvp, char *name, cred_t *cr)
1349 {
1350         znode_t         *zp, *dzp = VTOZ(dvp);
1351         znode_t         *xzp = NULL;
1352         vnode_t         *vp;
1353         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1354         zilog_t         *zilog = zfsvfs->z_log;
1355         uint64_t        acl_obj, xattr_obj;
1356         zfs_dirlock_t   *dl;
1357         dmu_tx_t        *tx;
1358         boolean_t       may_delete_now, delete_now = FALSE;
1359         boolean_t       unlinked;
1360         int             error;
1361
1362         ZFS_ENTER(zfsvfs);
1363
1364 top:
1365         /*
1366          * Attempt to lock directory; fail if entry doesn't exist.
1367          */
1368         if (error = zfs_dirent_lock(&dl, dzp, name, &zp, ZEXISTS)) {
1369                 ZFS_EXIT(zfsvfs);
1370                 return (error);
1371         }
1372
1373         vp = ZTOV(zp);
1374
1375         if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1376                 goto out;
1377         }
1378
1379         /*
1380          * Need to use rmdir for removing directories.
1381          */
1382         if (vp->v_type == VDIR) {
1383                 error = EPERM;
1384                 goto out;
1385         }
1386
1387         vnevent_remove(vp);
1388
1389         dnlc_remove(dvp, name);
1390
1391         may_delete_now = FALSE;
1392
1393         /*
1394          * We may delete the znode now, or we may put it in the unlinked set;
1395          * it depends on whether we're the last link, and on whether there are
1396          * other holds on the vnode.  So we dmu_tx_hold() the right things to
1397          * allow for either case.
1398          */
1399         tx = dmu_tx_create(zfsvfs->z_os);
1400         dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1401         dmu_tx_hold_bonus(tx, zp->z_id);
1402         if (may_delete_now)
1403                 dmu_tx_hold_free(tx, zp->z_id, 0, DMU_OBJECT_END);
1404
1405         /* are there any extended attributes? */
1406         if ((xattr_obj = zp->z_phys->zp_xattr) != 0) {
1407                 /* XXX - do we need this if we are deleting? */
1408                 dmu_tx_hold_bonus(tx, xattr_obj);
1409         }
1410
1411         /* are there any additional acls */
1412         if ((acl_obj = zp->z_phys->zp_acl.z_acl_extern_obj) != 0 &&
1413             may_delete_now)
1414                 dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1415
1416         /* charge as an update -- would be nice not to charge at all */
1417         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1418
1419         error = dmu_tx_assign(tx, zfsvfs->z_assign);
1420         if (error) {
1421                 zfs_dirent_unlock(dl);
1422                 VN_RELE(vp);
1423                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1424                         dmu_tx_wait(tx);
1425                         dmu_tx_abort(tx);
1426                         goto top;
1427                 }
1428                 dmu_tx_abort(tx);
1429                 ZFS_EXIT(zfsvfs);
1430                 return (error);
1431         }
1432
1433         /*
1434          * Remove the directory entry.
1435          */
1436         error = zfs_link_destroy(dl, zp, tx, 0, &unlinked);
1437
1438         if (error) {
1439                 dmu_tx_commit(tx);
1440                 goto out;
1441         }
1442
1443         if (0 && unlinked) {
1444                 VI_LOCK(vp);
1445                 delete_now = may_delete_now &&
1446                     vp->v_count == 1 && !vn_has_cached_data(vp) &&
1447                     zp->z_phys->zp_xattr == xattr_obj &&
1448                     zp->z_phys->zp_acl.z_acl_extern_obj == acl_obj;
1449                 VI_UNLOCK(vp);
1450         }
1451
1452         if (delete_now) {
1453                 if (zp->z_phys->zp_xattr) {
1454                         error = zfs_zget(zfsvfs, zp->z_phys->zp_xattr, &xzp);
1455                         ASSERT3U(error, ==, 0);
1456                         ASSERT3U(xzp->z_phys->zp_links, ==, 2);
1457                         dmu_buf_will_dirty(xzp->z_dbuf, tx);
1458                         mutex_enter(&xzp->z_lock);
1459                         xzp->z_unlinked = 1;
1460                         xzp->z_phys->zp_links = 0;
1461                         mutex_exit(&xzp->z_lock);
1462                         zfs_unlinked_add(xzp, tx);
1463                         zp->z_phys->zp_xattr = 0; /* probably unnecessary */
1464                 }
1465                 mutex_enter(&zp->z_lock);
1466                 VI_LOCK(vp);
1467                 vp->v_count--;
1468                 ASSERT3U(vp->v_count, ==, 0);
1469                 VI_UNLOCK(vp);
1470                 mutex_exit(&zp->z_lock);
1471                 zfs_znode_delete(zp, tx);
1472                 VFS_RELE(zfsvfs->z_vfs);
1473         } else if (unlinked) {
1474                 zfs_unlinked_add(zp, tx);
1475         }
1476
1477         zfs_log_remove(zilog, tx, TX_REMOVE, dzp, name);
1478
1479         dmu_tx_commit(tx);
1480 out:
1481         zfs_dirent_unlock(dl);
1482
1483         if (!delete_now) {
1484                 VN_RELE(vp);
1485         } else if (xzp) {
1486                 /* this rele delayed to prevent nesting transactions */
1487                 VN_RELE(ZTOV(xzp));
1488         }
1489
1490         ZFS_EXIT(zfsvfs);
1491         return (error);
1492 }
1493
1494 /*
1495  * Create a new directory and insert it into dvp using the name
1496  * provided.  Return a pointer to the inserted directory.
1497  *
1498  *      IN:     dvp     - vnode of directory to add subdir to.
1499  *              dirname - name of new directory.
1500  *              vap     - attributes of new directory.
1501  *              cr      - credentials of caller.
1502  *
1503  *      OUT:    vpp     - vnode of created directory.
1504  *
1505  *      RETURN: 0 if success
1506  *              error code if failure
1507  *
1508  * Timestamps:
1509  *      dvp - ctime|mtime updated
1510  *       vp - ctime|mtime|atime updated
1511  */
1512 static int
1513 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr)
1514 {
1515         znode_t         *zp, *dzp = VTOZ(dvp);
1516         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1517         zilog_t         *zilog = zfsvfs->z_log;
1518         zfs_dirlock_t   *dl;
1519         uint64_t        zoid = 0;
1520         dmu_tx_t        *tx;
1521         int             error;
1522
1523         ASSERT(vap->va_type == VDIR);
1524
1525         ZFS_ENTER(zfsvfs);
1526
1527         if (dzp->z_phys->zp_flags & ZFS_XATTR) {
1528                 ZFS_EXIT(zfsvfs);
1529                 return (EINVAL);
1530         }
1531 top:
1532         *vpp = NULL;
1533
1534         /*
1535          * First make sure the new directory doesn't exist.
1536          */
1537         if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, ZNEW)) {
1538                 ZFS_EXIT(zfsvfs);
1539                 return (error);
1540         }
1541
1542         if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, cr)) {
1543                 zfs_dirent_unlock(dl);
1544                 ZFS_EXIT(zfsvfs);
1545                 return (error);
1546         }
1547
1548         /*
1549          * Add a new entry to the directory.
1550          */
1551         tx = dmu_tx_create(zfsvfs->z_os);
1552         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1553         dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1554         if (dzp->z_phys->zp_flags & ZFS_INHERIT_ACE)
1555                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1556                     0, SPA_MAXBLOCKSIZE);
1557         error = dmu_tx_assign(tx, zfsvfs->z_assign);
1558         if (error) {
1559                 zfs_dirent_unlock(dl);
1560                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1561                         dmu_tx_wait(tx);
1562                         dmu_tx_abort(tx);
1563                         goto top;
1564                 }
1565                 dmu_tx_abort(tx);
1566                 ZFS_EXIT(zfsvfs);
1567                 return (error);
1568         }
1569
1570         /*
1571          * Create new node.
1572          */
1573         zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, 0);
1574
1575         /*
1576          * Now put new name in parent dir.
1577          */
1578         (void) zfs_link_create(dl, zp, tx, ZNEW);
1579
1580         *vpp = ZTOV(zp);
1581
1582         zfs_log_create(zilog, tx, TX_MKDIR, dzp, zp, dirname);
1583         dmu_tx_commit(tx);
1584
1585         zfs_dirent_unlock(dl);
1586
1587         ZFS_EXIT(zfsvfs);
1588         return (0);
1589 }
1590
1591 /*
1592  * Remove a directory subdir entry.  If the current working
1593  * directory is the same as the subdir to be removed, the
1594  * remove will fail.
1595  *
1596  *      IN:     dvp     - vnode of directory to remove from.
1597  *              name    - name of directory to be removed.
1598  *              cwd     - vnode of current working directory.
1599  *              cr      - credentials of caller.
1600  *
1601  *      RETURN: 0 if success
1602  *              error code if failure
1603  *
1604  * Timestamps:
1605  *      dvp - ctime|mtime updated
1606  */
1607 static int
1608 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr)
1609 {
1610         znode_t         *dzp = VTOZ(dvp);
1611         znode_t         *zp;
1612         vnode_t         *vp;
1613         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
1614         zilog_t         *zilog = zfsvfs->z_log;
1615         zfs_dirlock_t   *dl;
1616         dmu_tx_t        *tx;
1617         int             error;
1618
1619         ZFS_ENTER(zfsvfs);
1620
1621 top:
1622         zp = NULL;
1623
1624         /*
1625          * Attempt to lock directory; fail if entry doesn't exist.
1626          */
1627         if (error = zfs_dirent_lock(&dl, dzp, name, &zp, ZEXISTS)) {
1628                 ZFS_EXIT(zfsvfs);
1629                 return (error);
1630         }
1631
1632         vp = ZTOV(zp);
1633
1634         if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1635                 goto out;
1636         }
1637
1638         if (vp->v_type != VDIR) {
1639                 error = ENOTDIR;
1640                 goto out;
1641         }
1642
1643         if (vp == cwd) {
1644                 error = EINVAL;
1645                 goto out;
1646         }
1647
1648         vnevent_rmdir(vp);
1649
1650         /*
1651          * Grab a lock on the directory to make sure that noone is
1652          * trying to add (or lookup) entries while we are removing it.
1653          */
1654         rw_enter(&zp->z_name_lock, RW_WRITER);
1655
1656         /*
1657          * Grab a lock on the parent pointer to make sure we play well
1658          * with the treewalk and directory rename code.
1659          */
1660         rw_enter(&zp->z_parent_lock, RW_WRITER);
1661
1662         tx = dmu_tx_create(zfsvfs->z_os);
1663         dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1664         dmu_tx_hold_bonus(tx, zp->z_id);
1665         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1666         error = dmu_tx_assign(tx, zfsvfs->z_assign);
1667         if (error) {
1668                 rw_exit(&zp->z_parent_lock);
1669                 rw_exit(&zp->z_name_lock);
1670                 zfs_dirent_unlock(dl);
1671                 VN_RELE(vp);
1672                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1673                         dmu_tx_wait(tx);
1674                         dmu_tx_abort(tx);
1675                         goto top;
1676                 }
1677                 dmu_tx_abort(tx);
1678                 ZFS_EXIT(zfsvfs);
1679                 return (error);
1680         }
1681
1682 #ifdef FREEBSD_NAMECACHE
1683         cache_purge(dvp);
1684 #endif
1685
1686         error = zfs_link_destroy(dl, zp, tx, 0, NULL);
1687
1688         if (error == 0)
1689                 zfs_log_remove(zilog, tx, TX_RMDIR, dzp, name);
1690
1691         dmu_tx_commit(tx);
1692
1693         rw_exit(&zp->z_parent_lock);
1694         rw_exit(&zp->z_name_lock);
1695 #ifdef FREEBSD_NAMECACHE
1696         cache_purge(vp);
1697 #endif
1698 out:
1699         zfs_dirent_unlock(dl);
1700
1701         VN_RELE(vp);
1702
1703         ZFS_EXIT(zfsvfs);
1704         return (error);
1705 }
1706
1707 /*
1708  * Read as many directory entries as will fit into the provided
1709  * buffer from the given directory cursor position (specified in
1710  * the uio structure.
1711  *
1712  *      IN:     vp      - vnode of directory to read.
1713  *              uio     - structure supplying read location, range info,
1714  *                        and return buffer.
1715  *              cr      - credentials of caller.
1716  *
1717  *      OUT:    uio     - updated offset and range, buffer filled.
1718  *              eofp    - set to true if end-of-file detected.
1719  *
1720  *      RETURN: 0 if success
1721  *              error code if failure
1722  *
1723  * Timestamps:
1724  *      vp - atime updated
1725  *
1726  * Note that the low 4 bits of the cookie returned by zap is always zero.
1727  * This allows us to use the low range for "special" directory entries:
1728  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
1729  * we use the offset 2 for the '.zfs' directory.
1730  */
1731 /* ARGSUSED */
1732 static int
1733 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp, int *ncookies, u_long **cookies)
1734 {
1735         znode_t         *zp = VTOZ(vp);
1736         iovec_t         *iovp;
1737         dirent64_t      *odp;
1738         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
1739         objset_t        *os;
1740         caddr_t         outbuf;
1741         size_t          bufsize;
1742         zap_cursor_t    zc;
1743         zap_attribute_t zap;
1744         uint_t          bytes_wanted;
1745         uint64_t        offset; /* must be unsigned; checks for < 1 */
1746         int             local_eof;
1747         int             outcount;
1748         int             error;
1749         uint8_t         prefetch;
1750         uint8_t         type;
1751         int             ncooks;
1752         u_long          *cooks = NULL;
1753
1754         ZFS_ENTER(zfsvfs);
1755
1756         /*
1757          * If we are not given an eof variable,
1758          * use a local one.
1759          */
1760         if (eofp == NULL)
1761                 eofp = &local_eof;
1762
1763         /*
1764          * Check for valid iov_len.
1765          */
1766         if (uio->uio_iov->iov_len <= 0) {
1767                 ZFS_EXIT(zfsvfs);
1768                 return (EINVAL);
1769         }
1770
1771         /*
1772          * Quit if directory has been removed (posix)
1773          */
1774         if ((*eofp = zp->z_unlinked) != 0) {
1775                 ZFS_EXIT(zfsvfs);
1776                 return (0);
1777         }
1778
1779         error = 0;
1780         os = zfsvfs->z_os;
1781         offset = uio->uio_loffset;
1782         prefetch = zp->z_zn_prefetch;
1783
1784         /*
1785          * Initialize the iterator cursor.
1786          */
1787         if (offset <= 3) {
1788                 /*
1789                  * Start iteration from the beginning of the directory.
1790                  */
1791                 zap_cursor_init(&zc, os, zp->z_id);
1792         } else {
1793                 /*
1794                  * The offset is a serialized cursor.
1795                  */
1796                 zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
1797         }
1798
1799         /*
1800          * Get space to change directory entries into fs independent format.
1801          */
1802         iovp = uio->uio_iov;
1803         bytes_wanted = iovp->iov_len;
1804         if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
1805                 bufsize = bytes_wanted;
1806                 outbuf = kmem_alloc(bufsize, KM_SLEEP);
1807                 odp = (struct dirent64 *)outbuf;
1808         } else {
1809                 bufsize = bytes_wanted;
1810                 odp = (struct dirent64 *)iovp->iov_base;
1811         }
1812
1813         if (ncookies != NULL) {
1814                 /*
1815                  * Minimum entry size is dirent size and 1 byte for a file name.
1816                  */
1817                 ncooks = uio->uio_resid / (sizeof(struct dirent) - sizeof(((struct dirent *)NULL)->d_name) + 1);
1818                 cooks = malloc(ncooks * sizeof(u_long), M_TEMP, M_WAITOK);
1819                 *cookies = cooks;
1820                 *ncookies = ncooks;
1821         }
1822
1823         /*
1824          * Transform to file-system independent format
1825          */
1826         outcount = 0;
1827         while (outcount < bytes_wanted) {
1828                 ino64_t objnum;
1829                 ushort_t reclen;
1830
1831                 /*
1832                  * Special case `.', `..', and `.zfs'.
1833                  */
1834                 if (offset == 0) {
1835                         (void) strcpy(zap.za_name, ".");
1836                         objnum = zp->z_id;
1837                         type = DT_DIR;
1838                 } else if (offset == 1) {
1839                         (void) strcpy(zap.za_name, "..");
1840                         objnum = zp->z_phys->zp_parent;
1841                         type = DT_DIR;
1842                 } else if (offset == 2 && zfs_show_ctldir(zp)) {
1843                         (void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
1844                         objnum = ZFSCTL_INO_ROOT;
1845                         type = DT_DIR;
1846                 } else {
1847                         /*
1848                          * Grab next entry.
1849                          */
1850                         if (error = zap_cursor_retrieve(&zc, &zap)) {
1851                                 if ((*eofp = (error == ENOENT)) != 0)
1852                                         break;
1853                                 else
1854                                         goto update;
1855                         }
1856
1857                         if (zap.za_integer_length != 8 ||
1858                             zap.za_num_integers != 1) {
1859                                 cmn_err(CE_WARN, "zap_readdir: bad directory "
1860                                     "entry, obj = %lld, offset = %lld\n",
1861                                     (u_longlong_t)zp->z_id,
1862                                     (u_longlong_t)offset);
1863                                 error = ENXIO;
1864                                 goto update;
1865                         }
1866
1867                         objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
1868                         /*
1869                          * MacOS X can extract the object type here such as:
1870                          * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
1871                          */
1872                         type = ZFS_DIRENT_TYPE(zap.za_first_integer);
1873                 }
1874                 reclen = DIRENT64_RECLEN(strlen(zap.za_name));
1875
1876                 /*
1877                  * Will this entry fit in the buffer?
1878                  */
1879                 if (outcount + reclen > bufsize) {
1880                         /*
1881                          * Did we manage to fit anything in the buffer?
1882                          */
1883                         if (!outcount) {
1884                                 error = EINVAL;
1885                                 goto update;
1886                         }
1887                         break;
1888                 }
1889                 /*
1890                  * Add this entry:
1891                  */
1892                 odp->d_ino = objnum;
1893                 odp->d_reclen = reclen;
1894                 odp->d_namlen = strlen(zap.za_name);
1895                 (void) strlcpy(odp->d_name, zap.za_name, odp->d_namlen + 1);
1896                 odp->d_type = type;
1897                 outcount += reclen;
1898                 odp = (dirent64_t *)((intptr_t)odp + reclen);
1899
1900                 ASSERT(outcount <= bufsize);
1901
1902                 /* Prefetch znode */
1903                 if (prefetch)
1904                         dmu_prefetch(os, objnum, 0, 0);
1905
1906                 /*
1907                  * Move to the next entry, fill in the previous offset.
1908                  */
1909                 if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
1910                         zap_cursor_advance(&zc);
1911                         offset = zap_cursor_serialize(&zc);
1912                 } else {
1913                         offset += 1;
1914                 }
1915
1916                 if (cooks != NULL) {
1917                         *cooks++ = offset;
1918                         ncooks--;
1919                         KASSERT(ncooks >= 0, ("ncookies=%d", ncooks));
1920                 }
1921         }
1922         zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
1923
1924         /* Subtract unused cookies */
1925         if (ncookies != NULL)
1926                 *ncookies -= ncooks;
1927
1928         if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
1929                 iovp->iov_base += outcount;
1930                 iovp->iov_len -= outcount;
1931                 uio->uio_resid -= outcount;
1932         } else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
1933                 /*
1934                  * Reset the pointer.
1935                  */
1936                 offset = uio->uio_loffset;
1937         }
1938
1939 update:
1940         zap_cursor_fini(&zc);
1941         if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
1942                 kmem_free(outbuf, bufsize);
1943
1944         if (error == ENOENT)
1945                 error = 0;
1946
1947         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
1948
1949         uio->uio_loffset = offset;
1950         ZFS_EXIT(zfsvfs);
1951         if (error != 0 && cookies != NULL) {
1952                 free(*cookies, M_TEMP);
1953                 *cookies = NULL;
1954                 *ncookies = 0;
1955         }
1956         return (error);
1957 }
1958
1959 static int
1960 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr)
1961 {
1962         znode_t *zp = VTOZ(vp);
1963         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1964
1965         ZFS_ENTER(zfsvfs);
1966         zil_commit(zfsvfs->z_log, zp->z_last_itx, zp->z_id);
1967         ZFS_EXIT(zfsvfs);
1968         return (0);
1969 }
1970
1971 /*
1972  * Get the requested file attributes and place them in the provided
1973  * vattr structure.
1974  *
1975  *      IN:     vp      - vnode of file.
1976  *              vap     - va_mask identifies requested attributes.
1977  *              flags   - [UNUSED]
1978  *              cr      - credentials of caller.
1979  *
1980  *      OUT:    vap     - attribute values.
1981  *
1982  *      RETURN: 0 (always succeeds)
1983  */
1984 /* ARGSUSED */
1985 static int
1986 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr)
1987 {
1988         znode_t *zp = VTOZ(vp);
1989         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1990         znode_phys_t *pzp = zp->z_phys;
1991         uint32_t blksize;
1992         u_longlong_t nblocks;
1993         int     error;
1994
1995         ZFS_ENTER(zfsvfs);
1996
1997         /*
1998          * Return all attributes.  It's cheaper to provide the answer
1999          * than to determine whether we were asked the question.
2000          */
2001         mutex_enter(&zp->z_lock);
2002
2003         vap->va_type = IFTOVT(pzp->zp_mode);
2004         vap->va_mode = pzp->zp_mode & ~S_IFMT;
2005         vap->va_uid = zp->z_phys->zp_uid;
2006         vap->va_gid = zp->z_phys->zp_gid;
2007         vap->va_nodeid = zp->z_id;
2008         vap->va_nlink = MIN(pzp->zp_links, UINT32_MAX); /* nlink_t limit! */
2009         vap->va_size = pzp->zp_size;
2010         vap->va_fsid = vp->v_mount->mnt_stat.f_fsid.val[0];
2011         vap->va_rdev = zfs_cmpldev(pzp->zp_rdev);
2012         vap->va_seq = zp->z_seq;
2013         vap->va_flags = 0;      /* FreeBSD: Reset chflags(2) flags. */
2014
2015         ZFS_TIME_DECODE(&vap->va_atime, pzp->zp_atime);
2016         ZFS_TIME_DECODE(&vap->va_mtime, pzp->zp_mtime);
2017         ZFS_TIME_DECODE(&vap->va_ctime, pzp->zp_ctime);
2018         ZFS_TIME_DECODE(&vap->va_birthtime, pzp->zp_crtime);
2019
2020         /*
2021          * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2022          * Also, if we are the owner don't bother, since owner should
2023          * always be allowed to read basic attributes of file.
2024          */
2025         if (!(zp->z_phys->zp_flags & ZFS_ACL_TRIVIAL) &&
2026             (zp->z_phys->zp_uid != crgetuid(cr))) {
2027                 if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, cr)) {
2028                         mutex_exit(&zp->z_lock);
2029                         ZFS_EXIT(zfsvfs);
2030                         return (error);
2031                 }
2032         }
2033
2034         mutex_exit(&zp->z_lock);
2035
2036         dmu_object_size_from_db(zp->z_dbuf, &blksize, &nblocks);
2037         vap->va_blksize = blksize;
2038         vap->va_bytes = nblocks << 9;   /* nblocks * 512 */
2039
2040         if (zp->z_blksz == 0) {
2041                 /*
2042                  * Block size hasn't been set; suggest maximal I/O transfers.
2043                  */
2044                 vap->va_blksize = zfsvfs->z_max_blksz;
2045         }
2046
2047         ZFS_EXIT(zfsvfs);
2048         return (0);
2049 }
2050
2051 /*
2052  * Set the file attributes to the values contained in the
2053  * vattr structure.
2054  *
2055  *      IN:     vp      - vnode of file to be modified.
2056  *              vap     - new attribute values.
2057  *              flags   - ATTR_UTIME set if non-default time values provided.
2058  *              cr      - credentials of caller.
2059  *
2060  *      RETURN: 0 if success
2061  *              error code if failure
2062  *
2063  * Timestamps:
2064  *      vp - ctime updated, mtime updated if size changed.
2065  */
2066 /* ARGSUSED */
2067 static int
2068 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2069         caller_context_t *ct)
2070 {
2071         struct znode    *zp = VTOZ(vp);
2072         znode_phys_t    *pzp = zp->z_phys;
2073         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
2074         zilog_t         *zilog = zfsvfs->z_log;
2075         dmu_tx_t        *tx;
2076         vattr_t         oldva;
2077         uint_t          mask = vap->va_mask;
2078         uint_t          saved_mask;
2079         int             trim_mask = 0;
2080         uint64_t        new_mode;
2081         znode_t         *attrzp;
2082         int             need_policy = FALSE;
2083         int             err;
2084
2085         if (mask == 0)
2086                 return (0);
2087
2088         if (mask & AT_NOSET)
2089                 return (EINVAL);
2090
2091         if (mask & AT_SIZE && vp->v_type == VDIR)
2092                 return (EISDIR);
2093
2094         if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO)
2095                 return (EINVAL);
2096
2097         ZFS_ENTER(zfsvfs);
2098
2099 top:
2100         attrzp = NULL;
2101
2102         if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2103                 ZFS_EXIT(zfsvfs);
2104                 return (EROFS);
2105         }
2106
2107         /*
2108          * First validate permissions
2109          */
2110
2111         if (mask & AT_SIZE) {
2112                 err = zfs_zaccess(zp, ACE_WRITE_DATA, cr);
2113                 if (err) {
2114                         ZFS_EXIT(zfsvfs);
2115                         return (err);
2116                 }
2117                 /*
2118                  * XXX - Note, we are not providing any open
2119                  * mode flags here (like FNDELAY), so we may
2120                  * block if there are locks present... this
2121                  * should be addressed in openat().
2122                  */
2123                 do {
2124                         err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2125                         /* NB: we already did dmu_tx_wait() if necessary */
2126                 } while (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT);
2127                 if (err) {
2128                         ZFS_EXIT(zfsvfs);
2129                         return (err);
2130                 }
2131         }
2132
2133         if (mask & (AT_ATIME|AT_MTIME))
2134                 need_policy = zfs_zaccess_v4_perm(zp, ACE_WRITE_ATTRIBUTES, cr);
2135
2136         if (mask & (AT_UID|AT_GID)) {
2137                 int     idmask = (mask & (AT_UID|AT_GID));
2138                 int     take_owner;
2139                 int     take_group;
2140
2141                 /*
2142                  * NOTE: even if a new mode is being set,
2143                  * we may clear S_ISUID/S_ISGID bits.
2144                  */
2145
2146                 if (!(mask & AT_MODE))
2147                         vap->va_mode = pzp->zp_mode;
2148
2149                 /*
2150                  * Take ownership or chgrp to group we are a member of
2151                  */
2152
2153                 take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2154                 take_group = (mask & AT_GID) && groupmember(vap->va_gid, cr);
2155
2156                 /*
2157                  * If both AT_UID and AT_GID are set then take_owner and
2158                  * take_group must both be set in order to allow taking
2159                  * ownership.
2160                  *
2161                  * Otherwise, send the check through secpolicy_vnode_setattr()
2162                  *
2163                  */
2164
2165                 if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2166                     ((idmask == AT_UID) && take_owner) ||
2167                     ((idmask == AT_GID) && take_group)) {
2168                         if (zfs_zaccess_v4_perm(zp, ACE_WRITE_OWNER, cr) == 0) {
2169                                 /*
2170                                  * Remove setuid/setgid for non-privileged users
2171                                  */
2172                                 secpolicy_setid_clear(vap, cr);
2173                                 trim_mask = (mask & (AT_UID|AT_GID));
2174                         } else {
2175                                 need_policy =  TRUE;
2176                         }
2177                 } else {
2178                         need_policy =  TRUE;
2179                 }
2180         }
2181
2182         mutex_enter(&zp->z_lock);
2183         oldva.va_mode = pzp->zp_mode;
2184         oldva.va_uid = zp->z_phys->zp_uid;
2185         oldva.va_gid = zp->z_phys->zp_gid;
2186         mutex_exit(&zp->z_lock);
2187
2188         if (mask & AT_MODE) {
2189                 if (zfs_zaccess_v4_perm(zp, ACE_WRITE_ACL, cr) == 0) {
2190                         err = secpolicy_setid_setsticky_clear(vp, vap,
2191                             &oldva, cr);
2192                         if (err) {
2193                                 ZFS_EXIT(zfsvfs);
2194                                 return (err);
2195                         }
2196                         trim_mask |= AT_MODE;
2197                 } else {
2198                         need_policy = TRUE;
2199                 }
2200         }
2201
2202         if (need_policy) {
2203                 /*
2204                  * If trim_mask is set then take ownership
2205                  * has been granted or write_acl is present and user
2206                  * has the ability to modify mode.  In that case remove
2207                  * UID|GID and or MODE from mask so that
2208                  * secpolicy_vnode_setattr() doesn't revoke it.
2209                  */
2210
2211                 if (trim_mask) {
2212                         saved_mask = vap->va_mask;
2213                         vap->va_mask &= ~trim_mask;
2214
2215                 }
2216                 err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
2217                     (int (*)(void *, int, cred_t *))zfs_zaccess_rwx, zp);
2218                 if (err) {
2219                         ZFS_EXIT(zfsvfs);
2220                         return (err);
2221                 }
2222
2223                 if (trim_mask)
2224                         vap->va_mask |= saved_mask;
2225         }
2226
2227         /*
2228          * secpolicy_vnode_setattr, or take ownership may have
2229          * changed va_mask
2230          */
2231         mask = vap->va_mask;
2232
2233         tx = dmu_tx_create(zfsvfs->z_os);
2234         dmu_tx_hold_bonus(tx, zp->z_id);
2235
2236         if (mask & AT_MODE) {
2237                 uint64_t pmode = pzp->zp_mode;
2238
2239                 new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
2240
2241                 if (zp->z_phys->zp_acl.z_acl_extern_obj)
2242                         dmu_tx_hold_write(tx,
2243                             pzp->zp_acl.z_acl_extern_obj, 0, SPA_MAXBLOCKSIZE);
2244                 else
2245                         dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2246                             0, ZFS_ACL_SIZE(MAX_ACL_SIZE));
2247         }
2248
2249         if ((mask & (AT_UID | AT_GID)) && zp->z_phys->zp_xattr != 0) {
2250                 err = zfs_zget(zp->z_zfsvfs, zp->z_phys->zp_xattr, &attrzp);
2251                 if (err) {
2252                         dmu_tx_abort(tx);
2253                         ZFS_EXIT(zfsvfs);
2254                         return (err);
2255                 }
2256                 dmu_tx_hold_bonus(tx, attrzp->z_id);
2257         }
2258
2259         err = dmu_tx_assign(tx, zfsvfs->z_assign);
2260         if (err) {
2261                 if (attrzp)
2262                         VN_RELE(ZTOV(attrzp));
2263                 if (err == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2264                         dmu_tx_wait(tx);
2265                         dmu_tx_abort(tx);
2266                         goto top;
2267                 }
2268                 dmu_tx_abort(tx);
2269                 ZFS_EXIT(zfsvfs);
2270                 return (err);
2271         }
2272
2273         dmu_buf_will_dirty(zp->z_dbuf, tx);
2274
2275         /*
2276          * Set each attribute requested.
2277          * We group settings according to the locks they need to acquire.
2278          *
2279          * Note: you cannot set ctime directly, although it will be
2280          * updated as a side-effect of calling this function.
2281          */
2282
2283         mutex_enter(&zp->z_lock);
2284
2285         if (mask & AT_MODE) {
2286                 err = zfs_acl_chmod_setattr(zp, new_mode, tx);
2287                 ASSERT3U(err, ==, 0);
2288         }
2289
2290         if (attrzp)
2291                 mutex_enter(&attrzp->z_lock);
2292
2293         if (mask & AT_UID) {
2294                 zp->z_phys->zp_uid = (uint64_t)vap->va_uid;
2295                 if (attrzp) {
2296                         attrzp->z_phys->zp_uid = (uint64_t)vap->va_uid;
2297                 }
2298         }
2299
2300         if (mask & AT_GID) {
2301                 zp->z_phys->zp_gid = (uint64_t)vap->va_gid;
2302                 if (attrzp)
2303                         attrzp->z_phys->zp_gid = (uint64_t)vap->va_gid;
2304         }
2305
2306         if (attrzp)
2307                 mutex_exit(&attrzp->z_lock);
2308
2309         if (mask & AT_ATIME)
2310                 ZFS_TIME_ENCODE(&vap->va_atime, pzp->zp_atime);
2311
2312         if (mask & AT_MTIME)
2313                 ZFS_TIME_ENCODE(&vap->va_mtime, pzp->zp_mtime);
2314
2315         if (mask & AT_SIZE)
2316                 zfs_time_stamper_locked(zp, CONTENT_MODIFIED, tx);
2317         else if (mask != 0)
2318                 zfs_time_stamper_locked(zp, STATE_CHANGED, tx);
2319
2320         if (mask != 0)
2321                 zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask);
2322
2323         mutex_exit(&zp->z_lock);
2324
2325         if (attrzp)
2326                 VN_RELE(ZTOV(attrzp));
2327
2328         dmu_tx_commit(tx);
2329
2330         ZFS_EXIT(zfsvfs);
2331         return (err);
2332 }
2333
2334 typedef struct zfs_zlock {
2335         krwlock_t       *zl_rwlock;     /* lock we acquired */
2336         znode_t         *zl_znode;      /* znode we held */
2337         struct zfs_zlock *zl_next;      /* next in list */
2338 } zfs_zlock_t;
2339
2340 /*
2341  * Drop locks and release vnodes that were held by zfs_rename_lock().
2342  */
2343 static void
2344 zfs_rename_unlock(zfs_zlock_t **zlpp)
2345 {
2346         zfs_zlock_t *zl;
2347
2348         while ((zl = *zlpp) != NULL) {
2349                 if (zl->zl_znode != NULL)
2350                         VN_RELE(ZTOV(zl->zl_znode));
2351                 rw_exit(zl->zl_rwlock);
2352                 *zlpp = zl->zl_next;
2353                 kmem_free(zl, sizeof (*zl));
2354         }
2355 }
2356
2357 /*
2358  * Search back through the directory tree, using the ".." entries.
2359  * Lock each directory in the chain to prevent concurrent renames.
2360  * Fail any attempt to move a directory into one of its own descendants.
2361  * XXX - z_parent_lock can overlap with map or grow locks
2362  */
2363 static int
2364 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
2365 {
2366         zfs_zlock_t     *zl;
2367         znode_t         *zp = tdzp;
2368         uint64_t        rootid = zp->z_zfsvfs->z_root;
2369         uint64_t        *oidp = &zp->z_id;
2370         krwlock_t       *rwlp = &szp->z_parent_lock;
2371         krw_t           rw = RW_WRITER;
2372
2373         /*
2374          * First pass write-locks szp and compares to zp->z_id.
2375          * Later passes read-lock zp and compare to zp->z_parent.
2376          */
2377         do {
2378                 if (!rw_tryenter(rwlp, rw)) {
2379                         /*
2380                          * Another thread is renaming in this path.
2381                          * Note that if we are a WRITER, we don't have any
2382                          * parent_locks held yet.
2383                          */
2384                         if (rw == RW_READER && zp->z_id > szp->z_id) {
2385                                 /*
2386                                  * Drop our locks and restart
2387                                  */
2388                                 zfs_rename_unlock(&zl);
2389                                 *zlpp = NULL;
2390                                 zp = tdzp;
2391                                 oidp = &zp->z_id;
2392                                 rwlp = &szp->z_parent_lock;
2393                                 rw = RW_WRITER;
2394                                 continue;
2395                         } else {
2396                                 /*
2397                                  * Wait for other thread to drop its locks
2398                                  */
2399                                 rw_enter(rwlp, rw);
2400                         }
2401                 }
2402
2403                 zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
2404                 zl->zl_rwlock = rwlp;
2405                 zl->zl_znode = NULL;
2406                 zl->zl_next = *zlpp;
2407                 *zlpp = zl;
2408
2409                 if (*oidp == szp->z_id)         /* We're a descendant of szp */
2410                         return (EINVAL);
2411
2412                 if (*oidp == rootid)            /* We've hit the top */
2413                         return (0);
2414
2415                 if (rw == RW_READER) {          /* i.e. not the first pass */
2416                         int error = zfs_zget(zp->z_zfsvfs, *oidp, &zp);
2417                         if (error)
2418                                 return (error);
2419                         zl->zl_znode = zp;
2420                 }
2421                 oidp = &zp->z_phys->zp_parent;
2422                 rwlp = &zp->z_parent_lock;
2423                 rw = RW_READER;
2424
2425         } while (zp->z_id != sdzp->z_id);
2426
2427         return (0);
2428 }
2429
2430 /*
2431  * Move an entry from the provided source directory to the target
2432  * directory.  Change the entry name as indicated.
2433  *
2434  *      IN:     sdvp    - Source directory containing the "old entry".
2435  *              snm     - Old entry name.
2436  *              tdvp    - Target directory to contain the "new entry".
2437  *              tnm     - New entry name.
2438  *              cr      - credentials of caller.
2439  *
2440  *      RETURN: 0 if success
2441  *              error code if failure
2442  *
2443  * Timestamps:
2444  *      sdvp,tdvp - ctime|mtime updated
2445  */
2446 static int
2447 zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr)
2448 {
2449         znode_t         *tdzp, *szp, *tzp;
2450         znode_t         *sdzp = VTOZ(sdvp);
2451         zfsvfs_t        *zfsvfs = sdzp->z_zfsvfs;
2452         zilog_t         *zilog = zfsvfs->z_log;
2453         vnode_t         *realvp;
2454         zfs_dirlock_t   *sdl, *tdl;
2455         dmu_tx_t        *tx;
2456         zfs_zlock_t     *zl;
2457         int             cmp, serr, terr, error;
2458
2459         ZFS_ENTER(zfsvfs);
2460
2461         /*
2462          * Make sure we have the real vp for the target directory.
2463          */
2464         if (VOP_REALVP(tdvp, &realvp) == 0)
2465                 tdvp = realvp;
2466
2467         if (tdvp->v_vfsp != sdvp->v_vfsp) {
2468                 ZFS_EXIT(zfsvfs);
2469                 return (EXDEV);
2470         }
2471
2472         tdzp = VTOZ(tdvp);
2473 top:
2474         szp = NULL;
2475         tzp = NULL;
2476         zl = NULL;
2477
2478         /*
2479          * This is to prevent the creation of links into attribute space
2480          * by renaming a linked file into/outof an attribute directory.
2481          * See the comment in zfs_link() for why this is considered bad.
2482          */
2483         if ((tdzp->z_phys->zp_flags & ZFS_XATTR) !=
2484             (sdzp->z_phys->zp_flags & ZFS_XATTR)) {
2485                 ZFS_EXIT(zfsvfs);
2486                 return (EINVAL);
2487         }
2488
2489         /*
2490          * Lock source and target directory entries.  To prevent deadlock,
2491          * a lock ordering must be defined.  We lock the directory with
2492          * the smallest object id first, or if it's a tie, the one with
2493          * the lexically first name.
2494          */
2495         if (sdzp->z_id < tdzp->z_id) {
2496                 cmp = -1;
2497         } else if (sdzp->z_id > tdzp->z_id) {
2498                 cmp = 1;
2499         } else {
2500                 cmp = strcmp(snm, tnm);
2501                 if (cmp == 0) {
2502                         /*
2503                          * POSIX: "If the old argument and the new argument
2504                          * both refer to links to the same existing file,
2505                          * the rename() function shall return successfully
2506                          * and perform no other action."
2507                          */
2508                         ZFS_EXIT(zfsvfs);
2509                         return (0);
2510                 }
2511         }
2512         if (cmp < 0) {
2513                 serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp, ZEXISTS);
2514                 terr = zfs_dirent_lock(&tdl, tdzp, tnm, &tzp, 0);
2515         } else {
2516                 terr = zfs_dirent_lock(&tdl, tdzp, tnm, &tzp, 0);
2517                 serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp, ZEXISTS);
2518         }
2519
2520         if (serr) {
2521                 /*
2522                  * Source entry invalid or not there.
2523                  */
2524                 if (!terr) {
2525                         zfs_dirent_unlock(tdl);
2526                         if (tzp)
2527                                 VN_RELE(ZTOV(tzp));
2528                 }
2529                 if (strcmp(snm, ".") == 0 || strcmp(snm, "..") == 0)
2530                         serr = EINVAL;
2531                 ZFS_EXIT(zfsvfs);
2532                 return (serr);
2533         }
2534         if (terr) {
2535                 zfs_dirent_unlock(sdl);
2536                 VN_RELE(ZTOV(szp));
2537                 if (strcmp(tnm, "..") == 0)
2538                         terr = EINVAL;
2539                 ZFS_EXIT(zfsvfs);
2540                 return (terr);
2541         }
2542
2543         /*
2544          * Must have write access at the source to remove the old entry
2545          * and write access at the target to create the new entry.
2546          * Note that if target and source are the same, this can be
2547          * done in a single check.
2548          */
2549
2550         if (error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr))
2551                 goto out;
2552
2553         if (ZTOV(szp)->v_type == VDIR) {
2554                 /*
2555                  * Check to make sure rename is valid.
2556                  * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
2557                  */
2558                 if (error = zfs_rename_lock(szp, tdzp, sdzp, &zl))
2559                         goto out;
2560         }
2561
2562         /*
2563          * Does target exist?
2564          */
2565         if (tzp) {
2566                 /*
2567                  * Source and target must be the same type.
2568                  */
2569                 if (ZTOV(szp)->v_type == VDIR) {
2570                         if (ZTOV(tzp)->v_type != VDIR) {
2571                                 error = ENOTDIR;
2572                                 goto out;
2573                         }
2574                 } else {
2575                         if (ZTOV(tzp)->v_type == VDIR) {
2576                                 error = EISDIR;
2577                                 goto out;
2578                         }
2579                 }
2580                 /*
2581                  * POSIX dictates that when the source and target
2582                  * entries refer to the same file object, rename
2583                  * must do nothing and exit without error.
2584                  */
2585                 if (szp->z_id == tzp->z_id) {
2586                         error = 0;
2587                         goto out;
2588                 }
2589         }
2590
2591         vnevent_rename_src(ZTOV(szp));
2592         if (tzp)
2593                 vnevent_rename_dest(ZTOV(tzp));
2594
2595         tx = dmu_tx_create(zfsvfs->z_os);
2596         dmu_tx_hold_bonus(tx, szp->z_id);       /* nlink changes */
2597         dmu_tx_hold_bonus(tx, sdzp->z_id);      /* nlink changes */
2598         dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
2599         dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
2600         if (sdzp != tdzp)
2601                 dmu_tx_hold_bonus(tx, tdzp->z_id);      /* nlink changes */
2602         if (tzp)
2603                 dmu_tx_hold_bonus(tx, tzp->z_id);       /* parent changes */
2604         dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
2605         error = dmu_tx_assign(tx, zfsvfs->z_assign);
2606         if (error) {
2607                 if (zl != NULL)
2608                         zfs_rename_unlock(&zl);
2609                 zfs_dirent_unlock(sdl);
2610                 zfs_dirent_unlock(tdl);
2611                 VN_RELE(ZTOV(szp));
2612                 if (tzp)
2613                         VN_RELE(ZTOV(tzp));
2614                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2615                         dmu_tx_wait(tx);
2616                         dmu_tx_abort(tx);
2617                         goto top;
2618                 }
2619                 dmu_tx_abort(tx);
2620                 ZFS_EXIT(zfsvfs);
2621                 return (error);
2622         }
2623
2624         if (tzp)        /* Attempt to remove the existing target */
2625                 error = zfs_link_destroy(tdl, tzp, tx, 0, NULL);
2626
2627         if (error == 0) {
2628                 error = zfs_link_create(tdl, szp, tx, ZRENAMING);
2629                 if (error == 0) {
2630                         error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
2631                         ASSERT(error == 0);
2632                         zfs_log_rename(zilog, tx, TX_RENAME, sdzp,
2633                             sdl->dl_name, tdzp, tdl->dl_name, szp);
2634                 }
2635 #ifdef FREEBSD_NAMECACHE
2636                 if (error == 0) {
2637                         cache_purge(sdvp);
2638                         cache_purge(tdvp);
2639                 }
2640 #endif
2641         }
2642
2643         dmu_tx_commit(tx);
2644 out:
2645         if (zl != NULL)
2646                 zfs_rename_unlock(&zl);
2647
2648         zfs_dirent_unlock(sdl);
2649         zfs_dirent_unlock(tdl);
2650
2651         VN_RELE(ZTOV(szp));
2652         if (tzp)
2653                 VN_RELE(ZTOV(tzp));
2654
2655         ZFS_EXIT(zfsvfs);
2656
2657         return (error);
2658 }
2659
2660 /*
2661  * Insert the indicated symbolic reference entry into the directory.
2662  *
2663  *      IN:     dvp     - Directory to contain new symbolic link.
2664  *              link    - Name for new symlink entry.
2665  *              vap     - Attributes of new entry.
2666  *              target  - Target path of new symlink.
2667  *              cr      - credentials of caller.
2668  *
2669  *      RETURN: 0 if success
2670  *              error code if failure
2671  *
2672  * Timestamps:
2673  *      dvp - ctime|mtime updated
2674  */
2675 static int
2676 zfs_symlink(vnode_t *dvp, vnode_t **vpp, char *name, vattr_t *vap, char *link, cred_t *cr, kthread_t *td)
2677 {
2678         znode_t         *zp, *dzp = VTOZ(dvp);
2679         zfs_dirlock_t   *dl;
2680         dmu_tx_t        *tx;
2681         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
2682         zilog_t         *zilog = zfsvfs->z_log;
2683         uint64_t        zoid;
2684         int             len = strlen(link);
2685         int             error;
2686
2687         ASSERT(vap->va_type == VLNK);
2688
2689         ZFS_ENTER(zfsvfs);
2690 top:
2691         if (error = zfs_zaccess(dzp, ACE_ADD_FILE, cr)) {
2692                 ZFS_EXIT(zfsvfs);
2693                 return (error);
2694         }
2695
2696         if (len > MAXPATHLEN) {
2697                 ZFS_EXIT(zfsvfs);
2698                 return (ENAMETOOLONG);
2699         }
2700
2701         /*
2702          * Attempt to lock directory; fail if entry already exists.
2703          */
2704         if (error = zfs_dirent_lock(&dl, dzp, name, &zp, ZNEW)) {
2705                 ZFS_EXIT(zfsvfs);
2706                 return (error);
2707         }
2708
2709         tx = dmu_tx_create(zfsvfs->z_os);
2710         dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
2711         dmu_tx_hold_bonus(tx, dzp->z_id);
2712         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
2713         if (dzp->z_phys->zp_flags & ZFS_INHERIT_ACE)
2714                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, SPA_MAXBLOCKSIZE);
2715         error = dmu_tx_assign(tx, zfsvfs->z_assign);
2716         if (error) {
2717                 zfs_dirent_unlock(dl);
2718                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2719                         dmu_tx_wait(tx);
2720                         dmu_tx_abort(tx);
2721                         goto top;
2722                 }
2723                 dmu_tx_abort(tx);
2724                 ZFS_EXIT(zfsvfs);
2725                 return (error);
2726         }
2727
2728         dmu_buf_will_dirty(dzp->z_dbuf, tx);
2729
2730         /*
2731          * Create a new object for the symlink.
2732          * Put the link content into bonus buffer if it will fit;
2733          * otherwise, store it just like any other file data.
2734          */
2735         zoid = 0;
2736         if (sizeof (znode_phys_t) + len <= dmu_bonus_max()) {
2737                 zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, len);
2738                 if (len != 0)
2739                         bcopy(link, zp->z_phys + 1, len);
2740         } else {
2741                 dmu_buf_t *dbp;
2742
2743                 zfs_mknode(dzp, vap, &zoid, tx, cr, 0, &zp, 0);
2744
2745                 /*
2746                  * Nothing can access the znode yet so no locking needed
2747                  * for growing the znode's blocksize.
2748                  */
2749                 zfs_grow_blocksize(zp, len, tx);
2750
2751                 VERIFY(0 == dmu_buf_hold(zfsvfs->z_os, zoid, 0, FTAG, &dbp));
2752                 dmu_buf_will_dirty(dbp, tx);
2753
2754                 ASSERT3U(len, <=, dbp->db_size);
2755                 bcopy(link, dbp->db_data, len);
2756                 dmu_buf_rele(dbp, FTAG);
2757         }
2758         zp->z_phys->zp_size = len;
2759
2760         /*
2761          * Insert the new object into the directory.
2762          */
2763         (void) zfs_link_create(dl, zp, tx, ZNEW);
2764 out:
2765         if (error == 0) {
2766                 zfs_log_symlink(zilog, tx, TX_SYMLINK, dzp, zp, name, link);
2767                 *vpp = ZTOV(zp);
2768         }
2769
2770         dmu_tx_commit(tx);
2771
2772         zfs_dirent_unlock(dl);
2773
2774         ZFS_EXIT(zfsvfs);
2775         return (error);
2776 }
2777
2778 /*
2779  * Return, in the buffer contained in the provided uio structure,
2780  * the symbolic path referred to by vp.
2781  *
2782  *      IN:     vp      - vnode of symbolic link.
2783  *              uoip    - structure to contain the link path.
2784  *              cr      - credentials of caller.
2785  *
2786  *      OUT:    uio     - structure to contain the link path.
2787  *
2788  *      RETURN: 0 if success
2789  *              error code if failure
2790  *
2791  * Timestamps:
2792  *      vp - atime updated
2793  */
2794 /* ARGSUSED */
2795 static int
2796 zfs_readlink(vnode_t *vp, uio_t *uio, cred_t *cr)
2797 {
2798         znode_t         *zp = VTOZ(vp);
2799         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
2800         size_t          bufsz;
2801         int             error;
2802
2803         ZFS_ENTER(zfsvfs);
2804
2805         bufsz = (size_t)zp->z_phys->zp_size;
2806         if (bufsz + sizeof (znode_phys_t) <= zp->z_dbuf->db_size) {
2807                 error = uiomove(zp->z_phys + 1,
2808                     MIN((size_t)bufsz, uio->uio_resid), UIO_READ, uio);
2809         } else {
2810                 dmu_buf_t *dbp;
2811                 error = dmu_buf_hold(zfsvfs->z_os, zp->z_id, 0, FTAG, &dbp);
2812                 if (error) {
2813                         ZFS_EXIT(zfsvfs);
2814                         return (error);
2815                 }
2816                 error = uiomove(dbp->db_data,
2817                     MIN((size_t)bufsz, uio->uio_resid), UIO_READ, uio);
2818                 dmu_buf_rele(dbp, FTAG);
2819         }
2820
2821         ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2822         ZFS_EXIT(zfsvfs);
2823         return (error);
2824 }
2825
2826 /*
2827  * Insert a new entry into directory tdvp referencing svp.
2828  *
2829  *      IN:     tdvp    - Directory to contain new entry.
2830  *              svp     - vnode of new entry.
2831  *              name    - name of new entry.
2832  *              cr      - credentials of caller.
2833  *
2834  *      RETURN: 0 if success
2835  *              error code if failure
2836  *
2837  * Timestamps:
2838  *      tdvp - ctime|mtime updated
2839  *       svp - ctime updated
2840  */
2841 /* ARGSUSED */
2842 static int
2843 zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr)
2844 {
2845         znode_t         *dzp = VTOZ(tdvp);
2846         znode_t         *tzp, *szp;
2847         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
2848         zilog_t         *zilog = zfsvfs->z_log;
2849         zfs_dirlock_t   *dl;
2850         dmu_tx_t        *tx;
2851         vnode_t         *realvp;
2852         int             error;
2853
2854         ASSERT(tdvp->v_type == VDIR);
2855
2856         ZFS_ENTER(zfsvfs);
2857
2858         if (VOP_REALVP(svp, &realvp) == 0)
2859                 svp = realvp;
2860
2861         if (svp->v_vfsp != tdvp->v_vfsp) {
2862                 ZFS_EXIT(zfsvfs);
2863                 return (EXDEV);
2864         }
2865
2866         szp = VTOZ(svp);
2867 top:
2868         /*
2869          * We do not support links between attributes and non-attributes
2870          * because of the potential security risk of creating links
2871          * into "normal" file space in order to circumvent restrictions
2872          * imposed in attribute space.
2873          */
2874         if ((szp->z_phys->zp_flags & ZFS_XATTR) !=
2875             (dzp->z_phys->zp_flags & ZFS_XATTR)) {
2876                 ZFS_EXIT(zfsvfs);
2877                 return (EINVAL);
2878         }
2879
2880         /*
2881          * POSIX dictates that we return EPERM here.
2882          * Better choices include ENOTSUP or EISDIR.
2883          */
2884         if (svp->v_type == VDIR) {
2885                 ZFS_EXIT(zfsvfs);
2886                 return (EPERM);
2887         }
2888
2889         if ((uid_t)szp->z_phys->zp_uid != crgetuid(cr) &&
2890             secpolicy_basic_link(cr) != 0) {
2891                 ZFS_EXIT(zfsvfs);
2892                 return (EPERM);
2893         }
2894
2895         if (error = zfs_zaccess(dzp, ACE_ADD_FILE, cr)) {
2896                 ZFS_EXIT(zfsvfs);
2897                 return (error);
2898         }
2899
2900         /*
2901          * Attempt to lock directory; fail if entry already exists.
2902          */
2903         if (error = zfs_dirent_lock(&dl, dzp, name, &tzp, ZNEW)) {
2904                 ZFS_EXIT(zfsvfs);
2905                 return (error);
2906         }
2907
2908         tx = dmu_tx_create(zfsvfs->z_os);
2909         dmu_tx_hold_bonus(tx, szp->z_id);
2910         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
2911         error = dmu_tx_assign(tx, zfsvfs->z_assign);
2912         if (error) {
2913                 zfs_dirent_unlock(dl);
2914                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
2915                         dmu_tx_wait(tx);
2916                         dmu_tx_abort(tx);
2917                         goto top;
2918                 }
2919                 dmu_tx_abort(tx);
2920                 ZFS_EXIT(zfsvfs);
2921                 return (error);
2922         }
2923
2924         error = zfs_link_create(dl, szp, tx, 0);
2925
2926         if (error == 0)
2927                 zfs_log_link(zilog, tx, TX_LINK, dzp, szp, name);
2928
2929         dmu_tx_commit(tx);
2930
2931         zfs_dirent_unlock(dl);
2932
2933         ZFS_EXIT(zfsvfs);
2934         return (error);
2935 }
2936
2937 void
2938 zfs_inactive(vnode_t *vp, cred_t *cr)
2939 {
2940         znode_t *zp = VTOZ(vp);
2941         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2942         int error;
2943
2944         rw_enter(&zfsvfs->z_um_lock, RW_READER);
2945         if (zfsvfs->z_unmounted2) {
2946                 ASSERT(zp->z_dbuf_held == 0);
2947
2948                 mutex_enter(&zp->z_lock);
2949                 VI_LOCK(vp);
2950                 vp->v_count = 0; /* count arrives as 1 */
2951                 VI_UNLOCK(vp);
2952                 if (zp->z_dbuf == NULL) {
2953                         mutex_exit(&zp->z_lock);
2954                         zfs_znode_free(zp);
2955                 } else {
2956                         mutex_exit(&zp->z_lock);
2957                 }
2958                 rw_exit(&zfsvfs->z_um_lock);
2959                 VFS_RELE(zfsvfs->z_vfs);
2960                 return;
2961         }
2962
2963         if (zp->z_atime_dirty && zp->z_unlinked == 0) {
2964                 dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
2965
2966                 dmu_tx_hold_bonus(tx, zp->z_id);
2967                 error = dmu_tx_assign(tx, TXG_WAIT);
2968                 if (error) {
2969                         dmu_tx_abort(tx);
2970                 } else {
2971                         dmu_buf_will_dirty(zp->z_dbuf, tx);
2972                         mutex_enter(&zp->z_lock);
2973                         zp->z_atime_dirty = 0;
2974                         mutex_exit(&zp->z_lock);
2975                         dmu_tx_commit(tx);
2976                 }
2977         }
2978
2979         zfs_zinactive(zp);
2980         rw_exit(&zfsvfs->z_um_lock);
2981 }
2982
2983 CTASSERT(sizeof(struct zfid_short) <= sizeof(struct fid));
2984 CTASSERT(sizeof(struct zfid_long) <= sizeof(struct fid));
2985
2986 static int
2987 zfs_fid(vnode_t *vp, fid_t *fidp)
2988 {
2989         znode_t         *zp = VTOZ(vp);
2990         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
2991         uint32_t        gen = (uint32_t)zp->z_phys->zp_gen;
2992         uint64_t        object = zp->z_id;
2993         zfid_short_t    *zfid;
2994         int             size, i;
2995
2996         ZFS_ENTER(zfsvfs);
2997
2998         size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
2999         fidp->fid_len = size;
3000
3001         zfid = (zfid_short_t *)fidp;
3002
3003         zfid->zf_len = size;
3004
3005         for (i = 0; i < sizeof (zfid->zf_object); i++)
3006                 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
3007
3008         /* Must have a non-zero generation number to distinguish from .zfs */
3009         if (gen == 0)
3010                 gen = 1;
3011         for (i = 0; i < sizeof (zfid->zf_gen); i++)
3012                 zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
3013
3014         if (size == LONG_FID_LEN) {
3015                 uint64_t        objsetid = dmu_objset_id(zfsvfs->z_os);
3016                 zfid_long_t     *zlfid;
3017
3018                 zlfid = (zfid_long_t *)fidp;
3019
3020                 for (i = 0; i < sizeof (zlfid->zf_setid); i++)
3021                         zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
3022
3023                 /* XXX - this should be the generation number for the objset */
3024                 for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
3025                         zlfid->zf_setgen[i] = 0;
3026         }
3027
3028         ZFS_EXIT(zfsvfs);
3029         return (0);
3030 }
3031
3032 static int
3033 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr)
3034 {
3035         znode_t         *zp, *xzp;
3036         zfsvfs_t        *zfsvfs;
3037         zfs_dirlock_t   *dl;
3038         int             error;
3039
3040         switch (cmd) {
3041         case _PC_LINK_MAX:
3042                 *valp = INT_MAX;
3043                 return (0);
3044
3045         case _PC_FILESIZEBITS:
3046                 *valp = 64;
3047                 return (0);
3048
3049 #if 0
3050         case _PC_XATTR_EXISTS:
3051                 zp = VTOZ(vp);
3052                 zfsvfs = zp->z_zfsvfs;
3053                 ZFS_ENTER(zfsvfs);
3054                 *valp = 0;
3055                 error = zfs_dirent_lock(&dl, zp, "", &xzp,
3056                     ZXATTR | ZEXISTS | ZSHARED);
3057                 if (error == 0) {
3058                         zfs_dirent_unlock(dl);
3059                         if (!zfs_dirempty(xzp))
3060                                 *valp = 1;
3061                         VN_RELE(ZTOV(xzp));
3062                 } else if (error == ENOENT) {
3063                         /*
3064                          * If there aren't extended attributes, it's the
3065                          * same as having zero of them.
3066                          */
3067                         error = 0;
3068                 }
3069                 ZFS_EXIT(zfsvfs);
3070                 return (error);
3071 #endif
3072
3073         case _PC_ACL_EXTENDED:
3074                 *valp = 0;      /* TODO */
3075                 return (0);
3076
3077         case _PC_MIN_HOLE_SIZE:
3078                 *valp = (int)SPA_MINBLOCKSIZE;
3079                 return (0);
3080
3081         default:
3082                 return (EOPNOTSUPP);
3083         }
3084 }
3085
3086 #ifdef TODO
3087 /*ARGSUSED*/
3088 static int
3089 zfs_getsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr)
3090 {
3091         znode_t *zp = VTOZ(vp);
3092         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3093         int error;
3094
3095         ZFS_ENTER(zfsvfs);
3096         error = zfs_getacl(zp, vsecp, cr);
3097         ZFS_EXIT(zfsvfs);
3098
3099         return (error);
3100 }
3101 #endif  /* TODO */
3102
3103 #ifdef TODO
3104 /*ARGSUSED*/
3105 static int
3106 zfs_setsecattr(vnode_t *vp, vsecattr_t *vsecp, int flag, cred_t *cr)
3107 {
3108         znode_t *zp = VTOZ(vp);
3109         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
3110         int error;
3111
3112         ZFS_ENTER(zfsvfs);
3113         error = zfs_setacl(zp, vsecp, cr);
3114         ZFS_EXIT(zfsvfs);
3115         return (error);
3116 }
3117 #endif  /* TODO */
3118
3119 static int
3120 zfs_freebsd_open(ap)
3121         struct vop_open_args /* {
3122                 struct vnode *a_vp;
3123                 int a_mode;
3124                 struct ucred *a_cred;
3125                 struct thread *a_td;
3126         } */ *ap;
3127 {
3128         vnode_t *vp = ap->a_vp;
3129         znode_t *zp = VTOZ(vp);
3130         int error;
3131
3132         error = zfs_open(&vp, ap->a_mode, ap->a_cred);
3133         if (error == 0)
3134                 vnode_create_vobject(vp, zp->z_phys->zp_size, ap->a_td);
3135         return (error);
3136 }
3137
3138 static int
3139 zfs_freebsd_close(ap)
3140         struct vop_close_args /* {
3141                 struct vnode *a_vp;
3142                 int  a_fflag;
3143                 struct ucred *a_cred;
3144                 struct thread *a_td;
3145         } */ *ap;
3146 {
3147
3148         return (zfs_close(ap->a_vp, ap->a_fflag, 0, 0, ap->a_cred));
3149 }
3150
3151 static int
3152 zfs_freebsd_ioctl(ap)
3153         struct vop_ioctl_args /* {
3154                 struct vnode *a_vp;
3155                 u_long a_command;
3156                 caddr_t a_data;
3157                 int a_fflag;
3158                 struct ucred *cred;
3159                 struct thread *td;
3160         } */ *ap;
3161 {
3162
3163         return (zfs_ioctl(ap->a_vp, ap->a_command, (intptr_t)ap->a_data,
3164             ap->a_fflag, ap->a_cred, NULL));
3165 }
3166
3167 static int
3168 zfs_freebsd_read(ap)
3169         struct vop_read_args /* {
3170                 struct vnode *a_vp;
3171                 struct uio *a_uio;
3172                 int a_ioflag;
3173                 struct ucred *a_cred;
3174         } */ *ap;
3175 {
3176
3177         return (zfs_read(ap->a_vp, ap->a_uio, ap->a_ioflag, ap->a_cred, NULL));
3178 }
3179
3180 static int
3181 zfs_freebsd_write(ap)
3182         struct vop_write_args /* {
3183                 struct vnode *a_vp;
3184                 struct uio *a_uio;
3185                 int a_ioflag;
3186                 struct ucred *a_cred;
3187         } */ *ap;
3188 {
3189
3190         return (zfs_write(ap->a_vp, ap->a_uio, ap->a_ioflag, ap->a_cred, NULL));
3191 }
3192
3193 static int
3194 zfs_freebsd_access(ap)
3195         struct vop_access_args /* {
3196                 struct vnode *a_vp;
3197                 int  a_mode;
3198                 struct ucred *a_cred;
3199                 struct thread *a_td;
3200         } */ *ap;
3201 {
3202
3203         return (zfs_access(ap->a_vp, ap->a_mode, 0, ap->a_cred));
3204 }
3205
3206 static int
3207 zfs_freebsd_lookup(ap)
3208         struct vop_lookup_args /* {
3209                 struct vnode *a_dvp;
3210                 struct vnode **a_vpp;
3211                 struct componentname *a_cnp;
3212         } */ *ap;
3213 {
3214         struct componentname *cnp = ap->a_cnp;
3215         char nm[NAME_MAX + 1];
3216
3217         ASSERT(cnp->cn_namelen < sizeof(nm));
3218         strlcpy(nm, cnp->cn_nameptr, MIN(cnp->cn_namelen + 1, sizeof(nm)));
3219
3220         return (zfs_lookup(ap->a_dvp, nm, ap->a_vpp, cnp, cnp->cn_nameiop,
3221             cnp->cn_cred, cnp->cn_thread));
3222 }
3223
3224 static int
3225 zfs_freebsd_create(ap)
3226         struct vop_create_args /* {
3227                 struct vnode *a_dvp;
3228                 struct vnode **a_vpp;
3229                 struct componentname *a_cnp;
3230                 struct vattr *a_vap;
3231         } */ *ap;
3232 {
3233         struct componentname *cnp = ap->a_cnp;
3234         vattr_t *vap = ap->a_vap;
3235         int mode;
3236
3237         ASSERT(cnp->cn_flags & SAVENAME);
3238
3239         vattr_init_mask(vap);
3240         mode = vap->va_mode & ALLPERMS;
3241
3242         return (zfs_create(ap->a_dvp, cnp->cn_nameptr, vap, !EXCL, mode,
3243             ap->a_vpp, cnp->cn_cred, cnp->cn_thread));
3244 }
3245
3246 static int
3247 zfs_freebsd_remove(ap)
3248         struct vop_remove_args /* {
3249                 struct vnode *a_dvp;
3250                 struct vnode *a_vp;
3251                 struct componentname *a_cnp;
3252         } */ *ap;
3253 {
3254
3255         ASSERT(ap->a_cnp->cn_flags & SAVENAME);
3256
3257         return (zfs_remove(ap->a_dvp, ap->a_cnp->cn_nameptr,
3258             ap->a_cnp->cn_cred));
3259 }
3260
3261 static int
3262 zfs_freebsd_mkdir(ap)
3263         struct vop_mkdir_args /* {
3264                 struct vnode *a_dvp;
3265                 struct vnode **a_vpp;
3266                 struct componentname *a_cnp;
3267                 struct vattr *a_vap;
3268         } */ *ap;
3269 {
3270         vattr_t *vap = ap->a_vap;
3271
3272         ASSERT(ap->a_cnp->cn_flags & SAVENAME);
3273
3274         vattr_init_mask(vap);
3275
3276         return (zfs_mkdir(ap->a_dvp, ap->a_cnp->cn_nameptr, vap, ap->a_vpp,
3277             ap->a_cnp->cn_cred));
3278 }
3279
3280 static int
3281 zfs_freebsd_rmdir(ap)
3282         struct vop_rmdir_args /* {
3283                 struct vnode *a_dvp;
3284                 struct vnode *a_vp;
3285                 struct componentname *a_cnp;
3286         } */ *ap;
3287 {
3288         struct componentname *cnp = ap->a_cnp;
3289
3290         ASSERT(cnp->cn_flags & SAVENAME);
3291
3292         return (zfs_rmdir(ap->a_dvp, cnp->cn_nameptr, NULL, cnp->cn_cred));
3293 }
3294
3295 static int
3296 zfs_freebsd_readdir(ap)
3297         struct vop_readdir_args /* {
3298                 struct vnode *a_vp;
3299                 struct uio *a_uio;
3300                 struct ucred *a_cred;
3301                 int *a_eofflag;
3302                 int *a_ncookies;
3303                 u_long **a_cookies;
3304         } */ *ap;
3305 {
3306
3307         return (zfs_readdir(ap->a_vp, ap->a_uio, ap->a_cred, ap->a_eofflag,
3308             ap->a_ncookies, ap->a_cookies));
3309 }
3310
3311 static int
3312 zfs_freebsd_fsync(ap)
3313         struct vop_fsync_args /* {
3314                 struct vnode *a_vp;
3315                 int a_waitfor;
3316                 struct thread *a_td;
3317         } */ *ap;
3318 {
3319
3320         vop_stdfsync(ap);
3321         return (zfs_fsync(ap->a_vp, 0, ap->a_td->td_ucred));
3322 }
3323
3324 static int
3325 zfs_freebsd_getattr(ap)
3326         struct vop_getattr_args /* {
3327                 struct vnode *a_vp;
3328                 struct vattr *a_vap;
3329                 struct ucred *a_cred;
3330                 struct thread *a_td;
3331         } */ *ap;
3332 {
3333
3334         return (zfs_getattr(ap->a_vp, ap->a_vap, 0, ap->a_cred));
3335 }
3336
3337 static int
3338 zfs_freebsd_setattr(ap)
3339         struct vop_setattr_args /* {
3340                 struct vnode *a_vp;
3341                 struct vattr *a_vap;
3342                 struct ucred *a_cred;
3343                 struct thread *a_td;
3344         } */ *ap;
3345 {
3346         vattr_t *vap = ap->a_vap;
3347
3348         /* No support for FreeBSD's chflags(2). */
3349         if (vap->va_flags != VNOVAL)
3350                 return (EOPNOTSUPP);
3351
3352         vattr_init_mask(vap);
3353         vap->va_mask &= ~AT_NOSET;
3354
3355         return (zfs_setattr(ap->a_vp, vap, 0, ap->a_cred, NULL));
3356 }
3357
3358 static int
3359 zfs_freebsd_rename(ap)
3360         struct vop_rename_args  /* {
3361                 struct vnode *a_fdvp;
3362                 struct vnode *a_fvp;
3363                 struct componentname *a_fcnp;
3364                 struct vnode *a_tdvp;
3365                 struct vnode *a_tvp;
3366                 struct componentname *a_tcnp;
3367         } */ *ap;
3368 {
3369         vnode_t *fdvp = ap->a_fdvp;
3370         vnode_t *fvp = ap->a_fvp;
3371         vnode_t *tdvp = ap->a_tdvp;
3372         vnode_t *tvp = ap->a_tvp;
3373         int error;
3374
3375         ASSERT(ap->a_fcnp->cn_flags & SAVENAME);
3376         ASSERT(ap->a_tcnp->cn_flags & SAVENAME);
3377
3378         error = zfs_rename(fdvp, ap->a_fcnp->cn_nameptr, tdvp,
3379             ap->a_tcnp->cn_nameptr, ap->a_fcnp->cn_cred);
3380
3381         if (tdvp == tvp)
3382                 VN_RELE(tdvp);
3383         else
3384                 VN_URELE(tdvp);
3385         if (tvp)
3386                 VN_URELE(tvp);
3387         VN_RELE(fdvp);
3388         VN_RELE(fvp);
3389
3390         return (error);
3391 }
3392
3393 static int
3394 zfs_freebsd_symlink(ap)
3395         struct vop_symlink_args /* {
3396                 struct vnode *a_dvp;
3397                 struct vnode **a_vpp;
3398                 struct componentname *a_cnp;
3399                 struct vattr *a_vap;
3400                 char *a_target;
3401         } */ *ap;
3402 {
3403         struct componentname *cnp = ap->a_cnp;
3404         vattr_t *vap = ap->a_vap;
3405
3406         ASSERT(cnp->cn_flags & SAVENAME);
3407
3408         vap->va_type = VLNK;    /* FreeBSD: Syscall only sets va_mode. */
3409         vattr_init_mask(vap);
3410
3411         return (zfs_symlink(ap->a_dvp, ap->a_vpp, cnp->cn_nameptr, vap,
3412             ap->a_target, cnp->cn_cred, cnp->cn_thread));
3413 }
3414
3415 static int
3416 zfs_freebsd_readlink(ap)
3417         struct vop_readlink_args /* {
3418                 struct vnode *a_vp;
3419                 struct uio *a_uio;
3420                 struct ucred *a_cred;
3421         } */ *ap;
3422 {
3423
3424         return (zfs_readlink(ap->a_vp, ap->a_uio, ap->a_cred));
3425 }
3426
3427 static int
3428 zfs_freebsd_link(ap)
3429         struct vop_link_args /* {
3430                 struct vnode *a_tdvp;
3431                 struct vnode *a_vp;
3432                 struct componentname *a_cnp;
3433         } */ *ap;
3434 {
3435         struct componentname *cnp = ap->a_cnp;
3436
3437         ASSERT(cnp->cn_flags & SAVENAME);
3438
3439         return (zfs_link(ap->a_tdvp, ap->a_vp, cnp->cn_nameptr, cnp->cn_cred));
3440 }
3441
3442 static int
3443 zfs_freebsd_inactive(ap)
3444         struct vop_inactive_args /* {
3445                 struct vnode *a_vp;
3446                 struct thread *a_td;
3447         } */ *ap;
3448 {
3449         vnode_t *vp = ap->a_vp;
3450
3451         zfs_inactive(vp, ap->a_td->td_ucred);
3452         return (0);
3453 }
3454
3455 static int
3456 zfs_freebsd_reclaim(ap)
3457         struct vop_reclaim_args /* {
3458                 struct vnode *a_vp;
3459                 struct thread *a_td;
3460         } */ *ap;
3461 {
3462         vnode_t *vp = ap->a_vp;
3463         znode_t *zp = VTOZ(vp);
3464         zfsvfs_t *zfsvfs;
3465         int rele = 1;
3466
3467         ASSERT(zp != NULL);
3468
3469         /*
3470          * Destroy the vm object and flush associated pages.
3471          */
3472         vnode_destroy_vobject(vp);
3473
3474         mutex_enter(&zp->z_lock);
3475         ASSERT(zp->z_phys);
3476         ASSERT(zp->z_dbuf_held);
3477         zfsvfs = zp->z_zfsvfs;
3478         if (!zp->z_unlinked) {
3479                 zp->z_dbuf_held = 0;
3480                 ZTOV(zp) = NULL;
3481                 mutex_exit(&zp->z_lock);
3482                 dmu_buf_rele(zp->z_dbuf, NULL);
3483         } else {
3484                 mutex_exit(&zp->z_lock);
3485         }
3486         VI_LOCK(vp);
3487         if (vp->v_count > 0)
3488                 rele = 0;
3489         vp->v_data = NULL;
3490         ASSERT(vp->v_holdcnt >= 1);
3491         VI_UNLOCK(vp);
3492         if (!zp->z_unlinked && rele)
3493                 VFS_RELE(zfsvfs->z_vfs);
3494         return (0);
3495 }
3496
3497 static int
3498 zfs_freebsd_fid(ap)
3499         struct vop_fid_args /* {
3500                 struct vnode *a_vp;
3501                 struct fid *a_fid;
3502         } */ *ap;
3503 {
3504
3505         return (zfs_fid(ap->a_vp, (void *)ap->a_fid));
3506 }
3507
3508 static int
3509 zfs_freebsd_pathconf(ap)
3510         struct vop_pathconf_args /* {
3511                 struct vnode *a_vp;
3512                 int a_name;
3513                 register_t *a_retval;
3514         } */ *ap;
3515 {
3516         ulong_t val;
3517         int error;
3518
3519         error = zfs_pathconf(ap->a_vp, ap->a_name, &val, curthread->td_ucred);
3520         if (error == 0)
3521                 *ap->a_retval = val;
3522         else if (error == EOPNOTSUPP)
3523                 error = vop_stdpathconf(ap);
3524         return (error);
3525 }
3526
3527 struct vop_vector zfs_vnodeops;
3528 struct vop_vector zfs_fifoops;
3529
3530 struct vop_vector zfs_vnodeops = {
3531         .vop_default =  &default_vnodeops,
3532         .vop_inactive = zfs_freebsd_inactive,
3533         .vop_reclaim =  zfs_freebsd_reclaim,
3534         .vop_access =   zfs_freebsd_access,
3535 #ifdef FREEBSD_NAMECACHE
3536         .vop_lookup =   vfs_cache_lookup,
3537         .vop_cachedlookup = zfs_freebsd_lookup,
3538 #else
3539         .vop_lookup =   zfs_freebsd_lookup,
3540 #endif
3541         .vop_getattr =  zfs_freebsd_getattr,
3542         .vop_setattr =  zfs_freebsd_setattr,
3543         .vop_create =   zfs_freebsd_create,
3544         .vop_mknod =    zfs_freebsd_create,
3545         .vop_mkdir =    zfs_freebsd_mkdir,
3546         .vop_readdir =  zfs_freebsd_readdir,
3547         .vop_fsync =    zfs_freebsd_fsync,
3548         .vop_open =     zfs_freebsd_open,
3549         .vop_close =    zfs_freebsd_close,
3550         .vop_rmdir =    zfs_freebsd_rmdir,
3551         .vop_ioctl =    zfs_freebsd_ioctl,
3552         .vop_link =     zfs_freebsd_link,
3553         .vop_symlink =  zfs_freebsd_symlink,
3554         .vop_readlink = zfs_freebsd_readlink,
3555         .vop_read =     zfs_freebsd_read,
3556         .vop_write =    zfs_freebsd_write,
3557         .vop_remove =   zfs_freebsd_remove,
3558         .vop_rename =   zfs_freebsd_rename,
3559         .vop_pathconf = zfs_freebsd_pathconf,
3560         .vop_bmap =     VOP_EOPNOTSUPP,
3561         .vop_fid =      zfs_freebsd_fid,
3562 };
3563
3564 struct vop_vector zfs_fifoops = {
3565         .vop_default =  &fifo_specops,
3566         .vop_fsync =    VOP_PANIC,
3567         .vop_access =   zfs_freebsd_access,
3568         .vop_getattr =  zfs_freebsd_getattr,
3569         .vop_inactive = zfs_freebsd_inactive,
3570         .vop_read =     VOP_PANIC,
3571         .vop_reclaim =  zfs_freebsd_reclaim,
3572         .vop_setattr =  zfs_freebsd_setattr,
3573         .vop_write =    VOP_PANIC,
3574         .vop_fid =      zfs_freebsd_fid,
3575 };