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