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