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