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