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