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