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