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