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