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