]> granicus.if.org Git - zfs/blob - module/zfs/zfs_vnops.c
cb66741c2adf2d4d1be31f6c07fd75570c4ebed0
[zfs] / 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 offset_t 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[7], xattr_bulk[7];
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         /*
2382          * Immutable files can only alter immutable bit and atime
2383          */
2384         if ((zp->z_pflags & ZFS_IMMUTABLE) &&
2385             ((mask & (ATTR_SIZE|ATTR_UID|ATTR_GID|ATTR_MTIME|ATTR_MODE)) ||
2386             ((mask & ATTR_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2387                 err = EPERM;
2388                 goto out3;
2389         }
2390
2391         if ((mask & ATTR_SIZE) && (zp->z_pflags & ZFS_READONLY)) {
2392                 err = EPERM;
2393                 goto out3;
2394         }
2395
2396         /*
2397          * Verify timestamps doesn't overflow 32 bits.
2398          * ZFS can handle large timestamps, but 32bit syscalls can't
2399          * handle times greater than 2039.  This check should be removed
2400          * once large timestamps are fully supported.
2401          */
2402         if (mask & (ATTR_ATIME | ATTR_MTIME)) {
2403                 if (((mask & ATTR_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2404                     ((mask & ATTR_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2405                         err = EOVERFLOW;
2406                         goto out3;
2407                 }
2408         }
2409
2410 top:
2411         attrzp = NULL;
2412         aclp = NULL;
2413
2414         /* Can this be moved to before the top label? */
2415         if (zsb->z_vfs->mnt_flags & MNT_READONLY) {
2416                 err = EROFS;
2417                 goto out3;
2418         }
2419
2420         /*
2421          * First validate permissions
2422          */
2423
2424         if (mask & ATTR_SIZE) {
2425                 err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, skipaclchk, cr);
2426                 if (err)
2427                         goto out3;
2428
2429                 /*
2430                  * XXX - Note, we are not providing any open
2431                  * mode flags here (like FNDELAY), so we may
2432                  * block if there are locks present... this
2433                  * should be addressed in openat().
2434                  */
2435                 /* XXX - would it be OK to generate a log record here? */
2436                 err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2437                 if (err)
2438                         goto out3;
2439
2440                 /* Careful negative Linux return code here */
2441                 err = -vmtruncate(ip, vap->va_size);
2442                 if (err)
2443                         goto out3;
2444         }
2445
2446         if (mask & (ATTR_ATIME|ATTR_MTIME) ||
2447             ((mask & ATTR_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2448             XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2449             XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2450             XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
2451             XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
2452             XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2453             XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
2454                 need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2455                     skipaclchk, cr);
2456         }
2457
2458         if (mask & (ATTR_UID|ATTR_GID)) {
2459                 int     idmask = (mask & (ATTR_UID|ATTR_GID));
2460                 int     take_owner;
2461                 int     take_group;
2462
2463                 /*
2464                  * NOTE: even if a new mode is being set,
2465                  * we may clear S_ISUID/S_ISGID bits.
2466                  */
2467
2468                 if (!(mask & ATTR_MODE))
2469                         vap->va_mode = zp->z_mode;
2470
2471                 /*
2472                  * Take ownership or chgrp to group we are a member of
2473                  */
2474
2475                 take_owner = (mask & ATTR_UID) && (vap->va_uid == crgetuid(cr));
2476                 take_group = (mask & ATTR_GID) &&
2477                     zfs_groupmember(zsb, vap->va_gid, cr);
2478
2479                 /*
2480                  * If both ATTR_UID and ATTR_GID are set then take_owner and
2481                  * take_group must both be set in order to allow taking
2482                  * ownership.
2483                  *
2484                  * Otherwise, send the check through secpolicy_vnode_setattr()
2485                  *
2486                  */
2487
2488                 if (((idmask == (ATTR_UID|ATTR_GID)) &&
2489                     take_owner && take_group) ||
2490                     ((idmask == ATTR_UID) && take_owner) ||
2491                     ((idmask == ATTR_GID) && take_group)) {
2492                         if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2493                             skipaclchk, cr) == 0) {
2494                                 /*
2495                                  * Remove setuid/setgid for non-privileged users
2496                                  */
2497                                 (void) secpolicy_setid_clear(vap, cr);
2498                                 trim_mask = (mask & (ATTR_UID|ATTR_GID));
2499                         } else {
2500                                 need_policy =  TRUE;
2501                         }
2502                 } else {
2503                         need_policy =  TRUE;
2504                 }
2505         }
2506
2507         mutex_enter(&zp->z_lock);
2508         oldva.va_mode = zp->z_mode;
2509         zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
2510         if (mask & ATTR_XVATTR) {
2511                 /*
2512                  * Update xvattr mask to include only those attributes
2513                  * that are actually changing.
2514                  *
2515                  * the bits will be restored prior to actually setting
2516                  * the attributes so the caller thinks they were set.
2517                  */
2518                 if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2519                         if (xoap->xoa_appendonly !=
2520                             ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
2521                                 need_policy = TRUE;
2522                         } else {
2523                                 XVA_CLR_REQ(xvap, XAT_APPENDONLY);
2524                                 XVA_SET_REQ(tmpxvattr, XAT_APPENDONLY);
2525                         }
2526                 }
2527
2528                 if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2529                         if (xoap->xoa_nounlink !=
2530                             ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
2531                                 need_policy = TRUE;
2532                         } else {
2533                                 XVA_CLR_REQ(xvap, XAT_NOUNLINK);
2534                                 XVA_SET_REQ(tmpxvattr, XAT_NOUNLINK);
2535                         }
2536                 }
2537
2538                 if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2539                         if (xoap->xoa_immutable !=
2540                             ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
2541                                 need_policy = TRUE;
2542                         } else {
2543                                 XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
2544                                 XVA_SET_REQ(tmpxvattr, XAT_IMMUTABLE);
2545                         }
2546                 }
2547
2548                 if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2549                         if (xoap->xoa_nodump !=
2550                             ((zp->z_pflags & ZFS_NODUMP) != 0)) {
2551                                 need_policy = TRUE;
2552                         } else {
2553                                 XVA_CLR_REQ(xvap, XAT_NODUMP);
2554                                 XVA_SET_REQ(tmpxvattr, XAT_NODUMP);
2555                         }
2556                 }
2557
2558                 if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2559                         if (xoap->xoa_av_modified !=
2560                             ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
2561                                 need_policy = TRUE;
2562                         } else {
2563                                 XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
2564                                 XVA_SET_REQ(tmpxvattr, XAT_AV_MODIFIED);
2565                         }
2566                 }
2567
2568                 if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2569                         if ((!S_ISREG(ip->i_mode) &&
2570                             xoap->xoa_av_quarantined) ||
2571                             xoap->xoa_av_quarantined !=
2572                             ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
2573                                 need_policy = TRUE;
2574                         } else {
2575                                 XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
2576                                 XVA_SET_REQ(tmpxvattr, XAT_AV_QUARANTINED);
2577                         }
2578                 }
2579
2580                 if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2581                         mutex_exit(&zp->z_lock);
2582                         err = EPERM;
2583                         goto out3;
2584                 }
2585
2586                 if (need_policy == FALSE &&
2587                     (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
2588                     XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
2589                         need_policy = TRUE;
2590                 }
2591         }
2592
2593         mutex_exit(&zp->z_lock);
2594
2595         if (mask & ATTR_MODE) {
2596                 if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
2597                         err = secpolicy_setid_setsticky_clear(ip, vap,
2598                             &oldva, cr);
2599                         if (err)
2600                                 goto out3;
2601
2602                         trim_mask |= ATTR_MODE;
2603                 } else {
2604                         need_policy = TRUE;
2605                 }
2606         }
2607
2608         if (need_policy) {
2609                 /*
2610                  * If trim_mask is set then take ownership
2611                  * has been granted or write_acl is present and user
2612                  * has the ability to modify mode.  In that case remove
2613                  * UID|GID and or MODE from mask so that
2614                  * secpolicy_vnode_setattr() doesn't revoke it.
2615                  */
2616
2617                 if (trim_mask) {
2618                         saved_mask = vap->va_mask;
2619                         vap->va_mask &= ~trim_mask;
2620                 }
2621                 err = secpolicy_vnode_setattr(cr, ip, vap, &oldva, flags,
2622                     (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
2623                 if (err)
2624                         goto out3;
2625
2626                 if (trim_mask)
2627                         vap->va_mask |= saved_mask;
2628         }
2629
2630         /*
2631          * secpolicy_vnode_setattr, or take ownership may have
2632          * changed va_mask
2633          */
2634         mask = vap->va_mask;
2635
2636         if ((mask & (ATTR_UID | ATTR_GID))) {
2637                 err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zsb),
2638                     &xattr_obj, sizeof (xattr_obj));
2639
2640                 if (err == 0 && xattr_obj) {
2641                         err = zfs_zget(ZTOZSB(zp), xattr_obj, &attrzp);
2642                         if (err)
2643                                 goto out2;
2644                 }
2645                 if (mask & ATTR_UID) {
2646                         new_uid = zfs_fuid_create(zsb,
2647                             (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
2648                         if (new_uid != zp->z_uid &&
2649                             zfs_fuid_overquota(zsb, B_FALSE, new_uid)) {
2650                                 if (attrzp)
2651                                         iput(ZTOI(attrzp));
2652                                 err = EDQUOT;
2653                                 goto out2;
2654                         }
2655                 }
2656
2657                 if (mask & ATTR_GID) {
2658                         new_gid = zfs_fuid_create(zsb, (uint64_t)vap->va_gid,
2659                             cr, ZFS_GROUP, &fuidp);
2660                         if (new_gid != zp->z_gid &&
2661                             zfs_fuid_overquota(zsb, B_TRUE, new_gid)) {
2662                                 if (attrzp)
2663                                         iput(ZTOI(attrzp));
2664                                 err = EDQUOT;
2665                                 goto out2;
2666                         }
2667                 }
2668         }
2669         tx = dmu_tx_create(zsb->z_os);
2670
2671         if (mask & ATTR_MODE) {
2672                 uint64_t pmode = zp->z_mode;
2673                 uint64_t acl_obj;
2674                 new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
2675
2676                 zfs_acl_chmod_setattr(zp, &aclp, new_mode);
2677
2678                 mutex_enter(&zp->z_lock);
2679                 if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
2680                         /*
2681                          * Are we upgrading ACL from old V0 format
2682                          * to V1 format?
2683                          */
2684                         if (zsb->z_version >= ZPL_VERSION_FUID &&
2685                             zfs_znode_acl_version(zp) ==
2686                             ZFS_ACL_VERSION_INITIAL) {
2687                                 dmu_tx_hold_free(tx, acl_obj, 0,
2688                                     DMU_OBJECT_END);
2689                                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2690                                     0, aclp->z_acl_bytes);
2691                         } else {
2692                                 dmu_tx_hold_write(tx, acl_obj, 0,
2693                                     aclp->z_acl_bytes);
2694                         }
2695                 } else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
2696                         dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2697                             0, aclp->z_acl_bytes);
2698                 }
2699                 mutex_exit(&zp->z_lock);
2700                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2701         } else {
2702                 if ((mask & ATTR_XVATTR) &&
2703                     XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
2704                         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2705                 else
2706                         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2707         }
2708
2709         if (attrzp) {
2710                 dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, B_FALSE);
2711         }
2712
2713         fuid_dirtied = zsb->z_fuid_dirty;
2714         if (fuid_dirtied)
2715                 zfs_fuid_txhold(zsb, tx);
2716
2717         zfs_sa_upgrade_txholds(tx, zp);
2718
2719         err = dmu_tx_assign(tx, TXG_NOWAIT);
2720         if (err) {
2721                 if (err == ERESTART)
2722                         dmu_tx_wait(tx);
2723                 goto out;
2724         }
2725
2726         count = 0;
2727         /*
2728          * Set each attribute requested.
2729          * We group settings according to the locks they need to acquire.
2730          *
2731          * Note: you cannot set ctime directly, although it will be
2732          * updated as a side-effect of calling this function.
2733          */
2734
2735
2736         if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE))
2737                 mutex_enter(&zp->z_acl_lock);
2738         mutex_enter(&zp->z_lock);
2739
2740         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zsb), NULL,
2741             &zp->z_pflags, sizeof (zp->z_pflags));
2742
2743         if (attrzp) {
2744                 if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE))
2745                         mutex_enter(&attrzp->z_acl_lock);
2746                 mutex_enter(&attrzp->z_lock);
2747                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2748                     SA_ZPL_FLAGS(zsb), NULL, &attrzp->z_pflags,
2749                     sizeof (attrzp->z_pflags));
2750         }
2751
2752         if (mask & (ATTR_UID|ATTR_GID)) {
2753
2754                 if (mask & ATTR_UID) {
2755                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zsb), NULL,
2756                             &new_uid, sizeof (new_uid));
2757                         zp->z_uid = new_uid;
2758                         if (attrzp) {
2759                                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2760                                     SA_ZPL_UID(zsb), NULL, &new_uid,
2761                                     sizeof (new_uid));
2762                                 attrzp->z_uid = new_uid;
2763                         }
2764                 }
2765
2766                 if (mask & ATTR_GID) {
2767                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zsb),
2768                             NULL, &new_gid, sizeof (new_gid));
2769                         zp->z_gid = new_gid;
2770                         if (attrzp) {
2771                                 SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2772                                     SA_ZPL_GID(zsb), NULL, &new_gid,
2773                                     sizeof (new_gid));
2774                                 attrzp->z_gid = new_gid;
2775                         }
2776                 }
2777                 if (!(mask & ATTR_MODE)) {
2778                         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zsb),
2779                             NULL, &new_mode, sizeof (new_mode));
2780                         new_mode = zp->z_mode;
2781                 }
2782                 err = zfs_acl_chown_setattr(zp);
2783                 ASSERT(err == 0);
2784                 if (attrzp) {
2785                         err = zfs_acl_chown_setattr(attrzp);
2786                         ASSERT(err == 0);
2787                 }
2788         }
2789
2790         if (mask & ATTR_MODE) {
2791                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zsb), NULL,
2792                     &new_mode, sizeof (new_mode));
2793                 zp->z_mode = new_mode;
2794                 ASSERT3P(aclp, !=, NULL);
2795                 err = zfs_aclset_common(zp, aclp, cr, tx);
2796                 ASSERT3U(err, ==, 0);
2797                 if (zp->z_acl_cached)
2798                         zfs_acl_free(zp->z_acl_cached);
2799                 zp->z_acl_cached = aclp;
2800                 aclp = NULL;
2801         }
2802
2803
2804         if (mask & ATTR_ATIME) {
2805                 ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
2806                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zsb), NULL,
2807                     &zp->z_atime, sizeof (zp->z_atime));
2808         }
2809
2810         if (mask & ATTR_MTIME) {
2811                 ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
2812                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zsb), NULL,
2813                     mtime, sizeof (mtime));
2814         }
2815
2816         /* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
2817         if (mask & ATTR_SIZE && !(mask & ATTR_MTIME)) {
2818                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zsb),
2819                     NULL, mtime, sizeof (mtime));
2820                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zsb), NULL,
2821                     &ctime, sizeof (ctime));
2822                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
2823                     B_TRUE);
2824         } else if (mask != 0) {
2825                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zsb), NULL,
2826                     &ctime, sizeof (ctime));
2827                 zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime,
2828                     B_TRUE);
2829                 if (attrzp) {
2830                         SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2831                             SA_ZPL_CTIME(zsb), NULL,
2832                             &ctime, sizeof (ctime));
2833                         zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
2834                             mtime, ctime, B_TRUE);
2835                 }
2836         }
2837         /*
2838          * Do this after setting timestamps to prevent timestamp
2839          * update from toggling bit
2840          */
2841
2842         if (xoap && (mask & ATTR_XVATTR)) {
2843
2844                 /*
2845                  * restore trimmed off masks
2846                  * so that return masks can be set for caller.
2847                  */
2848
2849                 if (XVA_ISSET_REQ(tmpxvattr, XAT_APPENDONLY)) {
2850                         XVA_SET_REQ(xvap, XAT_APPENDONLY);
2851                 }
2852                 if (XVA_ISSET_REQ(tmpxvattr, XAT_NOUNLINK)) {
2853                         XVA_SET_REQ(xvap, XAT_NOUNLINK);
2854                 }
2855                 if (XVA_ISSET_REQ(tmpxvattr, XAT_IMMUTABLE)) {
2856                         XVA_SET_REQ(xvap, XAT_IMMUTABLE);
2857                 }
2858                 if (XVA_ISSET_REQ(tmpxvattr, XAT_NODUMP)) {
2859                         XVA_SET_REQ(xvap, XAT_NODUMP);
2860                 }
2861                 if (XVA_ISSET_REQ(tmpxvattr, XAT_AV_MODIFIED)) {
2862                         XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
2863                 }
2864                 if (XVA_ISSET_REQ(tmpxvattr, XAT_AV_QUARANTINED)) {
2865                         XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
2866                 }
2867
2868                 if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
2869                         ASSERT(S_ISREG(ip->i_mode));
2870
2871                 zfs_xvattr_set(zp, xvap, tx);
2872         }
2873
2874         if (fuid_dirtied)
2875                 zfs_fuid_sync(zsb, tx);
2876
2877         if (mask != 0)
2878                 zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
2879
2880         mutex_exit(&zp->z_lock);
2881         if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE))
2882                 mutex_exit(&zp->z_acl_lock);
2883
2884         if (attrzp) {
2885                 if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE))
2886                         mutex_exit(&attrzp->z_acl_lock);
2887                 mutex_exit(&attrzp->z_lock);
2888         }
2889 out:
2890         if (err == 0 && attrzp) {
2891                 err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
2892                     xattr_count, tx);
2893                 ASSERT(err2 == 0);
2894         }
2895
2896         if (attrzp)
2897                 iput(ZTOI(attrzp));
2898         if (aclp)
2899                 zfs_acl_free(aclp);
2900
2901         if (fuidp) {
2902                 zfs_fuid_info_free(fuidp);
2903                 fuidp = NULL;
2904         }
2905
2906         if (err) {
2907                 dmu_tx_abort(tx);
2908                 if (err == ERESTART)
2909                         goto top;
2910         } else {
2911                 err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
2912                 dmu_tx_commit(tx);
2913                 zfs_inode_update(zp);
2914         }
2915
2916 out2:
2917         if (zsb->z_os->os_sync == ZFS_SYNC_ALWAYS)
2918                 zil_commit(zilog, 0);
2919
2920 out3:
2921         kmem_free(tmpxvattr, sizeof(xvattr_t));
2922         ZFS_EXIT(zsb);
2923         return (err);
2924 }
2925 EXPORT_SYMBOL(zfs_setattr);
2926
2927 typedef struct zfs_zlock {
2928         krwlock_t       *zl_rwlock;     /* lock we acquired */
2929         znode_t         *zl_znode;      /* znode we held */
2930         struct zfs_zlock *zl_next;      /* next in list */
2931 } zfs_zlock_t;
2932
2933 /*
2934  * Drop locks and release vnodes that were held by zfs_rename_lock().
2935  */
2936 static void
2937 zfs_rename_unlock(zfs_zlock_t **zlpp)
2938 {
2939         zfs_zlock_t *zl;
2940
2941         while ((zl = *zlpp) != NULL) {
2942                 if (zl->zl_znode != NULL)
2943                         iput(ZTOI(zl->zl_znode));
2944                 rw_exit(zl->zl_rwlock);
2945                 *zlpp = zl->zl_next;
2946                 kmem_free(zl, sizeof (*zl));
2947         }
2948 }
2949
2950 /*
2951  * Search back through the directory tree, using the ".." entries.
2952  * Lock each directory in the chain to prevent concurrent renames.
2953  * Fail any attempt to move a directory into one of its own descendants.
2954  * XXX - z_parent_lock can overlap with map or grow locks
2955  */
2956 static int
2957 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
2958 {
2959         zfs_zlock_t     *zl;
2960         znode_t         *zp = tdzp;
2961         uint64_t        rootid = ZTOZSB(zp)->z_root;
2962         uint64_t        oidp = zp->z_id;
2963         krwlock_t       *rwlp = &szp->z_parent_lock;
2964         krw_t           rw = RW_WRITER;
2965
2966         /*
2967          * First pass write-locks szp and compares to zp->z_id.
2968          * Later passes read-lock zp and compare to zp->z_parent.
2969          */
2970         do {
2971                 if (!rw_tryenter(rwlp, rw)) {
2972                         /*
2973                          * Another thread is renaming in this path.
2974                          * Note that if we are a WRITER, we don't have any
2975                          * parent_locks held yet.
2976                          */
2977                         if (rw == RW_READER && zp->z_id > szp->z_id) {
2978                                 /*
2979                                  * Drop our locks and restart
2980                                  */
2981                                 zfs_rename_unlock(&zl);
2982                                 *zlpp = NULL;
2983                                 zp = tdzp;
2984                                 oidp = zp->z_id;
2985                                 rwlp = &szp->z_parent_lock;
2986                                 rw = RW_WRITER;
2987                                 continue;
2988                         } else {
2989                                 /*
2990                                  * Wait for other thread to drop its locks
2991                                  */
2992                                 rw_enter(rwlp, rw);
2993                         }
2994                 }
2995
2996                 zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
2997                 zl->zl_rwlock = rwlp;
2998                 zl->zl_znode = NULL;
2999                 zl->zl_next = *zlpp;
3000                 *zlpp = zl;
3001
3002                 if (oidp == szp->z_id)          /* We're a descendant of szp */
3003                         return (EINVAL);
3004
3005                 if (oidp == rootid)             /* We've hit the top */
3006                         return (0);
3007
3008                 if (rw == RW_READER) {          /* i.e. not the first pass */
3009                         int error = zfs_zget(ZTOZSB(zp), oidp, &zp);
3010                         if (error)
3011                                 return (error);
3012                         zl->zl_znode = zp;
3013                 }
3014                 (void) sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(ZTOZSB(zp)),
3015                     &oidp, sizeof (oidp));
3016                 rwlp = &zp->z_parent_lock;
3017                 rw = RW_READER;
3018
3019         } while (zp->z_id != sdzp->z_id);
3020
3021         return (0);
3022 }
3023
3024 /*
3025  * Move an entry from the provided source directory to the target
3026  * directory.  Change the entry name as indicated.
3027  *
3028  *      IN:     sdip    - Source directory containing the "old entry".
3029  *              snm     - Old entry name.
3030  *              tdip    - Target directory to contain the "new entry".
3031  *              tnm     - New entry name.
3032  *              cr      - credentials of caller.
3033  *              flags   - case flags
3034  *
3035  *      RETURN: 0 if success
3036  *              error code if failure
3037  *
3038  * Timestamps:
3039  *      sdip,tdip - ctime|mtime updated
3040  */
3041 /*ARGSUSED*/
3042 int
3043 zfs_rename(struct inode *sdip, char *snm, struct inode *tdip, char *tnm,
3044     cred_t *cr, int flags)
3045 {
3046         znode_t         *tdzp, *szp, *tzp;
3047         znode_t         *sdzp = ITOZ(sdip);
3048         zfs_sb_t        *zsb = ITOZSB(sdip);
3049         zilog_t         *zilog;
3050         zfs_dirlock_t   *sdl, *tdl;
3051         dmu_tx_t        *tx;
3052         zfs_zlock_t     *zl;
3053         int             cmp, serr, terr;
3054         int             error = 0;
3055         int             zflg = 0;
3056
3057         ZFS_ENTER(zsb);
3058         ZFS_VERIFY_ZP(sdzp);
3059         zilog = zsb->z_log;
3060
3061         if (tdip->i_sb != sdip->i_sb) {
3062                 ZFS_EXIT(zsb);
3063                 return (EXDEV);
3064         }
3065
3066         tdzp = ITOZ(tdip);
3067         ZFS_VERIFY_ZP(tdzp);
3068         if (zsb->z_utf8 && u8_validate(tnm,
3069             strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3070                 ZFS_EXIT(zsb);
3071                 return (EILSEQ);
3072         }
3073
3074         if (flags & FIGNORECASE)
3075                 zflg |= ZCILOOK;
3076
3077 top:
3078         szp = NULL;
3079         tzp = NULL;
3080         zl = NULL;
3081
3082         /*
3083          * This is to prevent the creation of links into attribute space
3084          * by renaming a linked file into/outof an attribute directory.
3085          * See the comment in zfs_link() for why this is considered bad.
3086          */
3087         if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3088                 ZFS_EXIT(zsb);
3089                 return (EINVAL);
3090         }
3091
3092         /*
3093          * Lock source and target directory entries.  To prevent deadlock,
3094          * a lock ordering must be defined.  We lock the directory with
3095          * the smallest object id first, or if it's a tie, the one with
3096          * the lexically first name.
3097          */
3098         if (sdzp->z_id < tdzp->z_id) {
3099                 cmp = -1;
3100         } else if (sdzp->z_id > tdzp->z_id) {
3101                 cmp = 1;
3102         } else {
3103                 /*
3104                  * First compare the two name arguments without
3105                  * considering any case folding.
3106                  */
3107                 int nofold = (zsb->z_norm & ~U8_TEXTPREP_TOUPPER);
3108
3109                 cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
3110                 ASSERT(error == 0 || !zsb->z_utf8);
3111                 if (cmp == 0) {
3112                         /*
3113                          * POSIX: "If the old argument and the new argument
3114                          * both refer to links to the same existing file,
3115                          * the rename() function shall return successfully
3116                          * and perform no other action."
3117                          */
3118                         ZFS_EXIT(zsb);
3119                         return (0);
3120                 }
3121                 /*
3122                  * If the file system is case-folding, then we may
3123                  * have some more checking to do.  A case-folding file
3124                  * system is either supporting mixed case sensitivity
3125                  * access or is completely case-insensitive.  Note
3126                  * that the file system is always case preserving.
3127                  *
3128                  * In mixed sensitivity mode case sensitive behavior
3129                  * is the default.  FIGNORECASE must be used to
3130                  * explicitly request case insensitive behavior.
3131                  *
3132                  * If the source and target names provided differ only
3133                  * by case (e.g., a request to rename 'tim' to 'Tim'),
3134                  * we will treat this as a special case in the
3135                  * case-insensitive mode: as long as the source name
3136                  * is an exact match, we will allow this to proceed as
3137                  * a name-change request.
3138                  */
3139                 if ((zsb->z_case == ZFS_CASE_INSENSITIVE ||
3140                     (zsb->z_case == ZFS_CASE_MIXED &&
3141                     flags & FIGNORECASE)) &&
3142                     u8_strcmp(snm, tnm, 0, zsb->z_norm, U8_UNICODE_LATEST,
3143                     &error) == 0) {
3144                         /*
3145                          * case preserving rename request, require exact
3146                          * name matches
3147                          */
3148                         zflg |= ZCIEXACT;
3149                         zflg &= ~ZCILOOK;
3150                 }
3151         }
3152
3153         /*
3154          * If the source and destination directories are the same, we should
3155          * grab the z_name_lock of that directory only once.
3156          */
3157         if (sdzp == tdzp) {
3158                 zflg |= ZHAVELOCK;
3159                 rw_enter(&sdzp->z_name_lock, RW_READER);
3160         }
3161
3162         if (cmp < 0) {
3163                 serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
3164                     ZEXISTS | zflg, NULL, NULL);
3165                 terr = zfs_dirent_lock(&tdl,
3166                     tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
3167         } else {
3168                 terr = zfs_dirent_lock(&tdl,
3169                     tdzp, tnm, &tzp, zflg, NULL, NULL);
3170                 serr = zfs_dirent_lock(&sdl,
3171                     sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
3172                     NULL, NULL);
3173         }
3174
3175         if (serr) {
3176                 /*
3177                  * Source entry invalid or not there.
3178                  */
3179                 if (!terr) {
3180                         zfs_dirent_unlock(tdl);
3181                         if (tzp)
3182                                 iput(ZTOI(tzp));
3183                 }
3184
3185                 if (sdzp == tdzp)
3186                         rw_exit(&sdzp->z_name_lock);
3187
3188                 if (strcmp(snm, "..") == 0)
3189                         serr = EINVAL;
3190                 ZFS_EXIT(zsb);
3191                 return (serr);
3192         }
3193         if (terr) {
3194                 zfs_dirent_unlock(sdl);
3195                 iput(ZTOI(szp));
3196
3197                 if (sdzp == tdzp)
3198                         rw_exit(&sdzp->z_name_lock);
3199
3200                 if (strcmp(tnm, "..") == 0)
3201                         terr = EINVAL;
3202                 ZFS_EXIT(zsb);
3203                 return (terr);
3204         }
3205
3206         /*
3207          * Must have write access at the source to remove the old entry
3208          * and write access at the target to create the new entry.
3209          * Note that if target and source are the same, this can be
3210          * done in a single check.
3211          */
3212
3213         if ((error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr)))
3214                 goto out;
3215
3216         if (S_ISDIR(ZTOI(szp)->i_mode)) {
3217                 /*
3218                  * Check to make sure rename is valid.
3219                  * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3220                  */
3221                 if ((error = zfs_rename_lock(szp, tdzp, sdzp, &zl)))
3222                         goto out;
3223         }
3224
3225         /*
3226          * Does target exist?
3227          */
3228         if (tzp) {
3229                 /*
3230                  * Source and target must be the same type.
3231                  */
3232                 if (S_ISDIR(ZTOI(szp)->i_mode)) {
3233                         if (!S_ISDIR(ZTOI(tzp)->i_mode)) {
3234                                 error = ENOTDIR;
3235                                 goto out;
3236                         }
3237                 } else {
3238                         if (S_ISDIR(ZTOI(tzp)->i_mode)) {
3239                                 error = EISDIR;
3240                                 goto out;
3241                         }
3242                 }
3243                 /*
3244                  * POSIX dictates that when the source and target
3245                  * entries refer to the same file object, rename
3246                  * must do nothing and exit without error.
3247                  */
3248                 if (szp->z_id == tzp->z_id) {
3249                         error = 0;
3250                         goto out;
3251                 }
3252         }
3253
3254         tx = dmu_tx_create(zsb->z_os);
3255         dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3256         dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
3257         dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3258         dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3259         if (sdzp != tdzp) {
3260                 dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, B_FALSE);
3261                 zfs_sa_upgrade_txholds(tx, tdzp);
3262         }
3263         if (tzp) {
3264                 dmu_tx_hold_sa(tx, tzp->z_sa_hdl, B_FALSE);
3265                 zfs_sa_upgrade_txholds(tx, tzp);
3266         }
3267
3268         zfs_sa_upgrade_txholds(tx, szp);
3269         dmu_tx_hold_zap(tx, zsb->z_unlinkedobj, FALSE, NULL);
3270         error = dmu_tx_assign(tx, TXG_NOWAIT);
3271         if (error) {
3272                 if (zl != NULL)
3273                         zfs_rename_unlock(&zl);
3274                 zfs_dirent_unlock(sdl);
3275                 zfs_dirent_unlock(tdl);
3276
3277                 if (sdzp == tdzp)
3278                         rw_exit(&sdzp->z_name_lock);
3279
3280                 iput(ZTOI(szp));
3281                 if (tzp)
3282                         iput(ZTOI(tzp));
3283                 if (error == ERESTART) {
3284                         dmu_tx_wait(tx);
3285                         dmu_tx_abort(tx);
3286                         goto top;
3287                 }
3288                 dmu_tx_abort(tx);
3289                 ZFS_EXIT(zsb);
3290                 return (error);
3291         }
3292
3293         if (tzp)        /* Attempt to remove the existing target */
3294                 error = zfs_link_destroy(tdl, tzp, tx, zflg, NULL);
3295
3296         if (error == 0) {
3297                 error = zfs_link_create(tdl, szp, tx, ZRENAMING);
3298                 if (error == 0) {
3299                         szp->z_pflags |= ZFS_AV_MODIFIED;
3300
3301                         error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zsb),
3302                             (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3303                         ASSERT3U(error, ==, 0);
3304
3305                         error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
3306                         if (error == 0) {
3307                                 zfs_log_rename(zilog, tx, TX_RENAME |
3308                                     (flags & FIGNORECASE ? TX_CI : 0), sdzp,
3309                                     sdl->dl_name, tdzp, tdl->dl_name, szp);
3310                         } else {
3311                                 /*
3312                                  * At this point, we have successfully created
3313                                  * the target name, but have failed to remove
3314                                  * the source name.  Since the create was done
3315                                  * with the ZRENAMING flag, there are
3316                                  * complications; for one, the link count is
3317                                  * wrong.  The easiest way to deal with this
3318                                  * is to remove the newly created target, and
3319                                  * return the original error.  This must
3320                                  * succeed; fortunately, it is very unlikely to
3321                                  * fail, since we just created it.
3322                                  */
3323                                 VERIFY3U(zfs_link_destroy(tdl, szp, tx,
3324                                     ZRENAMING, NULL), ==, 0);
3325                         }
3326                 }
3327         }
3328
3329         dmu_tx_commit(tx);
3330 out:
3331         if (zl != NULL)
3332                 zfs_rename_unlock(&zl);
3333
3334         zfs_dirent_unlock(sdl);
3335         zfs_dirent_unlock(tdl);
3336
3337         zfs_inode_update(sdzp);
3338         if (sdzp == tdzp)
3339                 rw_exit(&sdzp->z_name_lock);
3340
3341         if (sdzp != tdzp)
3342                 zfs_inode_update(tdzp);
3343
3344         zfs_inode_update(szp);
3345         iput(ZTOI(szp));
3346         if (tzp) {
3347                 zfs_inode_update(tzp);
3348                 iput(ZTOI(tzp));
3349         }
3350
3351         if (zsb->z_os->os_sync == ZFS_SYNC_ALWAYS)
3352                 zil_commit(zilog, 0);
3353
3354         ZFS_EXIT(zsb);
3355         return (error);
3356 }
3357 EXPORT_SYMBOL(zfs_rename);
3358
3359 /*
3360  * Insert the indicated symbolic reference entry into the directory.
3361  *
3362  *      IN:     dip     - Directory to contain new symbolic link.
3363  *              link    - Name for new symlink entry.
3364  *              vap     - Attributes of new entry.
3365  *              target  - Target path of new symlink.
3366  *
3367  *              cr      - credentials of caller.
3368  *              flags   - case flags
3369  *
3370  *      RETURN: 0 if success
3371  *              error code if failure
3372  *
3373  * Timestamps:
3374  *      dip - ctime|mtime updated
3375  */
3376 /*ARGSUSED*/
3377 int
3378 zfs_symlink(struct inode *dip, char *name, vattr_t *vap, char *link,
3379     struct inode **ipp, cred_t *cr, int flags)
3380 {
3381         znode_t         *zp, *dzp = ITOZ(dip);
3382         zfs_dirlock_t   *dl;
3383         dmu_tx_t        *tx;
3384         zfs_sb_t        *zsb = ITOZSB(dip);
3385         zilog_t         *zilog;
3386         uint64_t        len = strlen(link);
3387         int             error;
3388         int             zflg = ZNEW;
3389         zfs_acl_ids_t   acl_ids;
3390         boolean_t       fuid_dirtied;
3391         uint64_t        txtype = TX_SYMLINK;
3392
3393         ASSERT(S_ISLNK(vap->va_mode));
3394
3395         ZFS_ENTER(zsb);
3396         ZFS_VERIFY_ZP(dzp);
3397         zilog = zsb->z_log;
3398
3399         if (zsb->z_utf8 && u8_validate(name, strlen(name),
3400             NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3401                 ZFS_EXIT(zsb);
3402                 return (EILSEQ);
3403         }
3404         if (flags & FIGNORECASE)
3405                 zflg |= ZCILOOK;
3406
3407         if (len > MAXPATHLEN) {
3408                 ZFS_EXIT(zsb);
3409                 return (ENAMETOOLONG);
3410         }
3411
3412         if ((error = zfs_acl_ids_create(dzp, 0,
3413             vap, cr, NULL, &acl_ids)) != 0) {
3414                 ZFS_EXIT(zsb);
3415                 return (error);
3416         }
3417 top:
3418         *ipp = NULL;
3419
3420         /*
3421          * Attempt to lock directory; fail if entry already exists.
3422          */
3423         error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
3424         if (error) {
3425                 zfs_acl_ids_free(&acl_ids);
3426                 ZFS_EXIT(zsb);
3427                 return (error);
3428         }
3429
3430         if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr))) {
3431                 zfs_acl_ids_free(&acl_ids);
3432                 zfs_dirent_unlock(dl);
3433                 ZFS_EXIT(zsb);
3434                 return (error);
3435         }
3436
3437         if (zfs_acl_ids_overquota(zsb, &acl_ids)) {
3438                 zfs_acl_ids_free(&acl_ids);
3439                 zfs_dirent_unlock(dl);
3440                 ZFS_EXIT(zsb);
3441                 return (EDQUOT);
3442         }
3443         tx = dmu_tx_create(zsb->z_os);
3444         fuid_dirtied = zsb->z_fuid_dirty;
3445         dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3446         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3447         dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
3448             ZFS_SA_BASE_ATTR_SIZE + len);
3449         dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
3450         if (!zsb->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3451                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3452                     acl_ids.z_aclp->z_acl_bytes);
3453         }
3454         if (fuid_dirtied)
3455                 zfs_fuid_txhold(zsb, tx);
3456         error = dmu_tx_assign(tx, TXG_NOWAIT);
3457         if (error) {
3458                 zfs_dirent_unlock(dl);
3459                 if (error == ERESTART) {
3460                         dmu_tx_wait(tx);
3461                         dmu_tx_abort(tx);
3462                         goto top;
3463                 }
3464                 zfs_acl_ids_free(&acl_ids);
3465                 dmu_tx_abort(tx);
3466                 ZFS_EXIT(zsb);
3467                 return (error);
3468         }
3469
3470         /*
3471          * Create a new object for the symlink.
3472          * for version 4 ZPL datsets the symlink will be an SA attribute
3473          */
3474         zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
3475
3476         if (fuid_dirtied)
3477                 zfs_fuid_sync(zsb, tx);
3478
3479         mutex_enter(&zp->z_lock);
3480         if (zp->z_is_sa)
3481                 error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zsb),
3482                     link, len, tx);
3483         else
3484                 zfs_sa_symlink(zp, link, len, tx);
3485         mutex_exit(&zp->z_lock);
3486
3487         zp->z_size = len;
3488         (void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zsb),
3489             &zp->z_size, sizeof (zp->z_size), tx);
3490         /*
3491          * Insert the new object into the directory.
3492          */
3493         (void) zfs_link_create(dl, zp, tx, ZNEW);
3494
3495         if (flags & FIGNORECASE)
3496                 txtype |= TX_CI;
3497         zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3498
3499         zfs_inode_update(dzp);
3500         zfs_inode_update(zp);
3501
3502         zfs_acl_ids_free(&acl_ids);
3503
3504         dmu_tx_commit(tx);
3505
3506         zfs_dirent_unlock(dl);
3507
3508         *ipp = ZTOI(zp);
3509
3510         if (zsb->z_os->os_sync == ZFS_SYNC_ALWAYS)
3511                 zil_commit(zilog, 0);
3512
3513         ZFS_EXIT(zsb);
3514         return (error);
3515 }
3516 EXPORT_SYMBOL(zfs_symlink);
3517
3518 /*
3519  * Return, in the buffer contained in the provided uio structure,
3520  * the symbolic path referred to by ip.
3521  *
3522  *      IN:     ip      - inode of symbolic link
3523  *              uio     - structure to contain the link path.
3524  *              cr      - credentials of caller.
3525  *
3526  *      RETURN: 0 if success
3527  *              error code if failure
3528  *
3529  * Timestamps:
3530  *      ip - atime updated
3531  */
3532 /* ARGSUSED */
3533 int
3534 zfs_readlink(struct inode *ip, uio_t *uio, cred_t *cr)
3535 {
3536         znode_t         *zp = ITOZ(ip);
3537         zfs_sb_t        *zsb = ITOZSB(ip);
3538         int             error;
3539
3540         ZFS_ENTER(zsb);
3541         ZFS_VERIFY_ZP(zp);
3542
3543         mutex_enter(&zp->z_lock);
3544         if (zp->z_is_sa)
3545                 error = sa_lookup_uio(zp->z_sa_hdl,
3546                     SA_ZPL_SYMLINK(zsb), uio);
3547         else
3548                 error = zfs_sa_readlink(zp, uio);
3549         mutex_exit(&zp->z_lock);
3550
3551         ZFS_ACCESSTIME_STAMP(zsb, zp);
3552         zfs_inode_update(zp);
3553         ZFS_EXIT(zsb);
3554         return (error);
3555 }
3556 EXPORT_SYMBOL(zfs_readlink);
3557
3558 /*
3559  * Insert a new entry into directory tdip referencing sip.
3560  *
3561  *      IN:     tdip    - Directory to contain new entry.
3562  *              sip     - inode of new entry.
3563  *              name    - name of new entry.
3564  *              cr      - credentials of caller.
3565  *
3566  *      RETURN: 0 if success
3567  *              error code if failure
3568  *
3569  * Timestamps:
3570  *      tdip - ctime|mtime updated
3571  *       sip - ctime updated
3572  */
3573 /* ARGSUSED */
3574 int
3575 zfs_link(struct inode *tdip, struct inode *sip, char *name, cred_t *cr)
3576 {
3577         znode_t         *dzp = ITOZ(tdip);
3578         znode_t         *tzp, *szp;
3579         zfs_sb_t        *zsb = ITOZSB(tdip);
3580         zilog_t         *zilog;
3581         zfs_dirlock_t   *dl;
3582         dmu_tx_t        *tx;
3583         int             error;
3584         int             zf = ZNEW;
3585         uint64_t        parent;
3586         uid_t           owner;
3587
3588         ASSERT(S_ISDIR(tdip->i_mode));
3589
3590         ZFS_ENTER(zsb);
3591         ZFS_VERIFY_ZP(dzp);
3592         zilog = zsb->z_log;
3593
3594         /*
3595          * POSIX dictates that we return EPERM here.
3596          * Better choices include ENOTSUP or EISDIR.
3597          */
3598         if (S_ISDIR(sip->i_mode)) {
3599                 ZFS_EXIT(zsb);
3600                 return (EPERM);
3601         }
3602
3603         if (sip->i_sb != tdip->i_sb) {
3604                 ZFS_EXIT(zsb);
3605                 return (EXDEV);
3606         }
3607
3608         szp = ITOZ(sip);
3609         ZFS_VERIFY_ZP(szp);
3610
3611         /* Prevent links to .zfs/shares files */
3612
3613         if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zsb),
3614             &parent, sizeof (uint64_t))) != 0) {
3615                 ZFS_EXIT(zsb);
3616                 return (error);
3617         }
3618         if (parent == zsb->z_shares_dir) {
3619                 ZFS_EXIT(zsb);
3620                 return (EPERM);
3621         }
3622
3623         if (zsb->z_utf8 && u8_validate(name,
3624             strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3625                 ZFS_EXIT(zsb);
3626                 return (EILSEQ);
3627         }
3628 #ifdef HAVE_PN_UTILS
3629         if (flags & FIGNORECASE)
3630                 zf |= ZCILOOK;
3631 #endif /* HAVE_PN_UTILS */
3632
3633         /*
3634          * We do not support links between attributes and non-attributes
3635          * because of the potential security risk of creating links
3636          * into "normal" file space in order to circumvent restrictions
3637          * imposed in attribute space.
3638          */
3639         if ((szp->z_pflags & ZFS_XATTR) != (dzp->z_pflags & ZFS_XATTR)) {
3640                 ZFS_EXIT(zsb);
3641                 return (EINVAL);
3642         }
3643
3644         owner = zfs_fuid_map_id(zsb, szp->z_uid, cr, ZFS_OWNER);
3645         if (owner != crgetuid(cr) && secpolicy_basic_link(cr) != 0) {
3646                 ZFS_EXIT(zsb);
3647                 return (EPERM);
3648         }
3649
3650         if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr))) {
3651                 ZFS_EXIT(zsb);
3652                 return (error);
3653         }
3654
3655 top:
3656         /*
3657          * Attempt to lock directory; fail if entry already exists.
3658          */
3659         error = zfs_dirent_lock(&dl, dzp, name, &tzp, zf, NULL, NULL);
3660         if (error) {
3661                 ZFS_EXIT(zsb);
3662                 return (error);
3663         }
3664
3665         tx = dmu_tx_create(zsb->z_os);
3666         dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3667         dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3668         zfs_sa_upgrade_txholds(tx, szp);
3669         zfs_sa_upgrade_txholds(tx, dzp);
3670         error = dmu_tx_assign(tx, TXG_NOWAIT);
3671         if (error) {
3672                 zfs_dirent_unlock(dl);
3673                 if (error == ERESTART) {
3674                         dmu_tx_wait(tx);
3675                         dmu_tx_abort(tx);
3676                         goto top;
3677                 }
3678                 dmu_tx_abort(tx);
3679                 ZFS_EXIT(zsb);
3680                 return (error);
3681         }
3682
3683         error = zfs_link_create(dl, szp, tx, 0);
3684
3685         if (error == 0) {
3686                 uint64_t txtype = TX_LINK;
3687 #ifdef HAVE_PN_UTILS
3688                 if (flags & FIGNORECASE)
3689                         txtype |= TX_CI;
3690 #endif /* HAVE_PN_UTILS */
3691                 zfs_log_link(zilog, tx, txtype, dzp, szp, name);
3692         }
3693
3694         dmu_tx_commit(tx);
3695
3696         zfs_dirent_unlock(dl);
3697
3698         if (zsb->z_os->os_sync == ZFS_SYNC_ALWAYS)
3699                 zil_commit(zilog, 0);
3700
3701         zfs_inode_update(dzp);
3702         zfs_inode_update(szp);
3703         ZFS_EXIT(zsb);
3704         return (error);
3705 }
3706 EXPORT_SYMBOL(zfs_link);
3707
3708 #ifdef HAVE_MMAP
3709 /*
3710  * zfs_null_putapage() is used when the file system has been force
3711  * unmounted. It just drops the pages.
3712  */
3713 /* ARGSUSED */
3714 static int
3715 zfs_null_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
3716                 size_t *lenp, int flags, cred_t *cr)
3717 {
3718         pvn_write_done(pp, B_INVAL|B_FORCE|B_ERROR);
3719         return (0);
3720 }
3721
3722 /*
3723  * Push a page out to disk, klustering if possible.
3724  *
3725  *      IN:     vp      - file to push page to.
3726  *              pp      - page to push.
3727  *              flags   - additional flags.
3728  *              cr      - credentials of caller.
3729  *
3730  *      OUT:    offp    - start of range pushed.
3731  *              lenp    - len of range pushed.
3732  *
3733  *      RETURN: 0 if success
3734  *              error code if failure
3735  *
3736  * NOTE: callers must have locked the page to be pushed.  On
3737  * exit, the page (and all other pages in the kluster) must be
3738  * unlocked.
3739  */
3740 /* ARGSUSED */
3741 static int
3742 zfs_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp,
3743                 size_t *lenp, int flags, cred_t *cr)
3744 {
3745         znode_t         *zp = VTOZ(vp);
3746         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
3747         dmu_tx_t        *tx;
3748         u_offset_t      off, koff;
3749         size_t          len, klen;
3750         int             err;
3751
3752         off = pp->p_offset;
3753         len = PAGESIZE;
3754         /*
3755          * If our blocksize is bigger than the page size, try to kluster
3756          * multiple pages so that we write a full block (thus avoiding
3757          * a read-modify-write).
3758          */
3759         if (off < zp->z_size && zp->z_blksz > PAGESIZE) {
3760                 klen = P2ROUNDUP((ulong_t)zp->z_blksz, PAGESIZE);
3761                 koff = ISP2(klen) ? P2ALIGN(off, (u_offset_t)klen) : 0;
3762                 ASSERT(koff <= zp->z_size);
3763                 if (koff + klen > zp->z_size)
3764                         klen = P2ROUNDUP(zp->z_size - koff, (uint64_t)PAGESIZE);
3765                 pp = pvn_write_kluster(vp, pp, &off, &len, koff, klen, flags);
3766         }
3767         ASSERT3U(btop(len), ==, btopr(len));
3768
3769         /*
3770          * Can't push pages past end-of-file.
3771          */
3772         if (off >= zp->z_size) {
3773                 /* ignore all pages */
3774                 err = 0;
3775                 goto out;
3776         } else if (off + len > zp->z_size) {
3777                 int npages = btopr(zp->z_size - off);
3778                 page_t *trunc;
3779
3780                 page_list_break(&pp, &trunc, npages);
3781                 /* ignore pages past end of file */
3782                 if (trunc)
3783                         pvn_write_done(trunc, flags);
3784                 len = zp->z_size - off;
3785         }
3786
3787         if (zfs_owner_overquota(zfsvfs, zp, B_FALSE) ||
3788             zfs_owner_overquota(zfsvfs, zp, B_TRUE)) {
3789                 err = EDQUOT;
3790                 goto out;
3791         }
3792 top:
3793         tx = dmu_tx_create(zfsvfs->z_os);
3794         dmu_tx_hold_write(tx, zp->z_id, off, len);
3795
3796         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3797         zfs_sa_upgrade_txholds(tx, zp);
3798         err = dmu_tx_assign(tx, TXG_NOWAIT);
3799         if (err != 0) {
3800                 if (err == ERESTART) {
3801                         dmu_tx_wait(tx);
3802                         dmu_tx_abort(tx);
3803                         goto top;
3804                 }
3805                 dmu_tx_abort(tx);
3806                 goto out;
3807         }
3808
3809         if (zp->z_blksz <= PAGESIZE) {
3810                 caddr_t va = zfs_map_page(pp, S_READ);
3811                 ASSERT3U(len, <=, PAGESIZE);
3812                 dmu_write(zfsvfs->z_os, zp->z_id, off, len, va, tx);
3813                 zfs_unmap_page(pp, va);
3814         } else {
3815                 err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, pp, tx);
3816         }
3817
3818         if (err == 0) {
3819                 uint64_t mtime[2], ctime[2];
3820                 sa_bulk_attr_t bulk[3];
3821                 int count = 0;
3822
3823                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
3824                     &mtime, 16);
3825                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
3826                     &ctime, 16);
3827                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
3828                     &zp->z_pflags, 8);
3829                 zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
3830                     B_TRUE);
3831                 zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len, 0);
3832         }
3833         dmu_tx_commit(tx);
3834
3835 out:
3836         pvn_write_done(pp, (err ? B_ERROR : 0) | flags);
3837         if (offp)
3838                 *offp = off;
3839         if (lenp)
3840                 *lenp = len;
3841
3842         return (err);
3843 }
3844
3845 /*
3846  * Copy the portion of the file indicated from pages into the file.
3847  * The pages are stored in a page list attached to the files vnode.
3848  *
3849  *      IN:     vp      - vnode of file to push page data to.
3850  *              off     - position in file to put data.
3851  *              len     - amount of data to write.
3852  *              flags   - flags to control the operation.
3853  *              cr      - credentials of caller.
3854  *              ct      - caller context.
3855  *
3856  *      RETURN: 0 if success
3857  *              error code if failure
3858  *
3859  * Timestamps:
3860  *      vp - ctime|mtime updated
3861  */
3862 /*ARGSUSED*/
3863 static int
3864 zfs_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr)
3865 {
3866         znode_t         *zp = VTOZ(vp);
3867         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
3868         page_t          *pp;
3869         size_t          io_len;
3870         u_offset_t      io_off;
3871         uint_t          blksz;
3872         rl_t            *rl;
3873         int             error = 0;
3874
3875         ZFS_ENTER(zfsvfs);
3876         ZFS_VERIFY_ZP(zp);
3877
3878         /*
3879          * Align this request to the file block size in case we kluster.
3880          * XXX - this can result in pretty aggresive locking, which can
3881          * impact simultanious read/write access.  One option might be
3882          * to break up long requests (len == 0) into block-by-block
3883          * operations to get narrower locking.
3884          */
3885         blksz = zp->z_blksz;
3886         if (ISP2(blksz))
3887                 io_off = P2ALIGN_TYPED(off, blksz, u_offset_t);
3888         else
3889                 io_off = 0;
3890         if (len > 0 && ISP2(blksz))
3891                 io_len = P2ROUNDUP_TYPED(len + (off - io_off), blksz, size_t);
3892         else
3893                 io_len = 0;
3894
3895         if (io_len == 0) {
3896                 /*
3897                  * Search the entire vp list for pages >= io_off.
3898                  */
3899                 rl = zfs_range_lock(zp, io_off, UINT64_MAX, RL_WRITER);
3900                 error = pvn_vplist_dirty(vp, io_off, zfs_putapage, flags, cr);
3901                 goto out;
3902         }
3903         rl = zfs_range_lock(zp, io_off, io_len, RL_WRITER);
3904
3905         if (off > zp->z_size) {
3906                 /* past end of file */
3907                 zfs_range_unlock(rl);
3908                 ZFS_EXIT(zfsvfs);
3909                 return (0);
3910         }
3911
3912         len = MIN(io_len, P2ROUNDUP(zp->z_size, PAGESIZE) - io_off);
3913
3914         for (off = io_off; io_off < off + len; io_off += io_len) {
3915                 if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
3916                         pp = page_lookup(vp, io_off,
3917                             (flags & (B_INVAL | B_FREE)) ? SE_EXCL : SE_SHARED);
3918                 } else {
3919                         pp = page_lookup_nowait(vp, io_off,
3920                             (flags & B_FREE) ? SE_EXCL : SE_SHARED);
3921                 }
3922
3923                 if (pp != NULL && pvn_getdirty(pp, flags)) {
3924                         int err;
3925
3926                         /*
3927                          * Found a dirty page to push
3928                          */
3929                         err = zfs_putapage(vp, pp, &io_off, &io_len, flags, cr);
3930                         if (err)
3931                                 error = err;
3932                 } else {
3933                         io_len = PAGESIZE;
3934                 }
3935         }
3936 out:
3937         zfs_range_unlock(rl);
3938         if ((flags & B_ASYNC) == 0 || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3939                 zil_commit(zfsvfs->z_log, zp->z_id);
3940         ZFS_EXIT(zfsvfs);
3941         return (error);
3942 }
3943 #endif /* HAVE_MMAP */
3944
3945 /*ARGSUSED*/
3946 void
3947 zfs_inactive(struct inode *ip)
3948 {
3949         znode_t *zp = ITOZ(ip);
3950         zfs_sb_t *zsb = ITOZSB(ip);
3951         int error;
3952
3953 #ifdef HAVE_SNAPSHOT
3954         /* Early return for snapshot inode? */
3955 #endif /* HAVE_SNAPSHOT */
3956
3957         rw_enter(&zsb->z_teardown_inactive_lock, RW_READER);
3958         if (zp->z_sa_hdl == NULL) {
3959                 rw_exit(&zsb->z_teardown_inactive_lock);
3960                 return;
3961         }
3962
3963         if (zp->z_atime_dirty && zp->z_unlinked == 0) {
3964                 dmu_tx_t *tx = dmu_tx_create(zsb->z_os);
3965
3966                 dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3967                 zfs_sa_upgrade_txholds(tx, zp);
3968                 error = dmu_tx_assign(tx, TXG_WAIT);
3969                 if (error) {
3970                         dmu_tx_abort(tx);
3971                 } else {
3972                         mutex_enter(&zp->z_lock);
3973                         (void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zsb),
3974                             (void *)&zp->z_atime, sizeof (zp->z_atime), tx);
3975                         zp->z_atime_dirty = 0;
3976                         mutex_exit(&zp->z_lock);
3977                         dmu_tx_commit(tx);
3978                 }
3979         }
3980
3981         zfs_zinactive(zp);
3982         rw_exit(&zsb->z_teardown_inactive_lock);
3983 }
3984 EXPORT_SYMBOL(zfs_inactive);
3985
3986 /*
3987  * Bounds-check the seek operation.
3988  *
3989  *      IN:     ip      - inode seeking within
3990  *              ooff    - old file offset
3991  *              noffp   - pointer to new file offset
3992  *              ct      - caller context
3993  *
3994  *      RETURN: 0 if success
3995  *              EINVAL if new offset invalid
3996  */
3997 /* ARGSUSED */
3998 int
3999 zfs_seek(struct inode *ip, offset_t ooff, offset_t *noffp)
4000 {
4001         if (S_ISDIR(ip->i_mode))
4002                 return (0);
4003         return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
4004 }
4005 EXPORT_SYMBOL(zfs_seek);
4006
4007 #ifdef HAVE_MMAP
4008 /*
4009  * Pre-filter the generic locking function to trap attempts to place
4010  * a mandatory lock on a memory mapped file.
4011  */
4012 static int
4013 zfs_frlock(vnode_t *vp, int cmd, flock64_t *bfp, int flag, offset_t offset,
4014     flk_callback_t *flk_cbp, cred_t *cr)
4015 {
4016         znode_t *zp = VTOZ(vp);
4017         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4018
4019         ZFS_ENTER(zfsvfs);
4020         ZFS_VERIFY_ZP(zp);
4021
4022         /*
4023          * We are following the UFS semantics with respect to mapcnt
4024          * here: If we see that the file is mapped already, then we will
4025          * return an error, but we don't worry about races between this
4026          * function and zfs_map().
4027          */
4028         if (zp->z_mapcnt > 0 && MANDMODE(zp->z_mode)) {
4029                 ZFS_EXIT(zfsvfs);
4030                 return (EAGAIN);
4031         }
4032         ZFS_EXIT(zfsvfs);
4033         return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
4034 }
4035
4036 /*
4037  * If we can't find a page in the cache, we will create a new page
4038  * and fill it with file data.  For efficiency, we may try to fill
4039  * multiple pages at once (klustering) to fill up the supplied page
4040  * list.  Note that the pages to be filled are held with an exclusive
4041  * lock to prevent access by other threads while they are being filled.
4042  */
4043 static int
4044 zfs_fillpage(vnode_t *vp, u_offset_t off, struct seg *seg,
4045     caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw)
4046 {
4047         znode_t *zp = VTOZ(vp);
4048         page_t *pp, *cur_pp;
4049         objset_t *os = zp->z_zfsvfs->z_os;
4050         u_offset_t io_off, total;
4051         size_t io_len;
4052         int err;
4053
4054         if (plsz == PAGESIZE || zp->z_blksz <= PAGESIZE) {
4055                 /*
4056                  * We only have a single page, don't bother klustering
4057                  */
4058                 io_off = off;
4059                 io_len = PAGESIZE;
4060                 pp = page_create_va(vp, io_off, io_len,
4061                     PG_EXCL | PG_WAIT, seg, addr);
4062         } else {
4063                 /*
4064                  * Try to find enough pages to fill the page list
4065                  */
4066                 pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
4067                     &io_len, off, plsz, 0);
4068         }
4069         if (pp == NULL) {
4070                 /*
4071                  * The page already exists, nothing to do here.
4072                  */
4073                 *pl = NULL;
4074                 return (0);
4075         }
4076
4077         /*
4078          * Fill the pages in the kluster.
4079          */
4080         cur_pp = pp;
4081         for (total = io_off + io_len; io_off < total; io_off += PAGESIZE) {
4082                 caddr_t va;
4083
4084                 ASSERT3U(io_off, ==, cur_pp->p_offset);
4085                 va = zfs_map_page(cur_pp, S_WRITE);
4086                 err = dmu_read(os, zp->z_id, io_off, PAGESIZE, va,
4087                     DMU_READ_PREFETCH);
4088                 zfs_unmap_page(cur_pp, va);
4089                 if (err) {
4090                         /* On error, toss the entire kluster */
4091                         pvn_read_done(pp, B_ERROR);
4092                         /* convert checksum errors into IO errors */
4093                         if (err == ECKSUM)
4094                                 err = EIO;
4095                         return (err);
4096                 }
4097                 cur_pp = cur_pp->p_next;
4098         }
4099
4100         /*
4101          * Fill in the page list array from the kluster starting
4102          * from the desired offset `off'.
4103          * NOTE: the page list will always be null terminated.
4104          */
4105         pvn_plist_init(pp, pl, plsz, off, io_len, rw);
4106         ASSERT(pl == NULL || (*pl)->p_offset == off);
4107
4108         return (0);
4109 }
4110
4111 /*
4112  * Return pointers to the pages for the file region [off, off + len]
4113  * in the pl array.  If plsz is greater than len, this function may
4114  * also return page pointers from after the specified region
4115  * (i.e. the region [off, off + plsz]).  These additional pages are
4116  * only returned if they are already in the cache, or were created as
4117  * part of a klustered read.
4118  *
4119  *      IN:     vp      - vnode of file to get data from.
4120  *              off     - position in file to get data from.
4121  *              len     - amount of data to retrieve.
4122  *              plsz    - length of provided page list.
4123  *              seg     - segment to obtain pages for.
4124  *              addr    - virtual address of fault.
4125  *              rw      - mode of created pages.
4126  *              cr      - credentials of caller.
4127  *              ct      - caller context.
4128  *
4129  *      OUT:    protp   - protection mode of created pages.
4130  *              pl      - list of pages created.
4131  *
4132  *      RETURN: 0 if success
4133  *              error code if failure
4134  *
4135  * Timestamps:
4136  *      vp - atime updated
4137  */
4138 /* ARGSUSED */
4139 static int
4140 zfs_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
4141         page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
4142         enum seg_rw rw, cred_t *cr)
4143 {
4144         znode_t         *zp = VTOZ(vp);
4145         zfsvfs_t        *zfsvfs = zp->z_zfsvfs;
4146         page_t          **pl0 = pl;
4147         int             err = 0;
4148
4149         /* we do our own caching, faultahead is unnecessary */
4150         if (pl == NULL)
4151                 return (0);
4152         else if (len > plsz)
4153                 len = plsz;
4154         else
4155                 len = P2ROUNDUP(len, PAGESIZE);
4156         ASSERT(plsz >= len);
4157
4158         ZFS_ENTER(zfsvfs);
4159         ZFS_VERIFY_ZP(zp);
4160
4161         if (protp)
4162                 *protp = PROT_ALL;
4163
4164         /*
4165          * Loop through the requested range [off, off + len) looking
4166          * for pages.  If we don't find a page, we will need to create
4167          * a new page and fill it with data from the file.
4168          */
4169         while (len > 0) {
4170                 if (*pl = page_lookup(vp, off, SE_SHARED))
4171                         *(pl+1) = NULL;
4172                 else if (err = zfs_fillpage(vp, off, seg, addr, pl, plsz, rw))
4173                         goto out;
4174                 while (*pl) {
4175                         ASSERT3U((*pl)->p_offset, ==, off);
4176                         off += PAGESIZE;
4177                         addr += PAGESIZE;
4178                         if (len > 0) {
4179                                 ASSERT3U(len, >=, PAGESIZE);
4180                                 len -= PAGESIZE;
4181                         }
4182                         ASSERT3U(plsz, >=, PAGESIZE);
4183                         plsz -= PAGESIZE;
4184                         pl++;
4185                 }
4186         }
4187
4188         /*
4189          * Fill out the page array with any pages already in the cache.
4190          */
4191         while (plsz > 0 &&
4192             (*pl++ = page_lookup_nowait(vp, off, SE_SHARED))) {
4193                         off += PAGESIZE;
4194                         plsz -= PAGESIZE;
4195         }
4196 out:
4197         if (err) {
4198                 /*
4199                  * Release any pages we have previously locked.
4200                  */
4201                 while (pl > pl0)
4202                         page_unlock(*--pl);
4203         } else {
4204                 ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4205         }
4206
4207         *pl = NULL;
4208
4209         ZFS_EXIT(zfsvfs);
4210         return (err);
4211 }
4212
4213 /*
4214  * Request a memory map for a section of a file.  This code interacts
4215  * with common code and the VM system as follows:
4216  *
4217  *      common code calls mmap(), which ends up in smmap_common()
4218  *
4219  *      this calls VOP_MAP(), which takes you into (say) zfs
4220  *
4221  *      zfs_map() calls as_map(), passing segvn_create() as the callback
4222  *
4223  *      segvn_create() creates the new segment and calls VOP_ADDMAP()
4224  *
4225  *      zfs_addmap() updates z_mapcnt
4226  */
4227 /*ARGSUSED*/
4228 static int
4229 zfs_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
4230     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
4231 {
4232         znode_t *zp = VTOZ(vp);
4233         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4234         segvn_crargs_t  vn_a;
4235         int             error;
4236
4237         ZFS_ENTER(zfsvfs);
4238         ZFS_VERIFY_ZP(zp);
4239
4240         if ((prot & PROT_WRITE) && (zp->z_pflags &
4241             (ZFS_IMMUTABLE | ZFS_READONLY | ZFS_APPENDONLY))) {
4242                 ZFS_EXIT(zfsvfs);
4243                 return (EPERM);
4244         }
4245
4246         if ((prot & (PROT_READ | PROT_EXEC)) &&
4247             (zp->z_pflags & ZFS_AV_QUARANTINED)) {
4248                 ZFS_EXIT(zfsvfs);
4249                 return (EACCES);
4250         }
4251
4252         if (vp->v_flag & VNOMAP) {
4253                 ZFS_EXIT(zfsvfs);
4254                 return (ENOSYS);
4255         }
4256
4257         if (off < 0 || len > MAXOFFSET_T - off) {
4258                 ZFS_EXIT(zfsvfs);
4259                 return (ENXIO);
4260         }
4261
4262         if (vp->v_type != VREG) {
4263                 ZFS_EXIT(zfsvfs);
4264                 return (ENODEV);
4265         }
4266
4267         /*
4268          * If file is locked, disallow mapping.
4269          */
4270         if (MANDMODE(zp->z_mode) && vn_has_flocks(vp)) {
4271                 ZFS_EXIT(zfsvfs);
4272                 return (EAGAIN);
4273         }
4274
4275         as_rangelock(as);
4276         error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
4277         if (error != 0) {
4278                 as_rangeunlock(as);
4279                 ZFS_EXIT(zfsvfs);
4280                 return (error);
4281         }
4282
4283         vn_a.vp = vp;
4284         vn_a.offset = (u_offset_t)off;
4285         vn_a.type = flags & MAP_TYPE;
4286         vn_a.prot = prot;
4287         vn_a.maxprot = maxprot;
4288         vn_a.cred = cr;
4289         vn_a.amp = NULL;
4290         vn_a.flags = flags & ~MAP_TYPE;
4291         vn_a.szc = 0;
4292         vn_a.lgrp_mem_policy_flags = 0;
4293
4294         error = as_map(as, *addrp, len, segvn_create, &vn_a);
4295
4296         as_rangeunlock(as);
4297         ZFS_EXIT(zfsvfs);
4298         return (error);
4299 }
4300
4301 /* ARGSUSED */
4302 static int
4303 zfs_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4304     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
4305 {
4306         uint64_t pages = btopr(len);
4307
4308         atomic_add_64(&VTOZ(vp)->z_mapcnt, pages);
4309         return (0);
4310 }
4311
4312 /*
4313  * The reason we push dirty pages as part of zfs_delmap() is so that we get a
4314  * more accurate mtime for the associated file.  Since we don't have a way of
4315  * detecting when the data was actually modified, we have to resort to
4316  * heuristics.  If an explicit msync() is done, then we mark the mtime when the
4317  * last page is pushed.  The problem occurs when the msync() call is omitted,
4318  * which by far the most common case:
4319  *
4320  *      open()
4321  *      mmap()
4322  *      <modify memory>
4323  *      munmap()
4324  *      close()
4325  *      <time lapse>
4326  *      putpage() via fsflush
4327  *
4328  * If we wait until fsflush to come along, we can have a modification time that
4329  * is some arbitrary point in the future.  In order to prevent this in the
4330  * common case, we flush pages whenever a (MAP_SHARED, PROT_WRITE) mapping is
4331  * torn down.
4332  */
4333 /* ARGSUSED */
4334 static int
4335 zfs_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
4336     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr)
4337 {
4338         uint64_t pages = btopr(len);
4339
4340         ASSERT3U(VTOZ(vp)->z_mapcnt, >=, pages);
4341         atomic_add_64(&VTOZ(vp)->z_mapcnt, -pages);
4342
4343         if ((flags & MAP_SHARED) && (prot & PROT_WRITE) &&
4344             vn_has_cached_data(vp))
4345                 (void) VOP_PUTPAGE(vp, off, len, B_ASYNC, cr, ct);
4346
4347         return (0);
4348 }
4349 #endif /* HAVE_MMAP */
4350
4351 /*
4352  * convoff - converts the given data (start, whence) to the
4353  * given whence.
4354  */
4355 int
4356 convoff(struct inode *ip, flock64_t *lckdat, int  whence, offset_t offset)
4357 {
4358         vattr_t vap;
4359         int error;
4360
4361         if ((lckdat->l_whence == 2) || (whence == 2)) {
4362                 if ((error = zfs_getattr(ip, &vap, 0, CRED()) != 0))
4363                         return (error);
4364         }
4365
4366         switch (lckdat->l_whence) {
4367         case 1:
4368                 lckdat->l_start += offset;
4369                 break;
4370         case 2:
4371                 lckdat->l_start += vap.va_size;
4372                 /* FALLTHRU */
4373         case 0:
4374                 break;
4375         default:
4376                 return (EINVAL);
4377         }
4378
4379         if (lckdat->l_start < 0)
4380                 return (EINVAL);
4381
4382         switch (whence) {
4383         case 1:
4384                 lckdat->l_start -= offset;
4385                 break;
4386         case 2:
4387                 lckdat->l_start -= vap.va_size;
4388                 /* FALLTHRU */
4389         case 0:
4390                 break;
4391         default:
4392                 return (EINVAL);
4393         }
4394
4395         lckdat->l_whence = (short)whence;
4396         return (0);
4397 }
4398
4399 /*
4400  * Free or allocate space in a file.  Currently, this function only
4401  * supports the `F_FREESP' command.  However, this command is somewhat
4402  * misnamed, as its functionality includes the ability to allocate as
4403  * well as free space.
4404  *
4405  *      IN:     ip      - inode of file to free data in.
4406  *              cmd     - action to take (only F_FREESP supported).
4407  *              bfp     - section of file to free/alloc.
4408  *              flag    - current file open mode flags.
4409  *              offset  - current file offset.
4410  *              cr      - credentials of caller [UNUSED].
4411  *
4412  *      RETURN: 0 if success
4413  *              error code if failure
4414  *
4415  * Timestamps:
4416  *      ip - ctime|mtime updated
4417  */
4418 /* ARGSUSED */
4419 int
4420 zfs_space(struct inode *ip, int cmd, flock64_t *bfp, int flag,
4421     offset_t offset, cred_t *cr)
4422 {
4423         znode_t         *zp = ITOZ(ip);
4424         zfs_sb_t        *zsb = ITOZSB(ip);
4425         uint64_t        off, len;
4426         int             error;
4427
4428         ZFS_ENTER(zsb);
4429         ZFS_VERIFY_ZP(zp);
4430
4431         if (cmd != F_FREESP) {
4432                 ZFS_EXIT(zsb);
4433                 return (EINVAL);
4434         }
4435
4436         if ((error = convoff(ip, bfp, 0, offset))) {
4437                 ZFS_EXIT(zsb);
4438                 return (error);
4439         }
4440
4441         if (bfp->l_len < 0) {
4442                 ZFS_EXIT(zsb);
4443                 return (EINVAL);
4444         }
4445
4446         off = bfp->l_start;
4447         len = bfp->l_len; /* 0 means from off to end of file */
4448
4449         error = zfs_freesp(zp, off, len, flag, TRUE);
4450
4451         ZFS_EXIT(zsb);
4452         return (error);
4453 }
4454 EXPORT_SYMBOL(zfs_space);
4455
4456 /*ARGSUSED*/
4457 int
4458 zfs_fid(struct inode *ip, fid_t *fidp)
4459 {
4460         znode_t         *zp = ITOZ(ip);
4461         zfs_sb_t        *zsb = ITOZSB(ip);
4462         uint32_t        gen;
4463         uint64_t        gen64;
4464         uint64_t        object = zp->z_id;
4465         zfid_short_t    *zfid;
4466         int             size, i, error;
4467
4468         ZFS_ENTER(zsb);
4469         ZFS_VERIFY_ZP(zp);
4470
4471         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zsb),
4472             &gen64, sizeof (uint64_t))) != 0) {
4473                 ZFS_EXIT(zsb);
4474                 return (error);
4475         }
4476
4477         gen = (uint32_t)gen64;
4478
4479         size = (zsb->z_parent != zsb) ? LONG_FID_LEN : SHORT_FID_LEN;
4480         if (fidp->fid_len < size) {
4481                 fidp->fid_len = size;
4482                 ZFS_EXIT(zsb);
4483                 return (ENOSPC);
4484         }
4485
4486         zfid = (zfid_short_t *)fidp;
4487
4488         zfid->zf_len = size;
4489
4490         for (i = 0; i < sizeof (zfid->zf_object); i++)
4491                 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
4492
4493         /* Must have a non-zero generation number to distinguish from .zfs */
4494         if (gen == 0)
4495                 gen = 1;
4496         for (i = 0; i < sizeof (zfid->zf_gen); i++)
4497                 zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
4498
4499         if (size == LONG_FID_LEN) {
4500                 uint64_t        objsetid = dmu_objset_id(zsb->z_os);
4501                 zfid_long_t     *zlfid;
4502
4503                 zlfid = (zfid_long_t *)fidp;
4504
4505                 for (i = 0; i < sizeof (zlfid->zf_setid); i++)
4506                         zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
4507
4508                 /* XXX - this should be the generation number for the objset */
4509                 for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
4510                         zlfid->zf_setgen[i] = 0;
4511         }
4512
4513         ZFS_EXIT(zsb);
4514         return (0);
4515 }
4516 EXPORT_SYMBOL(zfs_fid);
4517
4518 /*ARGSUSED*/
4519 int
4520 zfs_getsecattr(struct inode *ip, vsecattr_t *vsecp, int flag, cred_t *cr)
4521 {
4522         znode_t *zp = ITOZ(ip);
4523         zfs_sb_t *zsb = ITOZSB(ip);
4524         int error;
4525         boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
4526
4527         ZFS_ENTER(zsb);
4528         ZFS_VERIFY_ZP(zp);
4529         error = zfs_getacl(zp, vsecp, skipaclchk, cr);
4530         ZFS_EXIT(zsb);
4531
4532         return (error);
4533 }
4534 EXPORT_SYMBOL(zfs_getsecattr);
4535
4536 /*ARGSUSED*/
4537 int
4538 zfs_setsecattr(struct inode *ip, vsecattr_t *vsecp, int flag, cred_t *cr)
4539 {
4540         znode_t *zp = ITOZ(ip);
4541         zfs_sb_t *zsb = ITOZSB(ip);
4542         int error;
4543         boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
4544         zilog_t *zilog = zsb->z_log;
4545
4546         ZFS_ENTER(zsb);
4547         ZFS_VERIFY_ZP(zp);
4548
4549         error = zfs_setacl(zp, vsecp, skipaclchk, cr);
4550
4551         if (zsb->z_os->os_sync == ZFS_SYNC_ALWAYS)
4552                 zil_commit(zilog, 0);
4553
4554         ZFS_EXIT(zsb);
4555         return (error);
4556 }
4557 EXPORT_SYMBOL(zfs_setsecattr);
4558
4559 #ifdef HAVE_UIO_ZEROCOPY
4560 /*
4561  * Tunable, both must be a power of 2.
4562  *
4563  * zcr_blksz_min: the smallest read we may consider to loan out an arcbuf
4564  * zcr_blksz_max: if set to less than the file block size, allow loaning out of
4565  *              an arcbuf for a partial block read
4566  */
4567 int zcr_blksz_min = (1 << 10);  /* 1K */
4568 int zcr_blksz_max = (1 << 17);  /* 128K */
4569
4570 /*ARGSUSED*/
4571 static int
4572 zfs_reqzcbuf(struct inode *ip, enum uio_rw ioflag, xuio_t *xuio, cred_t *cr)
4573 {
4574         znode_t *zp = ITOZ(ip);
4575         zfs_sb_t *zsb = ITOZSB(ip);
4576         int max_blksz = zsb->z_max_blksz;
4577         uio_t *uio = &xuio->xu_uio;
4578         ssize_t size = uio->uio_resid;
4579         offset_t offset = uio->uio_loffset;
4580         int blksz;
4581         int fullblk, i;
4582         arc_buf_t *abuf;
4583         ssize_t maxsize;
4584         int preamble, postamble;
4585
4586         if (xuio->xu_type != UIOTYPE_ZEROCOPY)
4587                 return (EINVAL);
4588
4589         ZFS_ENTER(zsb);
4590         ZFS_VERIFY_ZP(zp);
4591         switch (ioflag) {
4592         case UIO_WRITE:
4593                 /*
4594                  * Loan out an arc_buf for write if write size is bigger than
4595                  * max_blksz, and the file's block size is also max_blksz.
4596                  */
4597                 blksz = max_blksz;
4598                 if (size < blksz || zp->z_blksz != blksz) {
4599                         ZFS_EXIT(zsb);
4600                         return (EINVAL);
4601                 }
4602                 /*
4603                  * Caller requests buffers for write before knowing where the
4604                  * write offset might be (e.g. NFS TCP write).
4605                  */
4606                 if (offset == -1) {
4607                         preamble = 0;
4608                 } else {
4609                         preamble = P2PHASE(offset, blksz);
4610                         if (preamble) {
4611                                 preamble = blksz - preamble;
4612                                 size -= preamble;
4613                         }
4614                 }
4615
4616                 postamble = P2PHASE(size, blksz);
4617                 size -= postamble;
4618
4619                 fullblk = size / blksz;
4620                 (void) dmu_xuio_init(xuio,
4621                     (preamble != 0) + fullblk + (postamble != 0));
4622
4623                 /*
4624                  * Have to fix iov base/len for partial buffers.  They
4625                  * currently represent full arc_buf's.
4626                  */
4627                 if (preamble) {
4628                         /* data begins in the middle of the arc_buf */
4629                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
4630                             blksz);
4631                         ASSERT(abuf);
4632                         (void) dmu_xuio_add(xuio, abuf,
4633                             blksz - preamble, preamble);
4634                 }
4635
4636                 for (i = 0; i < fullblk; i++) {
4637                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
4638                             blksz);
4639                         ASSERT(abuf);
4640                         (void) dmu_xuio_add(xuio, abuf, 0, blksz);
4641                 }
4642
4643                 if (postamble) {
4644                         /* data ends in the middle of the arc_buf */
4645                         abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
4646                             blksz);
4647                         ASSERT(abuf);
4648                         (void) dmu_xuio_add(xuio, abuf, 0, postamble);
4649                 }
4650                 break;
4651         case UIO_READ:
4652                 /*
4653                  * Loan out an arc_buf for read if the read size is larger than
4654                  * the current file block size.  Block alignment is not
4655                  * considered.  Partial arc_buf will be loaned out for read.
4656                  */
4657                 blksz = zp->z_blksz;
4658                 if (blksz < zcr_blksz_min)
4659                         blksz = zcr_blksz_min;
4660                 if (blksz > zcr_blksz_max)
4661                         blksz = zcr_blksz_max;
4662                 /* avoid potential complexity of dealing with it */
4663                 if (blksz > max_blksz) {
4664                         ZFS_EXIT(zsb);
4665                         return (EINVAL);
4666                 }
4667
4668                 maxsize = zp->z_size - uio->uio_loffset;
4669                 if (size > maxsize)
4670                         size = maxsize;
4671
4672                 if (size < blksz) {
4673                         ZFS_EXIT(zsb);
4674                         return (EINVAL);
4675                 }
4676                 break;
4677         default:
4678                 ZFS_EXIT(zsb);
4679                 return (EINVAL);
4680         }
4681
4682         uio->uio_extflg = UIO_XUIO;
4683         XUIO_XUZC_RW(xuio) = ioflag;
4684         ZFS_EXIT(zsb);
4685         return (0);
4686 }
4687
4688 /*ARGSUSED*/
4689 static int
4690 zfs_retzcbuf(struct inode *ip, xuio_t *xuio, cred_t *cr)
4691 {
4692         int i;
4693         arc_buf_t *abuf;
4694         int ioflag = XUIO_XUZC_RW(xuio);
4695
4696         ASSERT(xuio->xu_type == UIOTYPE_ZEROCOPY);
4697
4698         i = dmu_xuio_cnt(xuio);
4699         while (i-- > 0) {
4700                 abuf = dmu_xuio_arcbuf(xuio, i);
4701                 /*
4702                  * if abuf == NULL, it must be a write buffer
4703                  * that has been returned in zfs_write().
4704                  */
4705                 if (abuf)
4706                         dmu_return_arcbuf(abuf);
4707                 ASSERT(abuf || ioflag == UIO_WRITE);
4708         }
4709
4710         dmu_xuio_fini(xuio);
4711         return (0);
4712 }
4713 #endif /* HAVE_UIO_ZEROCOPY */