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