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