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