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