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