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