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