]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/zfs/zfs_vnops.c
Remove znode's z_uid/z_gid member
[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_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_uid = zfs_fuid_create(zsb,
2848                             (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
2849                         if (new_uid != KUID_TO_SUID(ZTOI(zp)->i_uid) &&
2850                             zfs_fuid_overquota(zsb, B_FALSE, new_uid)) {
2851                                 if (attrzp)
2852                                         iput(ZTOI(attrzp));
2853                                 err = EDQUOT;
2854                                 goto out2;
2855                         }
2856                 }
2857
2858                 if (mask & ATTR_GID) {
2859                         new_gid = zfs_fuid_create(zsb, (uint64_t)vap->va_gid,
2860                             cr, ZFS_GROUP, &fuidp);
2861                         if (new_gid != KGID_TO_SGID(ZTOI(zp)->i_gid) &&
2862                             zfs_fuid_overquota(zsb, B_TRUE, new_gid)) {
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                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zsb), NULL,
2954                             &new_uid, sizeof (new_uid));
2955                         ZTOI(zp)->i_uid = SUID_TO_KUID(new_uid);
2956                         if (attrzp) {
2957                                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2958                                     SA_ZPL_UID(zsb), NULL, &new_uid,
2959                                     sizeof (new_uid));
2960                                 ZTOI(attrzp)->i_uid = SUID_TO_KUID(new_uid);
2961                         }
2962                 }
2963
2964                 if (mask & ATTR_GID) {
2965                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zsb),
2966                             NULL, &new_gid, sizeof (new_gid));
2967                         ZTOI(zp)->i_gid = SGID_TO_KGID(new_gid);
2968                         if (attrzp) {
2969                                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2970                                     SA_ZPL_GID(zsb), NULL, &new_gid,
2971                                     sizeof (new_gid));
2972                                 ZTOI(attrzp)->i_gid = SGID_TO_KGID(new_gid);
2973                         }
2974                 }
2975                 if (!(mask & ATTR_MODE)) {
2976                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zsb),
2977                             NULL, &new_mode, sizeof (new_mode));
2978                         new_mode = zp->z_mode;
2979                 }
2980                 err = zfs_acl_chown_setattr(zp);
2981                 ASSERT(err == 0);
2982                 if (attrzp) {
2983                         err = zfs_acl_chown_setattr(attrzp);
2984                         ASSERT(err == 0);
2985                 }
2986         }
2987
2988         if (mask & ATTR_MODE) {
2989                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zsb), NULL,
2990                     &new_mode, sizeof (new_mode));
2991                 zp->z_mode = new_mode;
2992                 ASSERT3P(aclp, !=, NULL);
2993                 err = zfs_aclset_common(zp, aclp, cr, tx);
2994                 ASSERT0(err);
2995                 if (zp->z_acl_cached)
2996                         zfs_acl_free(zp->z_acl_cached);
2997                 zp->z_acl_cached = aclp;
2998                 aclp = NULL;
2999         }
3000
3001
3002         if ((mask & ATTR_ATIME) || zp->z_atime_dirty) {
3003                 zp->z_atime_dirty = 0;
3004                 ZFS_TIME_ENCODE(&ip->i_atime, atime);
3005                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zsb), NULL,
3006                     &atime, sizeof (atime));
3007         }
3008
3009         if (mask & ATTR_MTIME) {
3010                 ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
3011                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zsb), NULL,
3012                     mtime, sizeof (mtime));
3013         }
3014
3015         /* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
3016         if (mask & ATTR_SIZE && !(mask & ATTR_MTIME)) {
3017                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zsb),
3018                     NULL, mtime, sizeof (mtime));
3019                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zsb), NULL,
3020                     &ctime, sizeof (ctime));
3021                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
3022         } else if (mask != 0) {
3023                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zsb), NULL,
3024                     &ctime, sizeof (ctime));
3025                 zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime);
3026                 if (attrzp) {
3027                         SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
3028                             SA_ZPL_CTIME(zsb), NULL,
3029                             &ctime, sizeof (ctime));
3030                         zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
3031                             mtime, ctime);
3032                 }
3033         }
3034         /*
3035          * Do this after setting timestamps to prevent timestamp
3036          * update from toggling bit
3037          */
3038
3039         if (xoap && (mask & ATTR_XVATTR)) {
3040
3041                 /*
3042                  * restore trimmed off masks
3043                  * so that return masks can be set for caller.
3044                  */
3045
3046                 if (XVA_ISSET_REQ(tmpxvattr, XAT_APPENDONLY)) {
3047                         XVA_SET_REQ(xvap, XAT_APPENDONLY);
3048                 }
3049                 if (XVA_ISSET_REQ(tmpxvattr, XAT_NOUNLINK)) {
3050                         XVA_SET_REQ(xvap, XAT_NOUNLINK);
3051                 }
3052                 if (XVA_ISSET_REQ(tmpxvattr, XAT_IMMUTABLE)) {
3053                         XVA_SET_REQ(xvap, XAT_IMMUTABLE);
3054                 }
3055                 if (XVA_ISSET_REQ(tmpxvattr, XAT_NODUMP)) {
3056                         XVA_SET_REQ(xvap, XAT_NODUMP);
3057                 }
3058                 if (XVA_ISSET_REQ(tmpxvattr, XAT_AV_MODIFIED)) {
3059                         XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
3060                 }
3061                 if (XVA_ISSET_REQ(tmpxvattr, XAT_AV_QUARANTINED)) {
3062                         XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
3063                 }
3064
3065                 if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
3066                         ASSERT(S_ISREG(ip->i_mode));
3067
3068                 zfs_xvattr_set(zp, xvap, tx);
3069         }
3070
3071         if (fuid_dirtied)
3072                 zfs_fuid_sync(zsb, tx);
3073
3074         if (mask != 0)
3075                 zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
3076
3077         mutex_exit(&zp->z_lock);
3078         if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE))
3079                 mutex_exit(&zp->z_acl_lock);
3080
3081         if (attrzp) {
3082                 if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE))
3083                         mutex_exit(&attrzp->z_acl_lock);
3084                 mutex_exit(&attrzp->z_lock);
3085         }
3086 out:
3087         if (err == 0 && attrzp) {
3088                 err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
3089                     xattr_count, tx);
3090                 ASSERT(err2 == 0);
3091         }
3092
3093         if (attrzp)
3094                 iput(ZTOI(attrzp));
3095         if (aclp)
3096                 zfs_acl_free(aclp);
3097
3098         if (fuidp) {
3099                 zfs_fuid_info_free(fuidp);
3100                 fuidp = NULL;
3101         }
3102
3103         if (err) {
3104                 dmu_tx_abort(tx);
3105                 if (err == ERESTART)
3106                         goto top;
3107         } else {
3108                 err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
3109                 dmu_tx_commit(tx);
3110                 zfs_inode_update(zp);
3111         }
3112
3113 out2:
3114         if (zsb->z_os->os_sync == ZFS_SYNC_ALWAYS)
3115                 zil_commit(zilog, 0);
3116
3117 out3:
3118         kmem_free(xattr_bulk, sizeof (sa_bulk_attr_t) * 7);
3119         kmem_free(bulk, sizeof (sa_bulk_attr_t) * 7);
3120         kmem_free(tmpxvattr, sizeof (xvattr_t));
3121         ZFS_EXIT(zsb);
3122         return (err);
3123 }
3124 EXPORT_SYMBOL(zfs_setattr);
3125
3126 typedef struct zfs_zlock {
3127         krwlock_t       *zl_rwlock;     /* lock we acquired */
3128         znode_t         *zl_znode;      /* znode we held */
3129         struct zfs_zlock *zl_next;      /* next in list */
3130 } zfs_zlock_t;
3131
3132 /*
3133  * Drop locks and release vnodes that were held by zfs_rename_lock().
3134  */
3135 static void
3136 zfs_rename_unlock(zfs_zlock_t **zlpp)
3137 {
3138         zfs_zlock_t *zl;
3139
3140         while ((zl = *zlpp) != NULL) {
3141                 if (zl->zl_znode != NULL)
3142                         iput(ZTOI(zl->zl_znode));
3143                 rw_exit(zl->zl_rwlock);
3144                 *zlpp = zl->zl_next;
3145                 kmem_free(zl, sizeof (*zl));
3146         }
3147 }
3148
3149 /*
3150  * Search back through the directory tree, using the ".." entries.
3151  * Lock each directory in the chain to prevent concurrent renames.
3152  * Fail any attempt to move a directory into one of its own descendants.
3153  * XXX - z_parent_lock can overlap with map or grow locks
3154  */
3155 static int
3156 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
3157 {
3158         zfs_zlock_t     *zl;
3159         znode_t         *zp = tdzp;
3160         uint64_t        rootid = ZTOZSB(zp)->z_root;
3161         uint64_t        oidp = zp->z_id;
3162         krwlock_t       *rwlp = &szp->z_parent_lock;
3163         krw_t           rw = RW_WRITER;
3164
3165         /*
3166          * First pass write-locks szp and compares to zp->z_id.
3167          * Later passes read-lock zp and compare to zp->z_parent.
3168          */
3169         do {
3170                 if (!rw_tryenter(rwlp, rw)) {
3171                         /*
3172                          * Another thread is renaming in this path.
3173                          * Note that if we are a WRITER, we don't have any
3174                          * parent_locks held yet.
3175                          */
3176                         if (rw == RW_READER && zp->z_id > szp->z_id) {
3177                                 /*
3178                                  * Drop our locks and restart
3179                                  */
3180                                 zfs_rename_unlock(&zl);
3181                                 *zlpp = NULL;
3182                                 zp = tdzp;
3183                                 oidp = zp->z_id;
3184                                 rwlp = &szp->z_parent_lock;
3185                                 rw = RW_WRITER;
3186                                 continue;
3187                         } else {
3188                                 /*
3189                                  * Wait for other thread to drop its locks
3190                                  */
3191                                 rw_enter(rwlp, rw);
3192                         }
3193                 }
3194
3195                 zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
3196                 zl->zl_rwlock = rwlp;
3197                 zl->zl_znode = NULL;
3198                 zl->zl_next = *zlpp;
3199                 *zlpp = zl;
3200
3201                 if (oidp == szp->z_id)          /* We're a descendant of szp */
3202                         return (SET_ERROR(EINVAL));
3203
3204                 if (oidp == rootid)             /* We've hit the top */
3205                         return (0);
3206
3207                 if (rw == RW_READER) {          /* i.e. not the first pass */
3208                         int error = zfs_zget(ZTOZSB(zp), oidp, &zp);
3209                         if (error)
3210                                 return (error);
3211                         zl->zl_znode = zp;
3212                 }
3213                 (void) sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(ZTOZSB(zp)),
3214                     &oidp, sizeof (oidp));
3215                 rwlp = &zp->z_parent_lock;
3216                 rw = RW_READER;
3217
3218         } while (zp->z_id != sdzp->z_id);
3219
3220         return (0);
3221 }
3222
3223 /*
3224  * Move an entry from the provided source directory to the target
3225  * directory.  Change the entry name as indicated.
3226  *
3227  *      IN:     sdip    - Source directory containing the "old entry".
3228  *              snm     - Old entry name.
3229  *              tdip    - Target directory to contain the "new entry".
3230  *              tnm     - New entry name.
3231  *              cr      - credentials of caller.
3232  *              flags   - case flags
3233  *
3234  *      RETURN: 0 on success, error code on failure.
3235  *
3236  * Timestamps:
3237  *      sdip,tdip - ctime|mtime updated
3238  */
3239 /*ARGSUSED*/
3240 int
3241 zfs_rename(struct inode *sdip, char *snm, struct inode *tdip, char *tnm,
3242     cred_t *cr, int flags)
3243 {
3244         znode_t         *tdzp, *szp, *tzp;
3245         znode_t         *sdzp = ITOZ(sdip);
3246         zfs_sb_t        *zsb = ITOZSB(sdip);
3247         zilog_t         *zilog;
3248         zfs_dirlock_t   *sdl, *tdl;
3249         dmu_tx_t        *tx;
3250         zfs_zlock_t     *zl;
3251         int             cmp, serr, terr;
3252         int             error = 0;
3253         int             zflg = 0;
3254         boolean_t       waited = B_FALSE;
3255
3256         ZFS_ENTER(zsb);
3257         ZFS_VERIFY_ZP(sdzp);
3258         zilog = zsb->z_log;
3259
3260         tdzp = ITOZ(tdip);
3261         ZFS_VERIFY_ZP(tdzp);
3262
3263         /*
3264          * We check i_sb because snapshots and the ctldir must have different
3265          * super blocks.
3266          */
3267         if (tdip->i_sb != sdip->i_sb || zfsctl_is_node(tdip)) {
3268                 ZFS_EXIT(zsb);
3269                 return (SET_ERROR(EXDEV));
3270         }
3271
3272         if (zsb->z_utf8 && u8_validate(tnm,
3273             strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3274                 ZFS_EXIT(zsb);
3275                 return (SET_ERROR(EILSEQ));
3276         }
3277
3278         if (flags & FIGNORECASE)
3279                 zflg |= ZCILOOK;
3280
3281 top:
3282         szp = NULL;
3283         tzp = NULL;
3284         zl = NULL;
3285
3286         /*
3287          * This is to prevent the creation of links into attribute space
3288          * by renaming a linked file into/outof an attribute directory.
3289          * See the comment in zfs_link() for why this is considered bad.
3290          */
3291         if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3292                 ZFS_EXIT(zsb);
3293                 return (SET_ERROR(EINVAL));
3294         }
3295
3296         /*
3297          * Lock source and target directory entries.  To prevent deadlock,
3298          * a lock ordering must be defined.  We lock the directory with
3299          * the smallest object id first, or if it's a tie, the one with
3300          * the lexically first name.
3301          */
3302         if (sdzp->z_id < tdzp->z_id) {
3303                 cmp = -1;
3304         } else if (sdzp->z_id > tdzp->z_id) {
3305                 cmp = 1;
3306         } else {
3307                 /*
3308                  * First compare the two name arguments without
3309                  * considering any case folding.
3310                  */
3311                 int nofold = (zsb->z_norm & ~U8_TEXTPREP_TOUPPER);
3312
3313                 cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
3314                 ASSERT(error == 0 || !zsb->z_utf8);
3315                 if (cmp == 0) {
3316                         /*
3317                          * POSIX: "If the old argument and the new argument
3318                          * both refer to links to the same existing file,
3319                          * the rename() function shall return successfully
3320                          * and perform no other action."
3321                          */
3322                         ZFS_EXIT(zsb);
3323                         return (0);
3324                 }
3325                 /*
3326                  * If the file system is case-folding, then we may
3327                  * have some more checking to do.  A case-folding file
3328                  * system is either supporting mixed case sensitivity
3329                  * access or is completely case-insensitive.  Note
3330                  * that the file system is always case preserving.
3331                  *
3332                  * In mixed sensitivity mode case sensitive behavior
3333                  * is the default.  FIGNORECASE must be used to
3334                  * explicitly request case insensitive behavior.
3335                  *
3336                  * If the source and target names provided differ only
3337                  * by case (e.g., a request to rename 'tim' to 'Tim'),
3338                  * we will treat this as a special case in the
3339                  * case-insensitive mode: as long as the source name
3340                  * is an exact match, we will allow this to proceed as
3341                  * a name-change request.
3342                  */
3343                 if ((zsb->z_case == ZFS_CASE_INSENSITIVE ||
3344                     (zsb->z_case == ZFS_CASE_MIXED &&
3345                     flags & FIGNORECASE)) &&
3346                     u8_strcmp(snm, tnm, 0, zsb->z_norm, U8_UNICODE_LATEST,
3347                     &error) == 0) {
3348                         /*
3349                          * case preserving rename request, require exact
3350                          * name matches
3351                          */
3352                         zflg |= ZCIEXACT;
3353                         zflg &= ~ZCILOOK;
3354                 }
3355         }
3356
3357         /*
3358          * If the source and destination directories are the same, we should
3359          * grab the z_name_lock of that directory only once.
3360          */
3361         if (sdzp == tdzp) {
3362                 zflg |= ZHAVELOCK;
3363                 rw_enter(&sdzp->z_name_lock, RW_READER);
3364         }
3365
3366         if (cmp < 0) {
3367                 serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
3368                     ZEXISTS | zflg, NULL, NULL);
3369                 terr = zfs_dirent_lock(&tdl,
3370                     tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
3371         } else {
3372                 terr = zfs_dirent_lock(&tdl,
3373                     tdzp, tnm, &tzp, zflg, NULL, NULL);
3374                 serr = zfs_dirent_lock(&sdl,
3375                     sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
3376                     NULL, NULL);
3377         }
3378
3379         if (serr) {
3380                 /*
3381                  * Source entry invalid or not there.
3382                  */
3383                 if (!terr) {
3384                         zfs_dirent_unlock(tdl);
3385                         if (tzp)
3386                                 iput(ZTOI(tzp));
3387                 }
3388
3389                 if (sdzp == tdzp)
3390                         rw_exit(&sdzp->z_name_lock);
3391
3392                 if (strcmp(snm, "..") == 0)
3393                         serr = EINVAL;
3394                 ZFS_EXIT(zsb);
3395                 return (serr);
3396         }
3397         if (terr) {
3398                 zfs_dirent_unlock(sdl);
3399                 iput(ZTOI(szp));
3400
3401                 if (sdzp == tdzp)
3402                         rw_exit(&sdzp->z_name_lock);
3403
3404                 if (strcmp(tnm, "..") == 0)
3405                         terr = EINVAL;
3406                 ZFS_EXIT(zsb);
3407                 return (terr);
3408         }
3409
3410         /*
3411          * Must have write access at the source to remove the old entry
3412          * and write access at the target to create the new entry.
3413          * Note that if target and source are the same, this can be
3414          * done in a single check.
3415          */
3416
3417         if ((error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr)))
3418                 goto out;
3419
3420         if (S_ISDIR(ZTOI(szp)->i_mode)) {
3421                 /*
3422                  * Check to make sure rename is valid.
3423                  * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3424                  */
3425                 if ((error = zfs_rename_lock(szp, tdzp, sdzp, &zl)))
3426                         goto out;
3427         }
3428
3429         /*
3430          * Does target exist?
3431          */
3432         if (tzp) {
3433                 /*
3434                  * Source and target must be the same type.
3435                  */
3436                 if (S_ISDIR(ZTOI(szp)->i_mode)) {
3437                         if (!S_ISDIR(ZTOI(tzp)->i_mode)) {
3438                                 error = SET_ERROR(ENOTDIR);
3439                                 goto out;
3440                         }
3441                 } else {
3442                         if (S_ISDIR(ZTOI(tzp)->i_mode)) {
3443                                 error = SET_ERROR(EISDIR);
3444                                 goto out;
3445                         }
3446                 }
3447                 /*
3448                  * POSIX dictates that when the source and target
3449                  * entries refer to the same file object, rename
3450                  * must do nothing and exit without error.
3451                  */
3452                 if (szp->z_id == tzp->z_id) {
3453                         error = 0;
3454                         goto out;
3455                 }
3456         }
3457
3458         tx = dmu_tx_create(zsb->z_os);
3459         dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3460         dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
3461         dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3462         dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3463         if (sdzp != tdzp) {
3464                 dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, B_FALSE);
3465                 zfs_sa_upgrade_txholds(tx, tdzp);
3466         }
3467         if (tzp) {
3468                 dmu_tx_hold_sa(tx, tzp->z_sa_hdl, B_FALSE);
3469                 zfs_sa_upgrade_txholds(tx, tzp);
3470         }
3471
3472         zfs_sa_upgrade_txholds(tx, szp);
3473         dmu_tx_hold_zap(tx, zsb->z_unlinkedobj, FALSE, NULL);
3474         error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
3475         if (error) {
3476                 if (zl != NULL)
3477                         zfs_rename_unlock(&zl);
3478                 zfs_dirent_unlock(sdl);
3479                 zfs_dirent_unlock(tdl);
3480
3481                 if (sdzp == tdzp)
3482                         rw_exit(&sdzp->z_name_lock);
3483
3484                 iput(ZTOI(szp));
3485                 if (tzp)
3486                         iput(ZTOI(tzp));
3487                 if (error == ERESTART) {
3488                         waited = B_TRUE;
3489                         dmu_tx_wait(tx);
3490                         dmu_tx_abort(tx);
3491                         goto top;
3492                 }
3493                 dmu_tx_abort(tx);
3494                 ZFS_EXIT(zsb);
3495                 return (error);
3496         }
3497
3498         if (tzp)        /* Attempt to remove the existing target */
3499                 error = zfs_link_destroy(tdl, tzp, tx, zflg, NULL);
3500
3501         if (error == 0) {
3502                 error = zfs_link_create(tdl, szp, tx, ZRENAMING);
3503                 if (error == 0) {
3504                         szp->z_pflags |= ZFS_AV_MODIFIED;
3505
3506                         error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zsb),
3507                             (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3508                         ASSERT0(error);
3509
3510                         error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
3511                         if (error == 0) {
3512                                 zfs_log_rename(zilog, tx, TX_RENAME |
3513                                     (flags & FIGNORECASE ? TX_CI : 0), sdzp,
3514                                     sdl->dl_name, tdzp, tdl->dl_name, szp);
3515                         } else {
3516                                 /*
3517                                  * At this point, we have successfully created
3518                                  * the target name, but have failed to remove
3519                                  * the source name.  Since the create was done
3520                                  * with the ZRENAMING flag, there are
3521                                  * complications; for one, the link count is
3522                                  * wrong.  The easiest way to deal with this
3523                                  * is to remove the newly created target, and
3524                                  * return the original error.  This must
3525                                  * succeed; fortunately, it is very unlikely to
3526                                  * fail, since we just created it.
3527                                  */
3528                                 VERIFY3U(zfs_link_destroy(tdl, szp, tx,
3529                                     ZRENAMING, NULL), ==, 0);
3530                         }
3531                 }
3532         }
3533
3534         dmu_tx_commit(tx);
3535 out:
3536         if (zl != NULL)
3537                 zfs_rename_unlock(&zl);
3538
3539         zfs_dirent_unlock(sdl);
3540         zfs_dirent_unlock(tdl);
3541
3542         zfs_inode_update(sdzp);
3543         if (sdzp == tdzp)
3544                 rw_exit(&sdzp->z_name_lock);
3545
3546         if (sdzp != tdzp)
3547                 zfs_inode_update(tdzp);
3548
3549         zfs_inode_update(szp);
3550         iput(ZTOI(szp));
3551         if (tzp) {
3552                 zfs_inode_update(tzp);
3553                 iput(ZTOI(tzp));
3554         }
3555
3556         if (zsb->z_os->os_sync == ZFS_SYNC_ALWAYS)
3557                 zil_commit(zilog, 0);
3558
3559         ZFS_EXIT(zsb);
3560         return (error);
3561 }
3562 EXPORT_SYMBOL(zfs_rename);
3563
3564 /*
3565  * Insert the indicated symbolic reference entry into the directory.
3566  *
3567  *      IN:     dip     - Directory to contain new symbolic link.
3568  *              link    - Name for new symlink entry.
3569  *              vap     - Attributes of new entry.
3570  *              target  - Target path of new symlink.
3571  *
3572  *              cr      - credentials of caller.
3573  *              flags   - case flags
3574  *
3575  *      RETURN: 0 on success, error code on failure.
3576  *
3577  * Timestamps:
3578  *      dip - ctime|mtime updated
3579  */
3580 /*ARGSUSED*/
3581 int
3582 zfs_symlink(struct inode *dip, char *name, vattr_t *vap, char *link,
3583     struct inode **ipp, cred_t *cr, int flags)
3584 {
3585         znode_t         *zp, *dzp = ITOZ(dip);
3586         zfs_dirlock_t   *dl;
3587         dmu_tx_t        *tx;
3588         zfs_sb_t        *zsb = ITOZSB(dip);
3589         zilog_t         *zilog;
3590         uint64_t        len = strlen(link);
3591         int             error;
3592         int             zflg = ZNEW;
3593         zfs_acl_ids_t   acl_ids;
3594         boolean_t       fuid_dirtied;
3595         uint64_t        txtype = TX_SYMLINK;
3596         boolean_t       waited = B_FALSE;
3597
3598         ASSERT(S_ISLNK(vap->va_mode));
3599
3600         ZFS_ENTER(zsb);
3601         ZFS_VERIFY_ZP(dzp);
3602         zilog = zsb->z_log;
3603
3604         if (zsb->z_utf8 && u8_validate(name, strlen(name),
3605             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3606                 ZFS_EXIT(zsb);
3607                 return (SET_ERROR(EILSEQ));
3608         }
3609         if (flags & FIGNORECASE)
3610                 zflg |= ZCILOOK;
3611
3612         if (len > MAXPATHLEN) {
3613                 ZFS_EXIT(zsb);
3614                 return (SET_ERROR(ENAMETOOLONG));
3615         }
3616
3617         if ((error = zfs_acl_ids_create(dzp, 0,
3618             vap, cr, NULL, &acl_ids)) != 0) {
3619                 ZFS_EXIT(zsb);
3620                 return (error);
3621         }
3622 top:
3623         *ipp = NULL;
3624
3625         /*
3626          * Attempt to lock directory; fail if entry already exists.
3627          */
3628         error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
3629         if (error) {
3630                 zfs_acl_ids_free(&acl_ids);
3631                 ZFS_EXIT(zsb);
3632                 return (error);
3633         }
3634
3635         if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr))) {
3636                 zfs_acl_ids_free(&acl_ids);
3637                 zfs_dirent_unlock(dl);
3638                 ZFS_EXIT(zsb);
3639                 return (error);
3640         }
3641
3642         if (zfs_acl_ids_overquota(zsb, &acl_ids)) {
3643                 zfs_acl_ids_free(&acl_ids);
3644                 zfs_dirent_unlock(dl);
3645                 ZFS_EXIT(zsb);
3646                 return (SET_ERROR(EDQUOT));
3647         }
3648         tx = dmu_tx_create(zsb->z_os);
3649         fuid_dirtied = zsb->z_fuid_dirty;
3650         dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3651         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3652         dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
3653             ZFS_SA_BASE_ATTR_SIZE + len);
3654         dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
3655         if (!zsb->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3656                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3657                     acl_ids.z_aclp->z_acl_bytes);
3658         }
3659         if (fuid_dirtied)
3660                 zfs_fuid_txhold(zsb, tx);
3661         error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
3662         if (error) {
3663                 zfs_dirent_unlock(dl);
3664                 if (error == ERESTART) {
3665                         waited = B_TRUE;
3666                         dmu_tx_wait(tx);
3667                         dmu_tx_abort(tx);
3668                         goto top;
3669                 }
3670                 zfs_acl_ids_free(&acl_ids);
3671                 dmu_tx_abort(tx);
3672                 ZFS_EXIT(zsb);
3673                 return (error);
3674         }
3675
3676         /*
3677          * Create a new object for the symlink.
3678          * for version 4 ZPL datsets the symlink will be an SA attribute
3679          */
3680         zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
3681
3682         if (fuid_dirtied)
3683                 zfs_fuid_sync(zsb, tx);
3684
3685         mutex_enter(&zp->z_lock);
3686         if (zp->z_is_sa)
3687                 error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zsb),
3688                     link, len, tx);
3689         else
3690                 zfs_sa_symlink(zp, link, len, tx);
3691         mutex_exit(&zp->z_lock);
3692
3693         zp->z_size = len;
3694         (void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zsb),
3695             &zp->z_size, sizeof (zp->z_size), tx);
3696         /*
3697          * Insert the new object into the directory.
3698          */
3699         (void) zfs_link_create(dl, zp, tx, ZNEW);
3700
3701         if (flags & FIGNORECASE)
3702                 txtype |= TX_CI;
3703         zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3704
3705         zfs_inode_update(dzp);
3706         zfs_inode_update(zp);
3707
3708         zfs_acl_ids_free(&acl_ids);
3709
3710         dmu_tx_commit(tx);
3711
3712         zfs_dirent_unlock(dl);
3713
3714         *ipp = ZTOI(zp);
3715
3716         if (zsb->z_os->os_sync == ZFS_SYNC_ALWAYS)
3717                 zil_commit(zilog, 0);
3718
3719         ZFS_EXIT(zsb);
3720         return (error);
3721 }
3722 EXPORT_SYMBOL(zfs_symlink);
3723
3724 /*
3725  * Return, in the buffer contained in the provided uio structure,
3726  * the symbolic path referred to by ip.
3727  *
3728  *      IN:     ip      - inode of symbolic link
3729  *              uio     - structure to contain the link path.
3730  *              cr      - credentials of caller.
3731  *
3732  *      RETURN: 0 if success
3733  *              error code if failure
3734  *
3735  * Timestamps:
3736  *      ip - atime updated
3737  */
3738 /* ARGSUSED */
3739 int
3740 zfs_readlink(struct inode *ip, uio_t *uio, cred_t *cr)
3741 {
3742         znode_t         *zp = ITOZ(ip);
3743         zfs_sb_t        *zsb = ITOZSB(ip);
3744         int             error;
3745
3746         ZFS_ENTER(zsb);
3747         ZFS_VERIFY_ZP(zp);
3748
3749         mutex_enter(&zp->z_lock);
3750         if (zp->z_is_sa)
3751                 error = sa_lookup_uio(zp->z_sa_hdl,
3752                     SA_ZPL_SYMLINK(zsb), uio);
3753         else
3754                 error = zfs_sa_readlink(zp, uio);
3755         mutex_exit(&zp->z_lock);
3756
3757         ZFS_EXIT(zsb);
3758         return (error);
3759 }
3760 EXPORT_SYMBOL(zfs_readlink);
3761
3762 /*
3763  * Insert a new entry into directory tdip referencing sip.
3764  *
3765  *      IN:     tdip    - Directory to contain new entry.
3766  *              sip     - inode of new entry.
3767  *              name    - name of new entry.
3768  *              cr      - credentials of caller.
3769  *
3770  *      RETURN: 0 if success
3771  *              error code if failure
3772  *
3773  * Timestamps:
3774  *      tdip - ctime|mtime updated
3775  *       sip - ctime updated
3776  */
3777 /* ARGSUSED */
3778 int
3779 zfs_link(struct inode *tdip, struct inode *sip, char *name, cred_t *cr,
3780     int flags)
3781 {
3782         znode_t         *dzp = ITOZ(tdip);
3783         znode_t         *tzp, *szp;
3784         zfs_sb_t        *zsb = ITOZSB(tdip);
3785         zilog_t         *zilog;
3786         zfs_dirlock_t   *dl;
3787         dmu_tx_t        *tx;
3788         int             error;
3789         int             zf = ZNEW;
3790         uint64_t        parent;
3791         uid_t           owner;
3792         boolean_t       waited = B_FALSE;
3793
3794         ASSERT(S_ISDIR(tdip->i_mode));
3795
3796         ZFS_ENTER(zsb);
3797         ZFS_VERIFY_ZP(dzp);
3798         zilog = zsb->z_log;
3799
3800         /*
3801          * POSIX dictates that we return EPERM here.
3802          * Better choices include ENOTSUP or EISDIR.
3803          */
3804         if (S_ISDIR(sip->i_mode)) {
3805                 ZFS_EXIT(zsb);
3806                 return (SET_ERROR(EPERM));
3807         }
3808
3809         szp = ITOZ(sip);
3810         ZFS_VERIFY_ZP(szp);
3811
3812         /*
3813          * We check i_sb because snapshots and the ctldir must have different
3814          * super blocks.
3815          */
3816         if (sip->i_sb != tdip->i_sb || zfsctl_is_node(sip)) {
3817                 ZFS_EXIT(zsb);
3818                 return (SET_ERROR(EXDEV));
3819         }
3820
3821         /* Prevent links to .zfs/shares files */
3822
3823         if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zsb),
3824             &parent, sizeof (uint64_t))) != 0) {
3825                 ZFS_EXIT(zsb);
3826                 return (error);
3827         }
3828         if (parent == zsb->z_shares_dir) {
3829                 ZFS_EXIT(zsb);
3830                 return (SET_ERROR(EPERM));
3831         }
3832
3833         if (zsb->z_utf8 && u8_validate(name,
3834             strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3835                 ZFS_EXIT(zsb);
3836                 return (SET_ERROR(EILSEQ));
3837         }
3838         if (flags & FIGNORECASE)
3839                 zf |= ZCILOOK;
3840
3841         /*
3842          * We do not support links between attributes and non-attributes
3843          * because of the potential security risk of creating links
3844          * into "normal" file space in order to circumvent restrictions
3845          * imposed in attribute space.
3846          */
3847         if ((szp->z_pflags & ZFS_XATTR) != (dzp->z_pflags & ZFS_XATTR)) {
3848                 ZFS_EXIT(zsb);
3849                 return (SET_ERROR(EINVAL));
3850         }
3851
3852         owner = zfs_fuid_map_id(zsb, KUID_TO_SUID(sip->i_uid), cr, ZFS_OWNER);
3853         if (owner != crgetuid(cr) && secpolicy_basic_link(cr) != 0) {
3854                 ZFS_EXIT(zsb);
3855                 return (SET_ERROR(EPERM));
3856         }
3857
3858         if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr))) {
3859                 ZFS_EXIT(zsb);
3860                 return (error);
3861         }
3862
3863 top:
3864         /*
3865          * Attempt to lock directory; fail if entry already exists.
3866          */
3867         error = zfs_dirent_lock(&dl, dzp, name, &tzp, zf, NULL, NULL);
3868         if (error) {
3869                 ZFS_EXIT(zsb);
3870                 return (error);
3871         }
3872
3873         tx = dmu_tx_create(zsb->z_os);
3874         dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3875         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3876         zfs_sa_upgrade_txholds(tx, szp);
3877         zfs_sa_upgrade_txholds(tx, dzp);
3878         error = dmu_tx_assign(tx, waited ? TXG_WAITED : TXG_NOWAIT);
3879         if (error) {
3880                 zfs_dirent_unlock(dl);
3881                 if (error == ERESTART) {
3882                         waited = B_TRUE;
3883                         dmu_tx_wait(tx);
3884                         dmu_tx_abort(tx);
3885                         goto top;
3886                 }
3887                 dmu_tx_abort(tx);
3888                 ZFS_EXIT(zsb);
3889                 return (error);
3890         }
3891
3892         error = zfs_link_create(dl, szp, tx, 0);
3893
3894         if (error == 0) {
3895                 uint64_t txtype = TX_LINK;
3896                 if (flags & FIGNORECASE)
3897                         txtype |= TX_CI;
3898                 zfs_log_link(zilog, tx, txtype, dzp, szp, name);
3899         }
3900
3901         dmu_tx_commit(tx);
3902
3903         zfs_dirent_unlock(dl);
3904
3905         if (zsb->z_os->os_sync == ZFS_SYNC_ALWAYS)
3906                 zil_commit(zilog, 0);
3907
3908         zfs_inode_update(dzp);
3909         zfs_inode_update(szp);
3910         ZFS_EXIT(zsb);
3911         return (error);
3912 }
3913 EXPORT_SYMBOL(zfs_link);
3914
3915 static void
3916 zfs_putpage_commit_cb(void *arg)
3917 {
3918         struct page *pp = arg;
3919
3920         ClearPageError(pp);
3921         end_page_writeback(pp);
3922 }
3923
3924 /*
3925  * Push a page out to disk, once the page is on stable storage the
3926  * registered commit callback will be run as notification of completion.
3927  *
3928  *      IN:     ip      - page mapped for inode.
3929  *              pp      - page to push (page is locked)
3930  *              wbc     - writeback control data
3931  *
3932  *      RETURN: 0 if success
3933  *              error code if failure
3934  *
3935  * Timestamps:
3936  *      ip - ctime|mtime updated
3937  */
3938 /* ARGSUSED */
3939 int
3940 zfs_putpage(struct inode *ip, struct page *pp, struct writeback_control *wbc)
3941 {
3942         znode_t         *zp = ITOZ(ip);
3943         zfs_sb_t        *zsb = ITOZSB(ip);
3944         loff_t          offset;
3945         loff_t          pgoff;
3946         unsigned int    pglen;
3947         rl_t            *rl;
3948         dmu_tx_t        *tx;
3949         caddr_t         va;
3950         int             err = 0;
3951         uint64_t        mtime[2], ctime[2];
3952         sa_bulk_attr_t  bulk[3];
3953         int             cnt = 0;
3954         struct address_space *mapping;
3955
3956         ZFS_ENTER(zsb);
3957         ZFS_VERIFY_ZP(zp);
3958
3959         ASSERT(PageLocked(pp));
3960
3961         pgoff = page_offset(pp);        /* Page byte-offset in file */
3962         offset = i_size_read(ip);       /* File length in bytes */
3963         pglen = MIN(PAGE_SIZE,          /* Page length in bytes */
3964             P2ROUNDUP(offset, PAGE_SIZE)-pgoff);
3965
3966         /* Page is beyond end of file */
3967         if (pgoff >= offset) {
3968                 unlock_page(pp);
3969                 ZFS_EXIT(zsb);
3970                 return (0);
3971         }
3972
3973         /* Truncate page length to end of file */
3974         if (pgoff + pglen > offset)
3975                 pglen = offset - pgoff;
3976
3977 #if 0
3978         /*
3979          * FIXME: Allow mmap writes past its quota.  The correct fix
3980          * is to register a page_mkwrite() handler to count the page
3981          * against its quota when it is about to be dirtied.
3982          */
3983         if (zfs_owner_overquota(zsb, zp, B_FALSE) ||
3984             zfs_owner_overquota(zsb, zp, B_TRUE)) {
3985                 err = EDQUOT;
3986         }
3987 #endif
3988
3989         /*
3990          * The ordering here is critical and must adhere to the following
3991          * rules in order to avoid deadlocking in either zfs_read() or
3992          * zfs_free_range() due to a lock inversion.
3993          *
3994          * 1) The page must be unlocked prior to acquiring the range lock.
3995          *    This is critical because zfs_read() calls find_lock_page()
3996          *    which may block on the page lock while holding the range lock.
3997          *
3998          * 2) Before setting or clearing write back on a page the range lock
3999          *    must be held in order to prevent a lock inversion with the
4000          *    zfs_free_range() function.
4001          *
4002          * This presents a problem because upon entering this function the
4003          * page lock is already held.  To safely acquire the range lock the
4004          * page lock must be dropped.  This creates a window where another
4005          * process could truncate, invalidate, dirty, or write out the page.
4006          *
4007          * Therefore, after successfully reacquiring the range and page locks
4008          * the current page state is checked.  In the common case everything
4009          * will be as is expected and it can be written out.  However, if
4010          * the page state has changed it must be handled accordingly.
4011          */
4012         mapping = pp->mapping;
4013         redirty_page_for_writepage(wbc, pp);
4014         unlock_page(pp);
4015
4016         rl = zfs_range_lock(&zp->z_range_lock, pgoff, pglen, RL_WRITER);
4017         lock_page(pp);
4018
4019         /* Page mapping changed or it was no longer dirty, we're done */
4020         if (unlikely((mapping != pp->mapping) || !PageDirty(pp))) {
4021                 unlock_page(pp);
4022                 zfs_range_unlock(rl);
4023                 ZFS_EXIT(zsb);
4024                 return (0);
4025         }
4026
4027         /* Another process started write block if required */
4028         if (PageWriteback(pp)) {
4029                 unlock_page(pp);
4030                 zfs_range_unlock(rl);
4031
4032                 if (wbc->sync_mode != WB_SYNC_NONE)
4033                         wait_on_page_writeback(pp);
4034
4035                 ZFS_EXIT(zsb);
4036                 return (0);
4037         }
4038
4039         /* Clear the dirty flag the required locks are held */
4040         if (!clear_page_dirty_for_io(pp)) {
4041                 unlock_page(pp);
4042                 zfs_range_unlock(rl);
4043                 ZFS_EXIT(zsb);
4044                 return (0);
4045         }
4046
4047         /*
4048          * Counterpart for redirty_page_for_writepage() above.  This page
4049          * was in fact not skipped and should not be counted as if it were.
4050          */
4051         wbc->pages_skipped--;
4052         set_page_writeback(pp);
4053         unlock_page(pp);
4054
4055         tx = dmu_tx_create(zsb->z_os);
4056         dmu_tx_hold_write(tx, zp->z_id, pgoff, pglen);
4057         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4058         zfs_sa_upgrade_txholds(tx, zp);
4059
4060         err = dmu_tx_assign(tx, TXG_NOWAIT);
4061         if (err != 0) {
4062                 if (err == ERESTART)
4063                         dmu_tx_wait(tx);
4064
4065                 dmu_tx_abort(tx);
4066                 __set_page_dirty_nobuffers(pp);
4067                 ClearPageError(pp);
4068                 end_page_writeback(pp);
4069                 zfs_range_unlock(rl);
4070                 ZFS_EXIT(zsb);
4071                 return (err);
4072         }
4073
4074         va = kmap(pp);
4075         ASSERT3U(pglen, <=, PAGE_SIZE);
4076         dmu_write(zsb->z_os, zp->z_id, pgoff, pglen, va, tx);
4077         kunmap(pp);
4078
4079         SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_MTIME(zsb), NULL, &mtime, 16);
4080         SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_CTIME(zsb), NULL, &ctime, 16);
4081         SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_FLAGS(zsb), NULL, &zp->z_pflags, 8);
4082
4083         /* Preserve the mtime and ctime provided by the inode */
4084         ZFS_TIME_ENCODE(&ip->i_mtime, mtime);
4085         ZFS_TIME_ENCODE(&ip->i_ctime, ctime);
4086         zp->z_atime_dirty = 0;
4087         zp->z_seq++;
4088
4089         err = sa_bulk_update(zp->z_sa_hdl, bulk, cnt, tx);
4090
4091         zfs_log_write(zsb->z_log, tx, TX_WRITE, zp, pgoff, pglen, 0,
4092             zfs_putpage_commit_cb, pp);
4093         dmu_tx_commit(tx);
4094
4095         zfs_range_unlock(rl);
4096
4097         if (wbc->sync_mode != WB_SYNC_NONE) {
4098                 /*
4099                  * Note that this is rarely called under writepages(), because
4100                  * writepages() normally handles the entire commit for
4101                  * performance reasons.
4102                  */
4103                 if (zsb->z_log != NULL)
4104                         zil_commit(zsb->z_log, zp->z_id);
4105         }
4106
4107         ZFS_EXIT(zsb);
4108         return (err);
4109 }
4110
4111 /*
4112  * Update the system attributes when the inode has been dirtied.  For the
4113  * moment we only update the mode, atime, mtime, and ctime.
4114  */
4115 int
4116 zfs_dirty_inode(struct inode *ip, int flags)
4117 {
4118         znode_t         *zp = ITOZ(ip);
4119         zfs_sb_t        *zsb = ITOZSB(ip);
4120         dmu_tx_t        *tx;
4121         uint64_t        mode, atime[2], mtime[2], ctime[2];
4122         sa_bulk_attr_t  bulk[4];
4123         int             error = 0;
4124         int             cnt = 0;
4125
4126         if (zfs_is_readonly(zsb) || dmu_objset_is_snapshot(zsb->z_os))
4127                 return (0);
4128
4129         ZFS_ENTER(zsb);
4130         ZFS_VERIFY_ZP(zp);
4131
4132 #ifdef I_DIRTY_TIME
4133         /*
4134          * This is the lazytime semantic indroduced in Linux 4.0
4135          * This flag will only be called from update_time when lazytime is set.
4136          * (Note, I_DIRTY_SYNC will also set if not lazytime)
4137          * Fortunately mtime and ctime are managed within ZFS itself, so we
4138          * only need to dirty atime.
4139          */
4140         if (flags == I_DIRTY_TIME) {
4141                 zp->z_atime_dirty = 1;
4142                 goto out;
4143         }
4144 #endif
4145
4146         tx = dmu_tx_create(zsb->z_os);
4147
4148         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4149         zfs_sa_upgrade_txholds(tx, zp);
4150
4151         error = dmu_tx_assign(tx, TXG_WAIT);
4152         if (error) {
4153                 dmu_tx_abort(tx);
4154                 goto out;
4155         }
4156
4157         mutex_enter(&zp->z_lock);
4158         zp->z_atime_dirty = 0;
4159
4160         SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_MODE(zsb), NULL, &mode, 8);
4161         SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_ATIME(zsb), NULL, &atime, 16);
4162         SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_MTIME(zsb), NULL, &mtime, 16);
4163         SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_CTIME(zsb), NULL, &ctime, 16);
4164
4165         /* Preserve the mode, mtime and ctime provided by the inode */
4166         ZFS_TIME_ENCODE(&ip->i_atime, atime);
4167         ZFS_TIME_ENCODE(&ip->i_mtime, mtime);
4168         ZFS_TIME_ENCODE(&ip->i_ctime, ctime);
4169         mode = ip->i_mode;
4170
4171         zp->z_mode = mode;
4172
4173         error = sa_bulk_update(zp->z_sa_hdl, bulk, cnt, tx);
4174         mutex_exit(&zp->z_lock);
4175
4176         dmu_tx_commit(tx);
4177 out:
4178         ZFS_EXIT(zsb);
4179         return (error);
4180 }
4181 EXPORT_SYMBOL(zfs_dirty_inode);
4182
4183 /*ARGSUSED*/
4184 void
4185 zfs_inactive(struct inode *ip)
4186 {
4187         znode_t *zp = ITOZ(ip);
4188         zfs_sb_t *zsb = ITOZSB(ip);
4189         uint64_t atime[2];
4190         int error;
4191         int need_unlock = 0;
4192
4193         /* Only read lock if we haven't already write locked, e.g. rollback */
4194         if (!RW_WRITE_HELD(&zsb->z_teardown_inactive_lock)) {
4195                 need_unlock = 1;
4196                 rw_enter(&zsb->z_teardown_inactive_lock, RW_READER);
4197         }
4198         if (zp->z_sa_hdl == NULL) {
4199                 if (need_unlock)
4200                         rw_exit(&zsb->z_teardown_inactive_lock);
4201                 return;
4202         }
4203
4204         if (zp->z_atime_dirty && zp->z_unlinked == 0) {
4205                 dmu_tx_t *tx = dmu_tx_create(zsb->z_os);
4206
4207                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4208                 zfs_sa_upgrade_txholds(tx, zp);
4209                 error = dmu_tx_assign(tx, TXG_WAIT);
4210                 if (error) {
4211                         dmu_tx_abort(tx);
4212                 } else {
4213                         ZFS_TIME_ENCODE(&ip->i_atime, atime);
4214                         mutex_enter(&zp->z_lock);
4215                         (void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zsb),
4216                             (void *)&atime, sizeof (atime), tx);
4217                         zp->z_atime_dirty = 0;
4218                         mutex_exit(&zp->z_lock);
4219                         dmu_tx_commit(tx);
4220                 }
4221         }
4222
4223         zfs_zinactive(zp);
4224         if (need_unlock)
4225                 rw_exit(&zsb->z_teardown_inactive_lock);
4226 }
4227 EXPORT_SYMBOL(zfs_inactive);
4228
4229 /*
4230  * Bounds-check the seek operation.
4231  *
4232  *      IN:     ip      - inode seeking within
4233  *              ooff    - old file offset
4234  *              noffp   - pointer to new file offset
4235  *              ct      - caller context
4236  *
4237  *      RETURN: 0 if success
4238  *              EINVAL if new offset invalid
4239  */
4240 /* ARGSUSED */
4241 int
4242 zfs_seek(struct inode *ip, offset_t ooff, offset_t *noffp)
4243 {
4244         if (S_ISDIR(ip->i_mode))
4245                 return (0);
4246         return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
4247 }
4248 EXPORT_SYMBOL(zfs_seek);
4249
4250 /*
4251  * Fill pages with data from the disk.
4252  */
4253 static int
4254 zfs_fillpage(struct inode *ip, struct page *pl[], int nr_pages)
4255 {
4256         znode_t *zp = ITOZ(ip);
4257         zfs_sb_t *zsb = ITOZSB(ip);
4258         objset_t *os;
4259         struct page *cur_pp;
4260         u_offset_t io_off, total;
4261         size_t io_len;
4262         loff_t i_size;
4263         unsigned page_idx;
4264         int err;
4265
4266         os = zsb->z_os;
4267         io_len = nr_pages << PAGE_SHIFT;
4268         i_size = i_size_read(ip);
4269         io_off = page_offset(pl[0]);
4270
4271         if (io_off + io_len > i_size)
4272                 io_len = i_size - io_off;
4273
4274         /*
4275          * Iterate over list of pages and read each page individually.
4276          */
4277         page_idx = 0;
4278         for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
4279                 caddr_t va;
4280
4281                 cur_pp = pl[page_idx++];
4282                 va = kmap(cur_pp);
4283                 err = dmu_read(os, zp->z_id, io_off, PAGESIZE, va,
4284                     DMU_READ_PREFETCH);
4285                 kunmap(cur_pp);
4286                 if (err) {
4287                         /* convert checksum errors into IO errors */
4288                         if (err == ECKSUM)
4289                                 err = SET_ERROR(EIO);
4290                         return (err);
4291                 }
4292         }
4293
4294         return (0);
4295 }
4296
4297 /*
4298  * Uses zfs_fillpage to read data from the file and fill the pages.
4299  *
4300  *      IN:     ip       - inode of file to get data from.
4301  *              pl       - list of pages to read
4302  *              nr_pages - number of pages to read
4303  *
4304  *      RETURN: 0 on success, error code on failure.
4305  *
4306  * Timestamps:
4307  *      vp - atime updated
4308  */
4309 /* ARGSUSED */
4310 int
4311 zfs_getpage(struct inode *ip, struct page *pl[], int nr_pages)
4312 {
4313         znode_t  *zp  = ITOZ(ip);
4314         zfs_sb_t *zsb = ITOZSB(ip);
4315         int      err;
4316
4317         if (pl == NULL)
4318                 return (0);
4319
4320         ZFS_ENTER(zsb);
4321         ZFS_VERIFY_ZP(zp);
4322
4323         err = zfs_fillpage(ip, pl, nr_pages);
4324
4325         ZFS_EXIT(zsb);
4326         return (err);
4327 }
4328 EXPORT_SYMBOL(zfs_getpage);
4329
4330 /*
4331  * Check ZFS specific permissions to memory map a section of a file.
4332  *
4333  *      IN:     ip      - inode of the file to mmap
4334  *              off     - file offset
4335  *              addrp   - start address in memory region
4336  *              len     - length of memory region
4337  *              vm_flags- address flags
4338  *
4339  *      RETURN: 0 if success
4340  *              error code if failure
4341  */
4342 /*ARGSUSED*/
4343 int
4344 zfs_map(struct inode *ip, offset_t off, caddr_t *addrp, size_t len,
4345     unsigned long vm_flags)
4346 {
4347         znode_t  *zp = ITOZ(ip);
4348         zfs_sb_t *zsb = ITOZSB(ip);
4349
4350         ZFS_ENTER(zsb);
4351         ZFS_VERIFY_ZP(zp);
4352
4353         if ((vm_flags & VM_WRITE) && (zp->z_pflags &
4354             (ZFS_IMMUTABLE | ZFS_READONLY | ZFS_APPENDONLY))) {
4355                 ZFS_EXIT(zsb);
4356                 return (SET_ERROR(EPERM));
4357         }
4358
4359         if ((vm_flags & (VM_READ | VM_EXEC)) &&
4360             (zp->z_pflags & ZFS_AV_QUARANTINED)) {
4361                 ZFS_EXIT(zsb);
4362                 return (SET_ERROR(EACCES));
4363         }
4364
4365         if (off < 0 || len > MAXOFFSET_T - off) {
4366                 ZFS_EXIT(zsb);
4367                 return (SET_ERROR(ENXIO));
4368         }
4369
4370         ZFS_EXIT(zsb);
4371         return (0);
4372 }
4373 EXPORT_SYMBOL(zfs_map);
4374
4375 /*
4376  * convoff - converts the given data (start, whence) to the
4377  * given whence.
4378  */
4379 int
4380 convoff(struct inode *ip, flock64_t *lckdat, int  whence, offset_t offset)
4381 {
4382         vattr_t vap;
4383         int error;
4384
4385         if ((lckdat->l_whence == 2) || (whence == 2)) {
4386                 if ((error = zfs_getattr(ip, &vap, 0, CRED()) != 0))
4387                         return (error);
4388         }
4389
4390         switch (lckdat->l_whence) {
4391         case 1:
4392                 lckdat->l_start += offset;
4393                 break;
4394         case 2:
4395                 lckdat->l_start += vap.va_size;
4396                 /* FALLTHRU */
4397         case 0:
4398                 break;
4399         default:
4400                 return (SET_ERROR(EINVAL));
4401         }
4402
4403         if (lckdat->l_start < 0)
4404                 return (SET_ERROR(EINVAL));
4405
4406         switch (whence) {
4407         case 1:
4408                 lckdat->l_start -= offset;
4409                 break;
4410         case 2:
4411                 lckdat->l_start -= vap.va_size;
4412                 /* FALLTHRU */
4413         case 0:
4414                 break;
4415         default:
4416                 return (SET_ERROR(EINVAL));
4417         }
4418
4419         lckdat->l_whence = (short)whence;
4420         return (0);
4421 }
4422
4423 /*
4424  * Free or allocate space in a file.  Currently, this function only
4425  * supports the `F_FREESP' command.  However, this command is somewhat
4426  * misnamed, as its functionality includes the ability to allocate as
4427  * well as free space.
4428  *
4429  *      IN:     ip      - inode of file to free data in.
4430  *              cmd     - action to take (only F_FREESP supported).
4431  *              bfp     - section of file to free/alloc.
4432  *              flag    - current file open mode flags.
4433  *              offset  - current file offset.
4434  *              cr      - credentials of caller [UNUSED].
4435  *
4436  *      RETURN: 0 on success, error code on failure.
4437  *
4438  * Timestamps:
4439  *      ip - ctime|mtime updated
4440  */
4441 /* ARGSUSED */
4442 int
4443 zfs_space(struct inode *ip, int cmd, flock64_t *bfp, int flag,
4444     offset_t offset, cred_t *cr)
4445 {
4446         znode_t         *zp = ITOZ(ip);
4447         zfs_sb_t        *zsb = ITOZSB(ip);
4448         uint64_t        off, len;
4449         int             error;
4450
4451         ZFS_ENTER(zsb);
4452         ZFS_VERIFY_ZP(zp);
4453
4454         if (cmd != F_FREESP) {
4455                 ZFS_EXIT(zsb);
4456                 return (SET_ERROR(EINVAL));
4457         }
4458
4459         /*
4460          * Callers might not be able to detect properly that we are read-only,
4461          * so check it explicitly here.
4462          */
4463         if (zfs_is_readonly(zsb)) {
4464                 ZFS_EXIT(zsb);
4465                 return (SET_ERROR(EROFS));
4466         }
4467
4468         if ((error = convoff(ip, bfp, 0, offset))) {
4469                 ZFS_EXIT(zsb);
4470                 return (error);
4471         }
4472
4473         if (bfp->l_len < 0) {
4474                 ZFS_EXIT(zsb);
4475                 return (SET_ERROR(EINVAL));
4476         }
4477
4478         /*
4479          * Permissions aren't checked on Solaris because on this OS
4480          * zfs_space() can only be called with an opened file handle.
4481          * On Linux we can get here through truncate_range() which
4482          * operates directly on inodes, so we need to check access rights.
4483          */
4484         if ((error = zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr))) {
4485                 ZFS_EXIT(zsb);
4486                 return (error);
4487         }
4488
4489         off = bfp->l_start;
4490         len = bfp->l_len; /* 0 means from off to end of file */
4491
4492         error = zfs_freesp(zp, off, len, flag, TRUE);
4493
4494         ZFS_EXIT(zsb);
4495         return (error);
4496 }
4497 EXPORT_SYMBOL(zfs_space);
4498
4499 /*ARGSUSED*/
4500 int
4501 zfs_fid(struct inode *ip, fid_t *fidp)
4502 {
4503         znode_t         *zp = ITOZ(ip);
4504         zfs_sb_t        *zsb = ITOZSB(ip);
4505         uint32_t        gen;
4506         uint64_t        gen64;
4507         uint64_t        object = zp->z_id;
4508         zfid_short_t    *zfid;
4509         int             size, i, error;
4510
4511         ZFS_ENTER(zsb);
4512         ZFS_VERIFY_ZP(zp);
4513
4514         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zsb),
4515             &gen64, sizeof (uint64_t))) != 0) {
4516                 ZFS_EXIT(zsb);
4517                 return (error);
4518         }
4519
4520         gen = (uint32_t)gen64;
4521
4522         size = (zsb->z_parent != zsb) ? LONG_FID_LEN : SHORT_FID_LEN;
4523         if (fidp->fid_len < size) {
4524                 fidp->fid_len = size;
4525                 ZFS_EXIT(zsb);
4526                 return (SET_ERROR(ENOSPC));
4527         }
4528
4529         zfid = (zfid_short_t *)fidp;
4530
4531         zfid->zf_len = size;
4532
4533         for (i = 0; i < sizeof (zfid->zf_object); i++)
4534                 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
4535
4536         /* Must have a non-zero generation number to distinguish from .zfs */
4537         if (gen == 0)
4538                 gen = 1;
4539         for (i = 0; i < sizeof (zfid->zf_gen); i++)
4540                 zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
4541
4542         if (size == LONG_FID_LEN) {
4543                 uint64_t        objsetid = dmu_objset_id(zsb->z_os);
4544                 zfid_long_t     *zlfid;
4545
4546                 zlfid = (zfid_long_t *)fidp;
4547
4548                 for (i = 0; i < sizeof (zlfid->zf_setid); i++)
4549                         zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
4550
4551                 /* XXX - this should be the generation number for the objset */
4552                 for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
4553                         zlfid->zf_setgen[i] = 0;
4554         }
4555
4556         ZFS_EXIT(zsb);
4557         return (0);
4558 }
4559 EXPORT_SYMBOL(zfs_fid);
4560
4561 /*ARGSUSED*/
4562 int
4563 zfs_getsecattr(struct inode *ip, vsecattr_t *vsecp, int flag, cred_t *cr)
4564 {
4565         znode_t *zp = ITOZ(ip);
4566         zfs_sb_t *zsb = ITOZSB(ip);
4567         int error;
4568         boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
4569
4570         ZFS_ENTER(zsb);
4571         ZFS_VERIFY_ZP(zp);
4572         error = zfs_getacl(zp, vsecp, skipaclchk, cr);
4573         ZFS_EXIT(zsb);
4574
4575         return (error);
4576 }
4577 EXPORT_SYMBOL(zfs_getsecattr);
4578
4579 /*ARGSUSED*/
4580 int
4581 zfs_setsecattr(struct inode *ip, vsecattr_t *vsecp, int flag, cred_t *cr)
4582 {
4583         znode_t *zp = ITOZ(ip);
4584         zfs_sb_t *zsb = ITOZSB(ip);
4585         int error;
4586         boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
4587         zilog_t *zilog = zsb->z_log;
4588
4589         ZFS_ENTER(zsb);
4590         ZFS_VERIFY_ZP(zp);
4591
4592         error = zfs_setacl(zp, vsecp, skipaclchk, cr);
4593
4594         if (zsb->z_os->os_sync == ZFS_SYNC_ALWAYS)
4595                 zil_commit(zilog, 0);
4596
4597         ZFS_EXIT(zsb);
4598         return (error);
4599 }
4600 EXPORT_SYMBOL(zfs_setsecattr);
4601
4602 #ifdef HAVE_UIO_ZEROCOPY
4603 /*
4604  * Tunable, both must be a power of 2.
4605  *
4606  * zcr_blksz_min: the smallest read we may consider to loan out an arcbuf
4607  * zcr_blksz_max: if set to less than the file block size, allow loaning out of
4608  *              an arcbuf for a partial block read
4609  */
4610 int zcr_blksz_min = (1 << 10);  /* 1K */
4611 int zcr_blksz_max = (1 << 17);  /* 128K */
4612
4613 /*ARGSUSED*/
4614 static int
4615 zfs_reqzcbuf(struct inode *ip, enum uio_rw ioflag, xuio_t *xuio, cred_t *cr)
4616 {
4617         znode_t *zp = ITOZ(ip);
4618         zfs_sb_t *zsb = ITOZSB(ip);
4619         int max_blksz = zsb->z_max_blksz;
4620         uio_t *uio = &xuio->xu_uio;
4621         ssize_t size = uio->uio_resid;
4622         offset_t offset = uio->uio_loffset;
4623         int blksz;
4624         int fullblk, i;
4625         arc_buf_t *abuf;
4626         ssize_t maxsize;
4627         int preamble, postamble;
4628
4629         if (xuio->xu_type != UIOTYPE_ZEROCOPY)
4630                 return (SET_ERROR(EINVAL));
4631
4632         ZFS_ENTER(zsb);
4633         ZFS_VERIFY_ZP(zp);
4634         switch (ioflag) {
4635         case UIO_WRITE:
4636                 /*
4637                  * Loan out an arc_buf for write if write size is bigger than
4638                  * max_blksz, and the file's block size is also max_blksz.
4639                  */
4640                 blksz = max_blksz;
4641                 if (size < blksz || zp->z_blksz != blksz) {
4642                         ZFS_EXIT(zsb);
4643                         return (SET_ERROR(EINVAL));
4644                 }
4645                 /*
4646                  * Caller requests buffers for write before knowing where the
4647                  * write offset might be (e.g. NFS TCP write).
4648                  */
4649                 if (offset == -1) {
4650                         preamble = 0;
4651                 } else {
4652                         preamble = P2PHASE(offset, blksz);
4653                         if (preamble) {
4654                                 preamble = blksz - preamble;
4655                                 size -= preamble;
4656                         }
4657                 }
4658
4659                 postamble = P2PHASE(size, blksz);
4660                 size -= postamble;
4661
4662                 fullblk = size / blksz;
4663                 (void) dmu_xuio_init(xuio,
4664                     (preamble != 0) + fullblk + (postamble != 0));
4665
4666                 /*
4667                  * Have to fix iov base/len for partial buffers.  They
4668                  * currently represent full arc_buf's.
4669                  */
4670                 if (preamble) {
4671                         /* data begins in the middle of the arc_buf */
4672                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
4673                             blksz);
4674                         ASSERT(abuf);
4675                         (void) dmu_xuio_add(xuio, abuf,
4676                             blksz - preamble, preamble);
4677                 }
4678
4679                 for (i = 0; i < fullblk; i++) {
4680                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
4681                             blksz);
4682                         ASSERT(abuf);
4683                         (void) dmu_xuio_add(xuio, abuf, 0, blksz);
4684                 }
4685
4686                 if (postamble) {
4687                         /* data ends in the middle of the arc_buf */
4688                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
4689                             blksz);
4690                         ASSERT(abuf);
4691                         (void) dmu_xuio_add(xuio, abuf, 0, postamble);
4692                 }
4693                 break;
4694         case UIO_READ:
4695                 /*
4696                  * Loan out an arc_buf for read if the read size is larger than
4697                  * the current file block size.  Block alignment is not
4698                  * considered.  Partial arc_buf will be loaned out for read.
4699                  */
4700                 blksz = zp->z_blksz;
4701                 if (blksz < zcr_blksz_min)
4702                         blksz = zcr_blksz_min;
4703                 if (blksz > zcr_blksz_max)
4704                         blksz = zcr_blksz_max;
4705                 /* avoid potential complexity of dealing with it */
4706                 if (blksz > max_blksz) {
4707                         ZFS_EXIT(zsb);
4708                         return (SET_ERROR(EINVAL));
4709                 }
4710
4711                 maxsize = zp->z_size - uio->uio_loffset;
4712                 if (size > maxsize)
4713                         size = maxsize;
4714
4715                 if (size < blksz) {
4716                         ZFS_EXIT(zsb);
4717                         return (SET_ERROR(EINVAL));
4718                 }
4719                 break;
4720         default:
4721                 ZFS_EXIT(zsb);
4722                 return (SET_ERROR(EINVAL));
4723         }
4724
4725         uio->uio_extflg = UIO_XUIO;
4726         XUIO_XUZC_RW(xuio) = ioflag;
4727         ZFS_EXIT(zsb);
4728         return (0);
4729 }
4730
4731 /*ARGSUSED*/
4732 static int
4733 zfs_retzcbuf(struct inode *ip, xuio_t *xuio, cred_t *cr)
4734 {
4735         int i;
4736         arc_buf_t *abuf;
4737         int ioflag = XUIO_XUZC_RW(xuio);
4738
4739         ASSERT(xuio->xu_type == UIOTYPE_ZEROCOPY);
4740
4741         i = dmu_xuio_cnt(xuio);
4742         while (i-- > 0) {
4743                 abuf = dmu_xuio_arcbuf(xuio, i);
4744                 /*
4745                  * if abuf == NULL, it must be a write buffer
4746                  * that has been returned in zfs_write().
4747                  */
4748                 if (abuf)
4749                         dmu_return_arcbuf(abuf);
4750                 ASSERT(abuf || ioflag == UIO_WRITE);
4751         }
4752
4753         dmu_xuio_fini(xuio);
4754         return (0);
4755 }
4756 #endif /* HAVE_UIO_ZEROCOPY */
4757
4758 #if defined(_KERNEL) && defined(HAVE_SPL)
4759 module_param(zfs_delete_blocks, ulong, 0644);
4760 MODULE_PARM_DESC(zfs_delete_blocks, "Delete files larger than N blocks async");
4761 module_param(zfs_read_chunk_size, long, 0644);
4762 MODULE_PARM_DESC(zfs_read_chunk_size, "Bytes to read per chunk");
4763 #endif