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