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