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