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