]> CyberLeo.Net >> Repos - FreeBSD/releng/8.0.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_znode.c
Fix BIND named(8) cache poisoning with DNSSEC validation.
[FreeBSD/releng/8.0.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / zfs_znode.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 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25
26 /* Portions Copyright 2007 Jeremy Teo */
27
28 #ifdef _KERNEL
29 #include <sys/types.h>
30 #include <sys/param.h>
31 #include <sys/time.h>
32 #include <sys/systm.h>
33 #include <sys/sysmacros.h>
34 #include <sys/resource.h>
35 #include <sys/mntent.h>
36 #include <sys/u8_textprep.h>
37 #include <sys/dsl_dataset.h>
38 #include <sys/vfs.h>
39 #include <sys/vnode.h>
40 #include <sys/file.h>
41 #include <sys/kmem.h>
42 #include <sys/errno.h>
43 #include <sys/unistd.h>
44 #include <sys/atomic.h>
45 #include <sys/zfs_dir.h>
46 #include <sys/zfs_acl.h>
47 #include <sys/zfs_ioctl.h>
48 #include <sys/zfs_rlock.h>
49 #include <sys/zfs_fuid.h>
50 #include <sys/fs/zfs.h>
51 #include <sys/kidmap.h>
52 #endif /* _KERNEL */
53
54 #include <sys/dmu.h>
55 #include <sys/refcount.h>
56 #include <sys/stat.h>
57 #include <sys/zap.h>
58 #include <sys/zfs_znode.h>
59 #include <sys/refcount.h>
60
61 #include "zfs_prop.h"
62
63 /* Used by fstat(1). */
64 SYSCTL_INT(_debug_sizeof, OID_AUTO, znode, CTLFLAG_RD, 0, sizeof(znode_t),
65     "sizeof(znode_t)");
66
67 /*
68  * Define ZNODE_STATS to turn on statistic gathering. By default, it is only
69  * turned on when DEBUG is also defined.
70  */
71 #ifdef  DEBUG
72 #define ZNODE_STATS
73 #endif  /* DEBUG */
74
75 #ifdef  ZNODE_STATS
76 #define ZNODE_STAT_ADD(stat)                    ((stat)++)
77 #else
78 #define ZNODE_STAT_ADD(stat)                    /* nothing */
79 #endif  /* ZNODE_STATS */
80
81 #define POINTER_IS_VALID(p)     (!((uintptr_t)(p) & 0x3))
82 #define POINTER_INVALIDATE(pp)  (*(pp) = (void *)((uintptr_t)(*(pp)) | 0x1))
83
84 /*
85  * Functions needed for userland (ie: libzpool) are not put under
86  * #ifdef_KERNEL; the rest of the functions have dependencies
87  * (such as VFS logic) that will not compile easily in userland.
88  */
89 #ifdef _KERNEL
90 static kmem_cache_t *znode_cache = NULL;
91
92 /*ARGSUSED*/
93 static void
94 znode_evict_error(dmu_buf_t *dbuf, void *user_ptr)
95 {
96 #if 1   /* XXXPJD: From OpenSolaris. */
97         /*
98          * We should never drop all dbuf refs without first clearing
99          * the eviction callback.
100          */
101         panic("evicting znode %p\n", user_ptr);
102 #else   /* XXXPJD */
103         znode_t *zp = user_ptr;
104         vnode_t *vp;
105
106         mutex_enter(&zp->z_lock);
107         zp->z_dbuf = NULL;
108         vp = ZTOV(zp);
109         if (vp == NULL) {
110                 mutex_exit(&zp->z_lock);
111                 zfs_znode_free(zp);
112         } else if (vp->v_count == 0) {
113                 zp->z_vnode = NULL;
114                 vhold(vp);
115                 mutex_exit(&zp->z_lock);
116                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
117                 vrecycle(vp, curthread);
118                 VOP_UNLOCK(vp, 0);
119                 vdrop(vp);
120                 zfs_znode_free(zp);
121         } else {
122                 mutex_exit(&zp->z_lock);
123         }
124 #endif
125 }
126
127 extern struct vop_vector zfs_vnodeops;
128 extern struct vop_vector zfs_fifoops;
129
130 /*
131  * XXX: We cannot use this function as a cache constructor, because
132  *      there is one global cache for all file systems and we need
133  *      to pass vfsp here, which is not possible, because argument
134  *      'cdrarg' is defined at kmem_cache_create() time.
135  */
136 static int
137 zfs_znode_cache_constructor(void *buf, void *arg, int kmflags)
138 {
139         znode_t *zp = buf;
140         vnode_t *vp;
141         vfs_t *vfsp = arg;
142         int error;
143
144         POINTER_INVALIDATE(&zp->z_zfsvfs);
145         ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
146
147         if (vfsp != NULL) {
148                 error = getnewvnode("zfs", vfsp, &zfs_vnodeops, &vp);
149                 if (error != 0 && (kmflags & KM_NOSLEEP))
150                         return (-1);
151                 ASSERT(error == 0);
152                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
153                 zp->z_vnode = vp;
154                 vp->v_data = (caddr_t)zp;
155                 VN_LOCK_AREC(vp);
156         } else {
157                 zp->z_vnode = NULL;
158         }
159
160         list_link_init(&zp->z_link_node);
161
162         mutex_init(&zp->z_lock, NULL, MUTEX_DEFAULT, NULL);
163         rw_init(&zp->z_map_lock, NULL, RW_DEFAULT, NULL);
164         rw_init(&zp->z_parent_lock, NULL, RW_DEFAULT, NULL);
165         rw_init(&zp->z_name_lock, NULL, RW_DEFAULT, NULL);
166         mutex_init(&zp->z_acl_lock, NULL, MUTEX_DEFAULT, NULL);
167
168         mutex_init(&zp->z_range_lock, NULL, MUTEX_DEFAULT, NULL);
169         avl_create(&zp->z_range_avl, zfs_range_compare,
170             sizeof (rl_t), offsetof(rl_t, r_node));
171
172         zp->z_dbuf = NULL;
173         zp->z_dirlocks = NULL;
174         return (0);
175 }
176
177 /*ARGSUSED*/
178 static void
179 zfs_znode_cache_destructor(void *buf, void *arg)
180 {
181         znode_t *zp = buf;
182
183         ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
184         ASSERT(ZTOV(zp) == NULL);
185         vn_free(ZTOV(zp));
186         ASSERT(!list_link_active(&zp->z_link_node));
187         mutex_destroy(&zp->z_lock);
188         rw_destroy(&zp->z_map_lock);
189         rw_destroy(&zp->z_parent_lock);
190         rw_destroy(&zp->z_name_lock);
191         mutex_destroy(&zp->z_acl_lock);
192         avl_destroy(&zp->z_range_avl);
193         mutex_destroy(&zp->z_range_lock);
194
195         ASSERT(zp->z_dbuf == NULL);
196         ASSERT(zp->z_dirlocks == NULL);
197 }
198
199 #ifdef  ZNODE_STATS
200 static struct {
201         uint64_t zms_zfsvfs_invalid;
202         uint64_t zms_zfsvfs_unmounted;
203         uint64_t zms_zfsvfs_recheck_invalid;
204         uint64_t zms_obj_held;
205         uint64_t zms_vnode_locked;
206         uint64_t zms_not_only_dnlc;
207 } znode_move_stats;
208 #endif  /* ZNODE_STATS */
209
210 #if defined(sun)
211 static void
212 zfs_znode_move_impl(znode_t *ozp, znode_t *nzp)
213 {
214         vnode_t *vp;
215
216         /* Copy fields. */
217         nzp->z_zfsvfs = ozp->z_zfsvfs;
218
219         /* Swap vnodes. */
220         vp = nzp->z_vnode;
221         nzp->z_vnode = ozp->z_vnode;
222         ozp->z_vnode = vp; /* let destructor free the overwritten vnode */
223         ZTOV(ozp)->v_data = ozp;
224         ZTOV(nzp)->v_data = nzp;
225
226         nzp->z_id = ozp->z_id;
227         ASSERT(ozp->z_dirlocks == NULL); /* znode not in use */
228         ASSERT(avl_numnodes(&ozp->z_range_avl) == 0);
229         nzp->z_unlinked = ozp->z_unlinked;
230         nzp->z_atime_dirty = ozp->z_atime_dirty;
231         nzp->z_zn_prefetch = ozp->z_zn_prefetch;
232         nzp->z_blksz = ozp->z_blksz;
233         nzp->z_seq = ozp->z_seq;
234         nzp->z_mapcnt = ozp->z_mapcnt;
235         nzp->z_last_itx = ozp->z_last_itx;
236         nzp->z_gen = ozp->z_gen;
237         nzp->z_sync_cnt = ozp->z_sync_cnt;
238         nzp->z_phys = ozp->z_phys;
239         nzp->z_dbuf = ozp->z_dbuf;
240
241         /* Update back pointers. */
242         (void) dmu_buf_update_user(nzp->z_dbuf, ozp, nzp, &nzp->z_phys,
243             znode_evict_error);
244
245         /*
246          * Invalidate the original znode by clearing fields that provide a
247          * pointer back to the znode. Set the low bit of the vfs pointer to
248          * ensure that zfs_znode_move() recognizes the znode as invalid in any
249          * subsequent callback.
250          */
251         ozp->z_dbuf = NULL;
252         POINTER_INVALIDATE(&ozp->z_zfsvfs);
253 }
254
255 /*
256  * Wrapper function for ZFS_ENTER that returns 0 if successful and otherwise
257  * returns a non-zero error code.
258  */
259 static int
260 zfs_enter(zfsvfs_t *zfsvfs)
261 {
262         ZFS_ENTER(zfsvfs);
263         return (0);
264 }
265
266 /*ARGSUSED*/
267 static kmem_cbrc_t
268 zfs_znode_move(void *buf, void *newbuf, size_t size, void *arg)
269 {
270         znode_t *ozp = buf, *nzp = newbuf;
271         zfsvfs_t *zfsvfs;
272         vnode_t *vp;
273
274         /*
275          * The znode is on the file system's list of known znodes if the vfs
276          * pointer is valid. We set the low bit of the vfs pointer when freeing
277          * the znode to invalidate it, and the memory patterns written by kmem
278          * (baddcafe and deadbeef) set at least one of the two low bits. A newly
279          * created znode sets the vfs pointer last of all to indicate that the
280          * znode is known and in a valid state to be moved by this function.
281          */
282         zfsvfs = ozp->z_zfsvfs;
283         if (!POINTER_IS_VALID(zfsvfs)) {
284                 ZNODE_STAT_ADD(znode_move_stats.zms_zfsvfs_invalid);
285                 return (KMEM_CBRC_DONT_KNOW);
286         }
287
288         /*
289          * Ensure that the filesystem is not unmounted during the move.
290          */
291         if (zfs_enter(zfsvfs) != 0) {           /* ZFS_ENTER */
292                 ZNODE_STAT_ADD(znode_move_stats.zms_zfsvfs_unmounted);
293                 return (KMEM_CBRC_DONT_KNOW);
294         }
295
296         mutex_enter(&zfsvfs->z_znodes_lock);
297         /*
298          * Recheck the vfs pointer in case the znode was removed just before
299          * acquiring the lock.
300          */
301         if (zfsvfs != ozp->z_zfsvfs) {
302                 mutex_exit(&zfsvfs->z_znodes_lock);
303                 ZFS_EXIT(zfsvfs);
304                 ZNODE_STAT_ADD(znode_move_stats.zms_zfsvfs_recheck_invalid);
305                 return (KMEM_CBRC_DONT_KNOW);
306         }
307
308         /*
309          * At this point we know that as long as we hold z_znodes_lock, the
310          * znode cannot be freed and fields within the znode can be safely
311          * accessed. Now, prevent a race with zfs_zget().
312          */
313         if (ZFS_OBJ_HOLD_TRYENTER(zfsvfs, ozp->z_id) == 0) {
314                 mutex_exit(&zfsvfs->z_znodes_lock);
315                 ZFS_EXIT(zfsvfs);
316                 ZNODE_STAT_ADD(znode_move_stats.zms_obj_held);
317                 return (KMEM_CBRC_LATER);
318         }
319
320         vp = ZTOV(ozp);
321         if (mutex_tryenter(&vp->v_lock) == 0) {
322                 ZFS_OBJ_HOLD_EXIT(zfsvfs, ozp->z_id);
323                 mutex_exit(&zfsvfs->z_znodes_lock);
324                 ZFS_EXIT(zfsvfs);
325                 ZNODE_STAT_ADD(znode_move_stats.zms_vnode_locked);
326                 return (KMEM_CBRC_LATER);
327         }
328
329         /* Only move znodes that are referenced _only_ by the DNLC. */
330         if (vp->v_count != 1 || !vn_in_dnlc(vp)) {
331                 mutex_exit(&vp->v_lock);
332                 ZFS_OBJ_HOLD_EXIT(zfsvfs, ozp->z_id);
333                 mutex_exit(&zfsvfs->z_znodes_lock);
334                 ZFS_EXIT(zfsvfs);
335                 ZNODE_STAT_ADD(znode_move_stats.zms_not_only_dnlc);
336                 return (KMEM_CBRC_LATER);
337         }
338
339         /*
340          * The znode is known and in a valid state to move. We're holding the
341          * locks needed to execute the critical section.
342          */
343         zfs_znode_move_impl(ozp, nzp);
344         mutex_exit(&vp->v_lock);
345         ZFS_OBJ_HOLD_EXIT(zfsvfs, ozp->z_id);
346
347         list_link_replace(&ozp->z_link_node, &nzp->z_link_node);
348         mutex_exit(&zfsvfs->z_znodes_lock);
349         ZFS_EXIT(zfsvfs);
350
351         return (KMEM_CBRC_YES);
352 }
353 #endif /* sun */
354
355 void
356 zfs_znode_init(void)
357 {
358         /*
359          * Initialize zcache
360          */
361         ASSERT(znode_cache == NULL);
362         znode_cache = kmem_cache_create("zfs_znode_cache",
363             sizeof (znode_t), 0, /* zfs_znode_cache_constructor */ NULL,
364             zfs_znode_cache_destructor, NULL, NULL, NULL, 0);
365 #if defined(sun)
366         kmem_cache_set_move(znode_cache, zfs_znode_move);
367 #endif
368 }
369
370 void
371 zfs_znode_fini(void)
372 {
373         /*
374          * Cleanup zcache
375          */
376         if (znode_cache)
377                 kmem_cache_destroy(znode_cache);
378         znode_cache = NULL;
379 }
380
381 /*
382  * zfs_init_fs - Initialize the zfsvfs struct and the file system
383  *      incore "master" object.  Verify version compatibility.
384  */
385 int
386 zfs_init_fs(zfsvfs_t *zfsvfs, znode_t **zpp)
387 {
388         objset_t        *os = zfsvfs->z_os;
389         int             i, error;
390         uint64_t fsid_guid;
391         uint64_t zval;
392
393         *zpp = NULL;
394
395         error = zfs_get_zplprop(os, ZFS_PROP_VERSION, &zfsvfs->z_version);
396         if (error) {
397                 return (error);
398         } else if (zfsvfs->z_version > ZPL_VERSION) {
399                 (void) printf("Mismatched versions:  File system "
400                     "is version %llu on-disk format, which is "
401                     "incompatible with this software version %lld!",
402                     (u_longlong_t)zfsvfs->z_version, ZPL_VERSION);
403                 return (ENOTSUP);
404         }
405
406         if ((error = zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &zval)) != 0)
407                 return (error);
408         zfsvfs->z_norm = (int)zval;
409         if ((error = zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &zval)) != 0)
410                 return (error);
411         zfsvfs->z_utf8 = (zval != 0);
412         if ((error = zfs_get_zplprop(os, ZFS_PROP_CASE, &zval)) != 0)
413                 return (error);
414         zfsvfs->z_case = (uint_t)zval;
415         /*
416          * Fold case on file systems that are always or sometimes case
417          * insensitive.
418          */
419         if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
420             zfsvfs->z_case == ZFS_CASE_MIXED)
421                 zfsvfs->z_norm |= U8_TEXTPREP_TOUPPER;
422
423         /*
424          * The fsid is 64 bits, composed of an 8-bit fs type, which
425          * separates our fsid from any other filesystem types, and a
426          * 56-bit objset unique ID.  The objset unique ID is unique to
427          * all objsets open on this system, provided by unique_create().
428          * The 8-bit fs type must be put in the low bits of fsid[1]
429          * because that's where other Solaris filesystems put it.
430          */
431         fsid_guid = dmu_objset_fsid_guid(os);
432         ASSERT((fsid_guid & ~((1ULL<<56)-1)) == 0);
433         zfsvfs->z_vfs->vfs_fsid.val[0] = fsid_guid;
434         zfsvfs->z_vfs->vfs_fsid.val[1] = ((fsid_guid>>32) << 8) |
435             zfsvfs->z_vfs->mnt_vfc->vfc_typenum & 0xFF;
436
437         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1,
438             &zfsvfs->z_root);
439         if (error)
440                 return (error);
441         ASSERT(zfsvfs->z_root != 0);
442
443         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_UNLINKED_SET, 8, 1,
444             &zfsvfs->z_unlinkedobj);
445         if (error)
446                 return (error);
447
448         /*
449          * Initialize zget mutex's
450          */
451         for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
452                 mutex_init(&zfsvfs->z_hold_mtx[i], NULL, MUTEX_DEFAULT, NULL);
453
454         error = zfs_zget(zfsvfs, zfsvfs->z_root, zpp);
455         if (error) {
456                 /*
457                  * On error, we destroy the mutexes here since it's not
458                  * possible for the caller to determine if the mutexes were
459                  * initialized properly.
460                  */
461                 for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
462                         mutex_destroy(&zfsvfs->z_hold_mtx[i]);
463                 return (error);
464         }
465         ASSERT3U((*zpp)->z_id, ==, zfsvfs->z_root);
466         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES, 8, 1,
467             &zfsvfs->z_fuid_obj);
468         if (error == ENOENT)
469                 error = 0;
470
471         return (0);
472 }
473
474 /*
475  * define a couple of values we need available
476  * for both 64 and 32 bit environments.
477  */
478 #ifndef NBITSMINOR64
479 #define NBITSMINOR64    32
480 #endif
481 #ifndef MAXMAJ64
482 #define MAXMAJ64        0xffffffffUL
483 #endif
484 #ifndef MAXMIN64
485 #define MAXMIN64        0xffffffffUL
486 #endif
487
488 /*
489  * Create special expldev for ZFS private use.
490  * Can't use standard expldev since it doesn't do
491  * what we want.  The standard expldev() takes a
492  * dev32_t in LP64 and expands it to a long dev_t.
493  * We need an interface that takes a dev32_t in ILP32
494  * and expands it to a long dev_t.
495  */
496 static uint64_t
497 zfs_expldev(dev_t dev)
498 {
499         return (((uint64_t)major(dev) << NBITSMINOR64) | minor(dev));
500 }
501 /*
502  * Special cmpldev for ZFS private use.
503  * Can't use standard cmpldev since it takes
504  * a long dev_t and compresses it to dev32_t in
505  * LP64.  We need to do a compaction of a long dev_t
506  * to a dev32_t in ILP32.
507  */
508 dev_t
509 zfs_cmpldev(uint64_t dev)
510 {
511         return (makedev((dev >> NBITSMINOR64), (dev & MAXMIN64)));
512 }
513
514 static void
515 zfs_znode_dmu_init(zfsvfs_t *zfsvfs, znode_t *zp, dmu_buf_t *db)
516 {
517         znode_t         *nzp;
518
519         ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs) || (zfsvfs == zp->z_zfsvfs));
520         ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zfsvfs, zp->z_id)));
521
522         mutex_enter(&zp->z_lock);
523
524         ASSERT(zp->z_dbuf == NULL);
525         zp->z_dbuf = db;
526         nzp = dmu_buf_set_user_ie(db, zp, &zp->z_phys, znode_evict_error);
527
528         /*
529          * there should be no
530          * concurrent zgets on this object.
531          */
532         if (nzp != NULL)
533                 panic("existing znode %p for dbuf %p", (void *)nzp, (void *)db);
534
535         /*
536          * Slap on VROOT if we are the root znode
537          */
538         if (zp->z_id == zfsvfs->z_root)
539                 ZTOV(zp)->v_flag |= VROOT;
540
541         mutex_exit(&zp->z_lock);
542         vn_exists(ZTOV(zp));
543 }
544
545 void
546 zfs_znode_dmu_fini(znode_t *zp)
547 {
548         dmu_buf_t *db = zp->z_dbuf;
549         ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zp->z_zfsvfs, zp->z_id)) ||
550             zp->z_unlinked ||
551             RW_WRITE_HELD(&zp->z_zfsvfs->z_teardown_inactive_lock));
552         ASSERT(zp->z_dbuf != NULL);
553         zp->z_dbuf = NULL;
554         VERIFY(zp == dmu_buf_update_user(db, zp, NULL, NULL, NULL));
555         dmu_buf_rele(db, NULL);
556 }
557
558 /*
559  * Construct a new znode/vnode and intialize.
560  *
561  * This does not do a call to dmu_set_user() that is
562  * up to the caller to do, in case you don't want to
563  * return the znode
564  */
565 static znode_t *
566 zfs_znode_alloc(zfsvfs_t *zfsvfs, dmu_buf_t *db, int blksz)
567 {
568         znode_t *zp;
569         vnode_t *vp;
570
571         zp = kmem_cache_alloc(znode_cache, KM_SLEEP);
572         zfs_znode_cache_constructor(zp, zfsvfs->z_parent->z_vfs, 0);
573
574         ASSERT(zp->z_dirlocks == NULL);
575         ASSERT(zp->z_dbuf == NULL);
576         ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
577
578         /*
579          * Defer setting z_zfsvfs until the znode is ready to be a candidate for
580          * the zfs_znode_move() callback.
581          */
582         zp->z_phys = NULL;
583         zp->z_unlinked = 0;
584         zp->z_atime_dirty = 0;
585         zp->z_mapcnt = 0;
586         zp->z_last_itx = 0;
587         zp->z_id = db->db_object;
588         zp->z_blksz = blksz;
589         zp->z_seq = 0x7A4653;
590         zp->z_sync_cnt = 0;
591
592         vp = ZTOV(zp);
593 #ifdef TODO
594         vn_reinit(vp);
595 #endif
596
597         zfs_znode_dmu_init(zfsvfs, zp, db);
598
599         zp->z_gen = zp->z_phys->zp_gen;
600
601 #if 0
602         if (vp == NULL)
603                 return (zp);
604 #endif
605
606         vp->v_type = IFTOVT((mode_t)zp->z_phys->zp_mode);
607         switch (vp->v_type) {
608         case VDIR:
609                 zp->z_zn_prefetch = B_TRUE; /* z_prefetch default is enabled */
610                 break;
611         case VFIFO:
612                 vp->v_op = &zfs_fifoops;
613                 break;
614         }
615         if (vp->v_type != VFIFO)
616                 VN_LOCK_ASHARE(vp);
617
618         mutex_enter(&zfsvfs->z_znodes_lock);
619         list_insert_tail(&zfsvfs->z_all_znodes, zp);
620         membar_producer();
621         /*
622          * Everything else must be valid before assigning z_zfsvfs makes the
623          * znode eligible for zfs_znode_move().
624          */
625         zp->z_zfsvfs = zfsvfs;
626         mutex_exit(&zfsvfs->z_znodes_lock);
627
628         VFS_HOLD(zfsvfs->z_vfs);
629         return (zp);
630 }
631
632 /*
633  * Create a new DMU object to hold a zfs znode.
634  *
635  *      IN:     dzp     - parent directory for new znode
636  *              vap     - file attributes for new znode
637  *              tx      - dmu transaction id for zap operations
638  *              cr      - credentials of caller
639  *              flag    - flags:
640  *                        IS_ROOT_NODE  - new object will be root
641  *                        IS_XATTR      - new object is an attribute
642  *                        IS_REPLAY     - intent log replay
643  *              bonuslen - length of bonus buffer
644  *              setaclp  - File/Dir initial ACL
645  *              fuidp    - Tracks fuid allocation.
646  *
647  *      OUT:    zpp     - allocated znode
648  *
649  */
650 void
651 zfs_mknode(znode_t *dzp, vattr_t *vap, dmu_tx_t *tx, cred_t *cr,
652     uint_t flag, znode_t **zpp, int bonuslen, zfs_acl_t *setaclp,
653     zfs_fuid_info_t **fuidp)
654 {
655         dmu_buf_t       *db;
656         znode_phys_t    *pzp;
657         zfsvfs_t        *zfsvfs = dzp->z_zfsvfs;
658         timestruc_t     now;
659         uint64_t        gen, obj;
660         int             err;
661
662         ASSERT(vap && (vap->va_mask & (AT_TYPE|AT_MODE)) == (AT_TYPE|AT_MODE));
663
664         if (zfsvfs->z_assign >= TXG_INITIAL) {          /* ZIL replay */
665                 obj = vap->va_nodeid;
666                 flag |= IS_REPLAY;
667                 now = vap->va_ctime;            /* see zfs_replay_create() */
668                 gen = vap->va_nblocks;          /* ditto */
669         } else {
670                 obj = 0;
671                 gethrestime(&now);
672                 gen = dmu_tx_get_txg(tx);
673         }
674
675         /*
676          * Create a new DMU object.
677          */
678         /*
679          * There's currently no mechanism for pre-reading the blocks that will
680          * be to needed allocate a new object, so we accept the small chance
681          * that there will be an i/o error and we will fail one of the
682          * assertions below.
683          */
684         if (vap->va_type == VDIR) {
685                 if (flag & IS_REPLAY) {
686                         err = zap_create_claim_norm(zfsvfs->z_os, obj,
687                             zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
688                             DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
689                         ASSERT3U(err, ==, 0);
690                 } else {
691                         obj = zap_create_norm(zfsvfs->z_os,
692                             zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
693                             DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
694                 }
695         } else {
696                 if (flag & IS_REPLAY) {
697                         err = dmu_object_claim(zfsvfs->z_os, obj,
698                             DMU_OT_PLAIN_FILE_CONTENTS, 0,
699                             DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
700                         ASSERT3U(err, ==, 0);
701                 } else {
702                         obj = dmu_object_alloc(zfsvfs->z_os,
703                             DMU_OT_PLAIN_FILE_CONTENTS, 0,
704                             DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
705                 }
706         }
707         VERIFY(0 == dmu_bonus_hold(zfsvfs->z_os, obj, NULL, &db));
708         dmu_buf_will_dirty(db, tx);
709
710         /*
711          * Initialize the znode physical data to zero.
712          */
713         ASSERT(db->db_size >= sizeof (znode_phys_t));
714         bzero(db->db_data, db->db_size);
715         pzp = db->db_data;
716
717         /*
718          * If this is the root, fix up the half-initialized parent pointer
719          * to reference the just-allocated physical data area.
720          */
721         if (flag & IS_ROOT_NODE) {
722                 dzp->z_dbuf = db;
723                 dzp->z_phys = pzp;
724                 dzp->z_id = obj;
725         }
726
727         /*
728          * If parent is an xattr, so am I.
729          */
730         if (dzp->z_phys->zp_flags & ZFS_XATTR)
731                 flag |= IS_XATTR;
732
733         if (vap->va_type == VBLK || vap->va_type == VCHR) {
734                 pzp->zp_rdev = zfs_expldev(vap->va_rdev);
735         }
736
737         if (zfsvfs->z_use_fuids)
738                 pzp->zp_flags = ZFS_ARCHIVE | ZFS_AV_MODIFIED;
739
740         if (vap->va_type == VDIR) {
741                 pzp->zp_size = 2;               /* contents ("." and "..") */
742                 pzp->zp_links = (flag & (IS_ROOT_NODE | IS_XATTR)) ? 2 : 1;
743         }
744
745         pzp->zp_parent = dzp->z_id;
746         if (flag & IS_XATTR)
747                 pzp->zp_flags |= ZFS_XATTR;
748
749         pzp->zp_gen = gen;
750
751         ZFS_TIME_ENCODE(&now, pzp->zp_crtime);
752         ZFS_TIME_ENCODE(&now, pzp->zp_ctime);
753
754         if (vap->va_mask & AT_ATIME) {
755                 ZFS_TIME_ENCODE(&vap->va_atime, pzp->zp_atime);
756         } else {
757                 ZFS_TIME_ENCODE(&now, pzp->zp_atime);
758         }
759
760         if (vap->va_mask & AT_MTIME) {
761                 ZFS_TIME_ENCODE(&vap->va_mtime, pzp->zp_mtime);
762         } else {
763                 ZFS_TIME_ENCODE(&now, pzp->zp_mtime);
764         }
765
766         pzp->zp_mode = MAKEIMODE(vap->va_type, vap->va_mode);
767         if (!(flag & IS_ROOT_NODE)) {
768                 ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
769                 *zpp = zfs_znode_alloc(zfsvfs, db, 0);
770                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
771         } else {
772                 /*
773                  * If we are creating the root node, the "parent" we
774                  * passed in is the znode for the root.
775                  */
776                 *zpp = dzp;
777         }
778         zfs_perm_init(*zpp, dzp, flag, vap, tx, cr, setaclp, fuidp);
779         if (!(flag & IS_ROOT_NODE)) {
780                 vnode_t *vp;
781
782                 vp = ZTOV(*zpp);
783                 vp->v_vflag |= VV_FORCEINSMQ;
784                 err = insmntque(vp, zfsvfs->z_vfs);
785                 vp->v_vflag &= ~VV_FORCEINSMQ;
786                 KASSERT(err == 0, ("insmntque() failed: error %d", err));
787         }
788 }
789
790 void
791 zfs_xvattr_set(znode_t *zp, xvattr_t *xvap)
792 {
793         xoptattr_t *xoap;
794
795         xoap = xva_getxoptattr(xvap);
796         ASSERT(xoap);
797
798         if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
799                 ZFS_TIME_ENCODE(&xoap->xoa_createtime, zp->z_phys->zp_crtime);
800                 XVA_SET_RTN(xvap, XAT_CREATETIME);
801         }
802         if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
803                 ZFS_ATTR_SET(zp, ZFS_READONLY, xoap->xoa_readonly);
804                 XVA_SET_RTN(xvap, XAT_READONLY);
805         }
806         if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
807                 ZFS_ATTR_SET(zp, ZFS_HIDDEN, xoap->xoa_hidden);
808                 XVA_SET_RTN(xvap, XAT_HIDDEN);
809         }
810         if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
811                 ZFS_ATTR_SET(zp, ZFS_SYSTEM, xoap->xoa_system);
812                 XVA_SET_RTN(xvap, XAT_SYSTEM);
813         }
814         if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
815                 ZFS_ATTR_SET(zp, ZFS_ARCHIVE, xoap->xoa_archive);
816                 XVA_SET_RTN(xvap, XAT_ARCHIVE);
817         }
818         if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
819                 ZFS_ATTR_SET(zp, ZFS_IMMUTABLE, xoap->xoa_immutable);
820                 XVA_SET_RTN(xvap, XAT_IMMUTABLE);
821         }
822         if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
823                 ZFS_ATTR_SET(zp, ZFS_NOUNLINK, xoap->xoa_nounlink);
824                 XVA_SET_RTN(xvap, XAT_NOUNLINK);
825         }
826         if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
827                 ZFS_ATTR_SET(zp, ZFS_APPENDONLY, xoap->xoa_appendonly);
828                 XVA_SET_RTN(xvap, XAT_APPENDONLY);
829         }
830         if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
831                 ZFS_ATTR_SET(zp, ZFS_NODUMP, xoap->xoa_nodump);
832                 XVA_SET_RTN(xvap, XAT_NODUMP);
833         }
834         if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
835                 ZFS_ATTR_SET(zp, ZFS_OPAQUE, xoap->xoa_opaque);
836                 XVA_SET_RTN(xvap, XAT_OPAQUE);
837         }
838         if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
839                 ZFS_ATTR_SET(zp, ZFS_AV_QUARANTINED,
840                     xoap->xoa_av_quarantined);
841                 XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
842         }
843         if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
844                 ZFS_ATTR_SET(zp, ZFS_AV_MODIFIED, xoap->xoa_av_modified);
845                 XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
846         }
847         if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
848                 (void) memcpy(zp->z_phys + 1, xoap->xoa_av_scanstamp,
849                     sizeof (xoap->xoa_av_scanstamp));
850                 zp->z_phys->zp_flags |= ZFS_BONUS_SCANSTAMP;
851                 XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
852         }
853 }
854
855 int
856 zfs_zget(zfsvfs_t *zfsvfs, uint64_t obj_num, znode_t **zpp)
857 {
858         dmu_object_info_t doi;
859         dmu_buf_t       *db;
860         znode_t         *zp;
861         vnode_t         *vp;
862         int err, first = 1;
863
864         *zpp = NULL;
865 again:
866         ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
867
868         err = dmu_bonus_hold(zfsvfs->z_os, obj_num, NULL, &db);
869         if (err) {
870                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
871                 return (err);
872         }
873
874         dmu_object_info_from_db(db, &doi);
875         if (doi.doi_bonus_type != DMU_OT_ZNODE ||
876             doi.doi_bonus_size < sizeof (znode_phys_t)) {
877                 dmu_buf_rele(db, NULL);
878                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
879                 return (EINVAL);
880         }
881
882         zp = dmu_buf_get_user(db);
883         if (zp != NULL) {
884                 mutex_enter(&zp->z_lock);
885
886                 /*
887                  * Since we do immediate eviction of the z_dbuf, we
888                  * should never find a dbuf with a znode that doesn't
889                  * know about the dbuf.
890                  */
891                 ASSERT3P(zp->z_dbuf, ==, db);
892                 ASSERT3U(zp->z_id, ==, obj_num);
893                 if (zp->z_unlinked) {
894                         err = ENOENT;
895                 } else {
896                         int dying = 0;
897
898                         vp = ZTOV(zp);
899                         if (vp == NULL)
900                                 dying = 1;
901                         else {
902                                 VN_HOLD(vp);
903                                 if ((vp->v_iflag & VI_DOOMED) != 0) {
904                                         dying = 1;
905                                         /*
906                                          * Don't VN_RELE() vnode here, because
907                                          * it can call vn_lock() which creates
908                                          * LOR between vnode lock and znode
909                                          * lock. We will VN_RELE() the vnode
910                                          * after droping znode lock.
911                                          */
912                                 }
913                         }
914                         if (dying) {
915                                 if (first) {
916                                         ZFS_LOG(1, "dying znode detected (zp=%p)", zp);
917                                         first = 0;
918                                 }
919                                 /*
920                                  * znode is dying so we can't reuse it, we must
921                                  * wait until destruction is completed.
922                                  */
923                                 dmu_buf_rele(db, NULL);
924                                 mutex_exit(&zp->z_lock);
925                                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
926                                 if (vp != NULL)
927                                         VN_RELE(vp);
928                                 tsleep(zp, 0, "zcollide", 1);
929                                 goto again;
930                         }
931                         *zpp = zp;
932                         err = 0;
933                 }
934                 dmu_buf_rele(db, NULL);
935                 mutex_exit(&zp->z_lock);
936                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
937                 return (err);
938         }
939
940         /*
941          * Not found create new znode/vnode
942          */
943         zp = zfs_znode_alloc(zfsvfs, db, doi.doi_data_block_size);
944
945         vp = ZTOV(zp);
946         vp->v_vflag |= VV_FORCEINSMQ;
947         err = insmntque(vp, zfsvfs->z_vfs);
948         vp->v_vflag &= ~VV_FORCEINSMQ;
949         KASSERT(err == 0, ("insmntque() failed: error %d", err));
950         VOP_UNLOCK(vp, 0);
951
952         ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
953         *zpp = zp;
954         return (0);
955 }
956
957 int
958 zfs_rezget(znode_t *zp)
959 {
960         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
961         dmu_object_info_t doi;
962         dmu_buf_t *db;
963         uint64_t obj_num = zp->z_id;
964         int err;
965
966         ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
967
968         err = dmu_bonus_hold(zfsvfs->z_os, obj_num, NULL, &db);
969         if (err) {
970                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
971                 return (err);
972         }
973
974         dmu_object_info_from_db(db, &doi);
975         if (doi.doi_bonus_type != DMU_OT_ZNODE ||
976             doi.doi_bonus_size < sizeof (znode_phys_t)) {
977                 dmu_buf_rele(db, NULL);
978                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
979                 return (EINVAL);
980         }
981
982         if (((znode_phys_t *)db->db_data)->zp_gen != zp->z_gen) {
983                 dmu_buf_rele(db, NULL);
984                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
985                 return (EIO);
986         }
987
988         zfs_znode_dmu_init(zfsvfs, zp, db);
989         zp->z_unlinked = (zp->z_phys->zp_links == 0);
990         zp->z_blksz = doi.doi_data_block_size;
991
992         ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
993
994         return (0);
995 }
996
997 void
998 zfs_znode_delete(znode_t *zp, dmu_tx_t *tx)
999 {
1000         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1001         objset_t *os = zfsvfs->z_os;
1002         uint64_t obj = zp->z_id;
1003         uint64_t acl_obj = zp->z_phys->zp_acl.z_acl_extern_obj;
1004
1005         ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
1006         if (acl_obj)
1007                 VERIFY(0 == dmu_object_free(os, acl_obj, tx));
1008         VERIFY(0 == dmu_object_free(os, obj, tx));
1009         zfs_znode_dmu_fini(zp);
1010         ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
1011         zfs_znode_free(zp);
1012 }
1013
1014 void
1015 zfs_zinactive(znode_t *zp)
1016 {
1017         vnode_t *vp = ZTOV(zp);
1018         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1019         uint64_t z_id = zp->z_id;
1020
1021         ASSERT(zp->z_dbuf && zp->z_phys);
1022
1023         /*
1024          * Don't allow a zfs_zget() while were trying to release this znode
1025          */
1026         ZFS_OBJ_HOLD_ENTER(zfsvfs, z_id);
1027
1028         mutex_enter(&zp->z_lock);
1029         VI_LOCK(vp);
1030         if (vp->v_count > 0) {
1031                 /*
1032                  * If the hold count is greater than zero, somebody has
1033                  * obtained a new reference on this znode while we were
1034                  * processing it here, so we are done.
1035                  */
1036                 VI_UNLOCK(vp);
1037                 mutex_exit(&zp->z_lock);
1038                 ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1039                 return;
1040         }
1041         VI_UNLOCK(vp);
1042
1043         /*
1044          * If this was the last reference to a file with no links,
1045          * remove the file from the file system.
1046          */
1047         if (zp->z_unlinked) {
1048                 mutex_exit(&zp->z_lock);
1049                 ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1050                 ASSERT(vp->v_count == 0);
1051                 vrecycle(vp, curthread);
1052                 zfs_rmnode(zp);
1053                 return;
1054         }
1055         mutex_exit(&zp->z_lock);
1056         ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1057 }
1058
1059 void
1060 zfs_znode_free(znode_t *zp)
1061 {
1062         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1063
1064         ASSERT(ZTOV(zp) == NULL);
1065         mutex_enter(&zfsvfs->z_znodes_lock);
1066         POINTER_INVALIDATE(&zp->z_zfsvfs);
1067         list_remove(&zfsvfs->z_all_znodes, zp);
1068         mutex_exit(&zfsvfs->z_znodes_lock);
1069
1070         kmem_cache_free(znode_cache, zp);
1071
1072         VFS_RELE(zfsvfs->z_vfs);
1073 }
1074
1075 void
1076 zfs_time_stamper_locked(znode_t *zp, uint_t flag, dmu_tx_t *tx)
1077 {
1078         timestruc_t     now;
1079
1080         ASSERT(MUTEX_HELD(&zp->z_lock));
1081
1082         gethrestime(&now);
1083
1084         if (tx) {
1085                 dmu_buf_will_dirty(zp->z_dbuf, tx);
1086                 zp->z_atime_dirty = 0;
1087                 zp->z_seq++;
1088         } else {
1089                 zp->z_atime_dirty = 1;
1090         }
1091
1092         if (flag & AT_ATIME)
1093                 ZFS_TIME_ENCODE(&now, zp->z_phys->zp_atime);
1094
1095         if (flag & AT_MTIME) {
1096                 ZFS_TIME_ENCODE(&now, zp->z_phys->zp_mtime);
1097                 if (zp->z_zfsvfs->z_use_fuids)
1098                         zp->z_phys->zp_flags |= (ZFS_ARCHIVE | ZFS_AV_MODIFIED);
1099         }
1100
1101         if (flag & AT_CTIME) {
1102                 ZFS_TIME_ENCODE(&now, zp->z_phys->zp_ctime);
1103                 if (zp->z_zfsvfs->z_use_fuids)
1104                         zp->z_phys->zp_flags |= ZFS_ARCHIVE;
1105         }
1106 }
1107
1108 /*
1109  * Update the requested znode timestamps with the current time.
1110  * If we are in a transaction, then go ahead and mark the znode
1111  * dirty in the transaction so the timestamps will go to disk.
1112  * Otherwise, we will get pushed next time the znode is updated
1113  * in a transaction, or when this znode eventually goes inactive.
1114  *
1115  * Why is this OK?
1116  *  1 - Only the ACCESS time is ever updated outside of a transaction.
1117  *  2 - Multiple consecutive updates will be collapsed into a single
1118  *      znode update by the transaction grouping semantics of the DMU.
1119  */
1120 void
1121 zfs_time_stamper(znode_t *zp, uint_t flag, dmu_tx_t *tx)
1122 {
1123         mutex_enter(&zp->z_lock);
1124         zfs_time_stamper_locked(zp, flag, tx);
1125         mutex_exit(&zp->z_lock);
1126 }
1127
1128 /*
1129  * Grow the block size for a file.
1130  *
1131  *      IN:     zp      - znode of file to free data in.
1132  *              size    - requested block size
1133  *              tx      - open transaction.
1134  *
1135  * NOTE: this function assumes that the znode is write locked.
1136  */
1137 void
1138 zfs_grow_blocksize(znode_t *zp, uint64_t size, dmu_tx_t *tx)
1139 {
1140         int             error;
1141         u_longlong_t    dummy;
1142
1143         if (size <= zp->z_blksz)
1144                 return;
1145         /*
1146          * If the file size is already greater than the current blocksize,
1147          * we will not grow.  If there is more than one block in a file,
1148          * the blocksize cannot change.
1149          */
1150         if (zp->z_blksz && zp->z_phys->zp_size > zp->z_blksz)
1151                 return;
1152
1153         error = dmu_object_set_blocksize(zp->z_zfsvfs->z_os, zp->z_id,
1154             size, 0, tx);
1155         if (error == ENOTSUP)
1156                 return;
1157         ASSERT3U(error, ==, 0);
1158
1159         /* What blocksize did we actually get? */
1160         dmu_object_size_from_db(zp->z_dbuf, &zp->z_blksz, &dummy);
1161 }
1162
1163 /*
1164  * Increase the file length
1165  *
1166  *      IN:     zp      - znode of file to free data in.
1167  *              end     - new end-of-file
1168  *
1169  *      RETURN: 0 if success
1170  *              error code if failure
1171  */
1172 static int
1173 zfs_extend(znode_t *zp, uint64_t end)
1174 {
1175         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1176         dmu_tx_t *tx;
1177         rl_t *rl;
1178         uint64_t newblksz;
1179         int error;
1180
1181         /*
1182          * We will change zp_size, lock the whole file.
1183          */
1184         rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1185
1186         /*
1187          * Nothing to do if file already at desired length.
1188          */
1189         if (end <= zp->z_phys->zp_size) {
1190                 zfs_range_unlock(rl);
1191                 return (0);
1192         }
1193 top:
1194         tx = dmu_tx_create(zfsvfs->z_os);
1195         dmu_tx_hold_bonus(tx, zp->z_id);
1196         if (end > zp->z_blksz &&
1197             (!ISP2(zp->z_blksz) || zp->z_blksz < zfsvfs->z_max_blksz)) {
1198                 /*
1199                  * We are growing the file past the current block size.
1200                  */
1201                 if (zp->z_blksz > zp->z_zfsvfs->z_max_blksz) {
1202                         ASSERT(!ISP2(zp->z_blksz));
1203                         newblksz = MIN(end, SPA_MAXBLOCKSIZE);
1204                 } else {
1205                         newblksz = MIN(end, zp->z_zfsvfs->z_max_blksz);
1206                 }
1207                 dmu_tx_hold_write(tx, zp->z_id, 0, newblksz);
1208         } else {
1209                 newblksz = 0;
1210         }
1211
1212         error = dmu_tx_assign(tx, zfsvfs->z_assign);
1213         if (error) {
1214                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1215                         dmu_tx_wait(tx);
1216                         dmu_tx_abort(tx);
1217                         goto top;
1218                 }
1219                 dmu_tx_abort(tx);
1220                 zfs_range_unlock(rl);
1221                 return (error);
1222         }
1223         dmu_buf_will_dirty(zp->z_dbuf, tx);
1224
1225         if (newblksz)
1226                 zfs_grow_blocksize(zp, newblksz, tx);
1227
1228         zp->z_phys->zp_size = end;
1229
1230         zfs_range_unlock(rl);
1231
1232         dmu_tx_commit(tx);
1233
1234         rw_enter(&zp->z_map_lock, RW_WRITER);
1235         error = vinvalbuf(ZTOV(zp), V_SAVE, 0, 0);
1236         ASSERT(error == 0);
1237         vnode_pager_setsize(ZTOV(zp), end);
1238         rw_exit(&zp->z_map_lock);
1239
1240         return (0);
1241 }
1242
1243 /*
1244  * Free space in a file.
1245  *
1246  *      IN:     zp      - znode of file to free data in.
1247  *              off     - start of section to free.
1248  *              len     - length of section to free.
1249  *
1250  *      RETURN: 0 if success
1251  *              error code if failure
1252  */
1253 static int
1254 zfs_free_range(znode_t *zp, uint64_t off, uint64_t len)
1255 {
1256         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1257         rl_t *rl;
1258         int error;
1259
1260         /*
1261          * Lock the range being freed.
1262          */
1263         rl = zfs_range_lock(zp, off, len, RL_WRITER);
1264
1265         /*
1266          * Nothing to do if file already at desired length.
1267          */
1268         if (off >= zp->z_phys->zp_size) {
1269                 zfs_range_unlock(rl);
1270                 return (0);
1271         }
1272
1273         if (off + len > zp->z_phys->zp_size)
1274                 len = zp->z_phys->zp_size - off;
1275
1276         error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, off, len);
1277
1278         if (error == 0) {
1279                 /*
1280                  * In FreeBSD we cannot free block in the middle of a file,
1281                  * but only at the end of a file.
1282                  */
1283                 rw_enter(&zp->z_map_lock, RW_WRITER);
1284                 error = vinvalbuf(ZTOV(zp), V_SAVE, 0, 0);
1285                 ASSERT(error == 0);
1286                 vnode_pager_setsize(ZTOV(zp), off);
1287                 rw_exit(&zp->z_map_lock);
1288         }
1289
1290         zfs_range_unlock(rl);
1291
1292         return (error);
1293 }
1294
1295 /*
1296  * Truncate a file
1297  *
1298  *      IN:     zp      - znode of file to free data in.
1299  *              end     - new end-of-file.
1300  *
1301  *      RETURN: 0 if success
1302  *              error code if failure
1303  */
1304 static int
1305 zfs_trunc(znode_t *zp, uint64_t end)
1306 {
1307         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1308         vnode_t *vp = ZTOV(zp);
1309         dmu_tx_t *tx;
1310         rl_t *rl;
1311         int error;
1312
1313         /*
1314          * We will change zp_size, lock the whole file.
1315          */
1316         rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1317
1318         /*
1319          * Nothing to do if file already at desired length.
1320          */
1321         if (end >= zp->z_phys->zp_size) {
1322                 zfs_range_unlock(rl);
1323                 return (0);
1324         }
1325
1326         error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, end,  -1);
1327         if (error) {
1328                 zfs_range_unlock(rl);
1329                 return (error);
1330         }
1331 top:
1332         tx = dmu_tx_create(zfsvfs->z_os);
1333         dmu_tx_hold_bonus(tx, zp->z_id);
1334         error = dmu_tx_assign(tx, zfsvfs->z_assign);
1335         if (error) {
1336                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1337                         dmu_tx_wait(tx);
1338                         dmu_tx_abort(tx);
1339                         goto top;
1340                 }
1341                 dmu_tx_abort(tx);
1342                 zfs_range_unlock(rl);
1343                 return (error);
1344         }
1345         dmu_buf_will_dirty(zp->z_dbuf, tx);
1346
1347         zp->z_phys->zp_size = end;
1348
1349         dmu_tx_commit(tx);
1350
1351         zfs_range_unlock(rl);
1352
1353         /*
1354          * Clear any mapped pages in the truncated region.  This has to
1355          * happen outside of the transaction to avoid the possibility of
1356          * a deadlock with someone trying to push a page that we are
1357          * about to invalidate.
1358          */
1359         rw_enter(&zp->z_map_lock, RW_WRITER);
1360 #if 0
1361         error = vtruncbuf(vp, curthread->td_ucred, curthread, end, PAGE_SIZE);
1362 #else
1363         error = vinvalbuf(vp, V_SAVE, 0, 0);
1364         ASSERT(error == 0);
1365         vnode_pager_setsize(vp, end);
1366 #endif
1367         rw_exit(&zp->z_map_lock);
1368
1369         return (0);
1370 }
1371
1372 /*
1373  * Free space in a file
1374  *
1375  *      IN:     zp      - znode of file to free data in.
1376  *              off     - start of range
1377  *              len     - end of range (0 => EOF)
1378  *              flag    - current file open mode flags.
1379  *              log     - TRUE if this action should be logged
1380  *
1381  *      RETURN: 0 if success
1382  *              error code if failure
1383  */
1384 int
1385 zfs_freesp(znode_t *zp, uint64_t off, uint64_t len, int flag, boolean_t log)
1386 {
1387         vnode_t *vp = ZTOV(zp);
1388         dmu_tx_t *tx;
1389         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1390         zilog_t *zilog = zfsvfs->z_log;
1391         int error;
1392
1393         if (off > zp->z_phys->zp_size) {
1394                 error =  zfs_extend(zp, off+len);
1395                 if (error == 0 && log)
1396                         goto log;
1397                 else
1398                         return (error);
1399         }
1400
1401         if (len == 0) {
1402                 error = zfs_trunc(zp, off);
1403         } else {
1404                 if ((error = zfs_free_range(zp, off, len)) == 0 &&
1405                     off + len > zp->z_phys->zp_size)
1406                         error = zfs_extend(zp, off+len);
1407         }
1408         if (error || !log)
1409                 return (error);
1410 log:
1411         tx = dmu_tx_create(zfsvfs->z_os);
1412         dmu_tx_hold_bonus(tx, zp->z_id);
1413         error = dmu_tx_assign(tx, zfsvfs->z_assign);
1414         if (error) {
1415                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1416                         dmu_tx_wait(tx);
1417                         dmu_tx_abort(tx);
1418                         goto log;
1419                 }
1420                 dmu_tx_abort(tx);
1421                 return (error);
1422         }
1423
1424         zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
1425         zfs_log_truncate(zilog, tx, TX_TRUNCATE, zp, off, len);
1426
1427         dmu_tx_commit(tx);
1428         return (0);
1429 }
1430
1431 void
1432 zfs_create_fs(objset_t *os, cred_t *cr, nvlist_t *zplprops, dmu_tx_t *tx)
1433 {
1434         zfsvfs_t        zfsvfs;
1435         uint64_t        moid, doid, version;
1436         uint64_t        sense = ZFS_CASE_SENSITIVE;
1437         uint64_t        norm = 0;
1438         nvpair_t        *elem;
1439         int             error;
1440         znode_t         *rootzp = NULL;
1441         vnode_t         vnode;
1442         vattr_t         vattr;
1443         znode_t         *zp;
1444
1445         /*
1446          * First attempt to create master node.
1447          */
1448         /*
1449          * In an empty objset, there are no blocks to read and thus
1450          * there can be no i/o errors (which we assert below).
1451          */
1452         moid = MASTER_NODE_OBJ;
1453         error = zap_create_claim(os, moid, DMU_OT_MASTER_NODE,
1454             DMU_OT_NONE, 0, tx);
1455         ASSERT(error == 0);
1456
1457         /*
1458          * Set starting attributes.
1459          */
1460         if (spa_version(dmu_objset_spa(os)) >= SPA_VERSION_FUID)
1461                 version = ZPL_VERSION;
1462         else
1463                 version = ZPL_VERSION_FUID - 1;
1464         error = zap_update(os, moid, ZPL_VERSION_STR,
1465             8, 1, &version, tx);
1466         elem = NULL;
1467         while ((elem = nvlist_next_nvpair(zplprops, elem)) != NULL) {
1468                 /* For the moment we expect all zpl props to be uint64_ts */
1469                 uint64_t val;
1470                 char *name;
1471
1472                 ASSERT(nvpair_type(elem) == DATA_TYPE_UINT64);
1473                 VERIFY(nvpair_value_uint64(elem, &val) == 0);
1474                 name = nvpair_name(elem);
1475                 if (strcmp(name, zfs_prop_to_name(ZFS_PROP_VERSION)) == 0) {
1476                         version = val;
1477                         error = zap_update(os, moid, ZPL_VERSION_STR,
1478                             8, 1, &version, tx);
1479                 } else {
1480                         error = zap_update(os, moid, name, 8, 1, &val, tx);
1481                 }
1482                 ASSERT(error == 0);
1483                 if (strcmp(name, zfs_prop_to_name(ZFS_PROP_NORMALIZE)) == 0)
1484                         norm = val;
1485                 else if (strcmp(name, zfs_prop_to_name(ZFS_PROP_CASE)) == 0)
1486                         sense = val;
1487         }
1488         ASSERT(version != 0);
1489
1490         /*
1491          * Create a delete queue.
1492          */
1493         doid = zap_create(os, DMU_OT_UNLINKED_SET, DMU_OT_NONE, 0, tx);
1494
1495         error = zap_add(os, moid, ZFS_UNLINKED_SET, 8, 1, &doid, tx);
1496         ASSERT(error == 0);
1497
1498         /*
1499          * Create root znode.  Create minimal znode/vnode/zfsvfs
1500          * to allow zfs_mknode to work.
1501          */
1502         VATTR_NULL(&vattr);
1503         vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
1504         vattr.va_type = VDIR;
1505         vattr.va_mode = S_IFDIR|0755;
1506         vattr.va_uid = crgetuid(cr);
1507         vattr.va_gid = crgetgid(cr);
1508
1509         rootzp = kmem_cache_alloc(znode_cache, KM_SLEEP);
1510         zfs_znode_cache_constructor(rootzp, NULL, 0);
1511         rootzp->z_unlinked = 0;
1512         rootzp->z_atime_dirty = 0;
1513
1514         vnode.v_type = VDIR;
1515         vnode.v_data = rootzp;
1516         rootzp->z_vnode = &vnode;
1517
1518         bzero(&zfsvfs, sizeof (zfsvfs_t));
1519
1520         zfsvfs.z_os = os;
1521         zfsvfs.z_assign = TXG_NOWAIT;
1522         zfsvfs.z_parent = &zfsvfs;
1523         zfsvfs.z_version = version;
1524         zfsvfs.z_use_fuids = USE_FUIDS(version, os);
1525         zfsvfs.z_norm = norm;
1526         /*
1527          * Fold case on file systems that are always or sometimes case
1528          * insensitive.
1529          */
1530         if (sense == ZFS_CASE_INSENSITIVE || sense == ZFS_CASE_MIXED)
1531                 zfsvfs.z_norm |= U8_TEXTPREP_TOUPPER;
1532
1533         mutex_init(&zfsvfs.z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
1534         list_create(&zfsvfs.z_all_znodes, sizeof (znode_t),
1535             offsetof(znode_t, z_link_node));
1536
1537         ASSERT(!POINTER_IS_VALID(rootzp->z_zfsvfs));
1538         rootzp->z_zfsvfs = &zfsvfs;
1539         zfs_mknode(rootzp, &vattr, tx, cr, IS_ROOT_NODE, &zp, 0, NULL, NULL);
1540         ASSERT3P(zp, ==, rootzp);
1541         error = zap_add(os, moid, ZFS_ROOT_OBJ, 8, 1, &rootzp->z_id, tx);
1542         ASSERT(error == 0);
1543         POINTER_INVALIDATE(&rootzp->z_zfsvfs);
1544
1545         dmu_buf_rele(rootzp->z_dbuf, NULL);
1546         rootzp->z_dbuf = NULL;
1547         mutex_destroy(&zfsvfs.z_znodes_lock);
1548         rootzp->z_vnode = NULL;
1549         kmem_cache_free(znode_cache, rootzp);
1550 }
1551
1552 #endif /* _KERNEL */
1553 /*
1554  * Given an object number, return its parent object number and whether
1555  * or not the object is an extended attribute directory.
1556  */
1557 static int
1558 zfs_obj_to_pobj(objset_t *osp, uint64_t obj, uint64_t *pobjp, int *is_xattrdir)
1559 {
1560         dmu_buf_t *db;
1561         dmu_object_info_t doi;
1562         znode_phys_t *zp;
1563         int error;
1564
1565         if ((error = dmu_bonus_hold(osp, obj, FTAG, &db)) != 0)
1566                 return (error);
1567
1568         dmu_object_info_from_db(db, &doi);
1569         if (doi.doi_bonus_type != DMU_OT_ZNODE ||
1570             doi.doi_bonus_size < sizeof (znode_phys_t)) {
1571                 dmu_buf_rele(db, FTAG);
1572                 return (EINVAL);
1573         }
1574
1575         zp = db->db_data;
1576         *pobjp = zp->zp_parent;
1577         *is_xattrdir = ((zp->zp_flags & ZFS_XATTR) != 0) &&
1578             S_ISDIR(zp->zp_mode);
1579         dmu_buf_rele(db, FTAG);
1580
1581         return (0);
1582 }
1583
1584 int
1585 zfs_obj_to_path(objset_t *osp, uint64_t obj, char *buf, int len)
1586 {
1587         char *path = buf + len - 1;
1588         int error;
1589
1590         *path = '\0';
1591
1592         for (;;) {
1593                 uint64_t pobj;
1594                 char component[MAXNAMELEN + 2];
1595                 size_t complen;
1596                 int is_xattrdir;
1597
1598                 if ((error = zfs_obj_to_pobj(osp, obj, &pobj,
1599                     &is_xattrdir)) != 0)
1600                         break;
1601
1602                 if (pobj == obj) {
1603                         if (path[0] != '/')
1604                                 *--path = '/';
1605                         break;
1606                 }
1607
1608                 component[0] = '/';
1609                 if (is_xattrdir) {
1610                         (void) sprintf(component + 1, "<xattrdir>");
1611                 } else {
1612                         error = zap_value_search(osp, pobj, obj,
1613                             ZFS_DIRENT_OBJ(-1ULL), component + 1);
1614                         if (error != 0)
1615                                 break;
1616                 }
1617
1618                 complen = strlen(component);
1619                 path -= complen;
1620                 ASSERT(path >= buf);
1621                 bcopy(component, path, complen);
1622                 obj = pobj;
1623         }
1624
1625         if (error == 0)
1626                 (void) memmove(buf, path, buf + len - path);
1627         return (error);
1628 }