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