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