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