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