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