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