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