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