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