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