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