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