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