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