]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_znode.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.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
708         ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
709         VERIFY(0 == dmu_bonus_hold(zfsvfs->z_os, obj, NULL, &db));
710         dmu_buf_will_dirty(db, tx);
711
712         /*
713          * Initialize the znode physical data to zero.
714          */
715         ASSERT(db->db_size >= sizeof (znode_phys_t));
716         bzero(db->db_data, db->db_size);
717         pzp = db->db_data;
718
719         /*
720          * If this is the root, fix up the half-initialized parent pointer
721          * to reference the just-allocated physical data area.
722          */
723         if (flag & IS_ROOT_NODE) {
724                 dzp->z_dbuf = db;
725                 dzp->z_phys = pzp;
726                 dzp->z_id = obj;
727         }
728
729         /*
730          * If parent is an xattr, so am I.
731          */
732         if (dzp->z_phys->zp_flags & ZFS_XATTR)
733                 flag |= IS_XATTR;
734
735         if (vap->va_type == VBLK || vap->va_type == VCHR) {
736                 pzp->zp_rdev = zfs_expldev(vap->va_rdev);
737         }
738
739         if (zfsvfs->z_use_fuids)
740                 pzp->zp_flags = ZFS_ARCHIVE | ZFS_AV_MODIFIED;
741
742         if (vap->va_type == VDIR) {
743                 pzp->zp_size = 2;               /* contents ("." and "..") */
744                 pzp->zp_links = (flag & (IS_ROOT_NODE | IS_XATTR)) ? 2 : 1;
745         }
746
747         pzp->zp_parent = dzp->z_id;
748         if (flag & IS_XATTR)
749                 pzp->zp_flags |= ZFS_XATTR;
750
751         pzp->zp_gen = gen;
752
753         ZFS_TIME_ENCODE(&now, pzp->zp_crtime);
754         ZFS_TIME_ENCODE(&now, pzp->zp_ctime);
755
756         if (vap->va_mask & AT_ATIME) {
757                 ZFS_TIME_ENCODE(&vap->va_atime, pzp->zp_atime);
758         } else {
759                 ZFS_TIME_ENCODE(&now, pzp->zp_atime);
760         }
761
762         if (vap->va_mask & AT_MTIME) {
763                 ZFS_TIME_ENCODE(&vap->va_mtime, pzp->zp_mtime);
764         } else {
765                 ZFS_TIME_ENCODE(&now, pzp->zp_mtime);
766         }
767
768         pzp->zp_mode = MAKEIMODE(vap->va_type, vap->va_mode);
769         if (!(flag & IS_ROOT_NODE)) {
770                 *zpp = zfs_znode_alloc(zfsvfs, db, 0);
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         ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
780         if (!(flag & IS_ROOT_NODE)) {
781                 vnode_t *vp;
782
783                 vp = ZTOV(*zpp);
784                 vp->v_vflag |= VV_FORCEINSMQ;
785                 err = insmntque(vp, zfsvfs->z_vfs);
786                 vp->v_vflag &= ~VV_FORCEINSMQ;
787                 KASSERT(err == 0, ("insmntque() failed: error %d", err));
788         }
789 }
790
791 void
792 zfs_xvattr_set(znode_t *zp, xvattr_t *xvap)
793 {
794         xoptattr_t *xoap;
795
796         xoap = xva_getxoptattr(xvap);
797         ASSERT(xoap);
798
799         if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
800                 ZFS_TIME_ENCODE(&xoap->xoa_createtime, zp->z_phys->zp_crtime);
801                 XVA_SET_RTN(xvap, XAT_CREATETIME);
802         }
803         if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
804                 ZFS_ATTR_SET(zp, ZFS_READONLY, xoap->xoa_readonly);
805                 XVA_SET_RTN(xvap, XAT_READONLY);
806         }
807         if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
808                 ZFS_ATTR_SET(zp, ZFS_HIDDEN, xoap->xoa_hidden);
809                 XVA_SET_RTN(xvap, XAT_HIDDEN);
810         }
811         if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
812                 ZFS_ATTR_SET(zp, ZFS_SYSTEM, xoap->xoa_system);
813                 XVA_SET_RTN(xvap, XAT_SYSTEM);
814         }
815         if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
816                 ZFS_ATTR_SET(zp, ZFS_ARCHIVE, xoap->xoa_archive);
817                 XVA_SET_RTN(xvap, XAT_ARCHIVE);
818         }
819         if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
820                 ZFS_ATTR_SET(zp, ZFS_IMMUTABLE, xoap->xoa_immutable);
821                 XVA_SET_RTN(xvap, XAT_IMMUTABLE);
822         }
823         if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
824                 ZFS_ATTR_SET(zp, ZFS_NOUNLINK, xoap->xoa_nounlink);
825                 XVA_SET_RTN(xvap, XAT_NOUNLINK);
826         }
827         if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
828                 ZFS_ATTR_SET(zp, ZFS_APPENDONLY, xoap->xoa_appendonly);
829                 XVA_SET_RTN(xvap, XAT_APPENDONLY);
830         }
831         if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
832                 ZFS_ATTR_SET(zp, ZFS_NODUMP, xoap->xoa_nodump);
833                 XVA_SET_RTN(xvap, XAT_NODUMP);
834         }
835         if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
836                 ZFS_ATTR_SET(zp, ZFS_OPAQUE, xoap->xoa_opaque);
837                 XVA_SET_RTN(xvap, XAT_OPAQUE);
838         }
839         if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
840                 ZFS_ATTR_SET(zp, ZFS_AV_QUARANTINED,
841                     xoap->xoa_av_quarantined);
842                 XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
843         }
844         if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
845                 ZFS_ATTR_SET(zp, ZFS_AV_MODIFIED, xoap->xoa_av_modified);
846                 XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
847         }
848         if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
849                 (void) memcpy(zp->z_phys + 1, xoap->xoa_av_scanstamp,
850                     sizeof (xoap->xoa_av_scanstamp));
851                 zp->z_phys->zp_flags |= ZFS_BONUS_SCANSTAMP;
852                 XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
853         }
854 }
855
856 int
857 zfs_zget(zfsvfs_t *zfsvfs, uint64_t obj_num, znode_t **zpp)
858 {
859         dmu_object_info_t doi;
860         dmu_buf_t       *db;
861         znode_t         *zp;
862         vnode_t         *vp;
863         int err, first = 1;
864
865         *zpp = NULL;
866 again:
867         ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
868
869         err = dmu_bonus_hold(zfsvfs->z_os, obj_num, NULL, &db);
870         if (err) {
871                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
872                 return (err);
873         }
874
875         dmu_object_info_from_db(db, &doi);
876         if (doi.doi_bonus_type != DMU_OT_ZNODE ||
877             doi.doi_bonus_size < sizeof (znode_phys_t)) {
878                 dmu_buf_rele(db, NULL);
879                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
880                 return (EINVAL);
881         }
882
883         zp = dmu_buf_get_user(db);
884         if (zp != NULL) {
885                 mutex_enter(&zp->z_lock);
886
887                 /*
888                  * Since we do immediate eviction of the z_dbuf, we
889                  * should never find a dbuf with a znode that doesn't
890                  * know about the dbuf.
891                  */
892                 ASSERT3P(zp->z_dbuf, ==, db);
893                 ASSERT3U(zp->z_id, ==, obj_num);
894                 if (zp->z_unlinked) {
895                         err = ENOENT;
896                 } else {
897                         int dying = 0;
898
899                         vp = ZTOV(zp);
900                         if (vp == NULL)
901                                 dying = 1;
902                         else {
903                                 VN_HOLD(vp);
904                                 if ((vp->v_iflag & VI_DOOMED) != 0) {
905                                         dying = 1;
906                                         /*
907                                          * Don't VN_RELE() vnode here, because
908                                          * it can call vn_lock() which creates
909                                          * LOR between vnode lock and znode
910                                          * lock. We will VN_RELE() the vnode
911                                          * after droping znode lock.
912                                          */
913                                 }
914                         }
915                         if (dying) {
916                                 if (first) {
917                                         ZFS_LOG(1, "dying znode detected (zp=%p)", zp);
918                                         first = 0;
919                                 }
920                                 /*
921                                  * znode is dying so we can't reuse it, we must
922                                  * wait until destruction is completed.
923                                  */
924                                 dmu_buf_rele(db, NULL);
925                                 mutex_exit(&zp->z_lock);
926                                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
927                                 if (vp != NULL)
928                                         VN_RELE(vp);
929                                 tsleep(zp, 0, "zcollide", 1);
930                                 goto again;
931                         }
932                         *zpp = zp;
933                         err = 0;
934                 }
935                 dmu_buf_rele(db, NULL);
936                 mutex_exit(&zp->z_lock);
937                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
938                 return (err);
939         }
940
941         /*
942          * Not found create new znode/vnode
943          * but only if file exists.
944          *
945          * There is a small window where zfs_vget() could
946          * find this object while a file create is still in
947          * progress.  Since a gen number can never be zero
948          * we will check that to determine if its an allocated
949          * file.
950          */
951
952         if (((znode_phys_t *)db->db_data)->zp_gen != 0) {
953                 zp = zfs_znode_alloc(zfsvfs, db, doi.doi_data_block_size);
954                 *zpp = zp;
955                 vp = ZTOV(zp);
956                 vp->v_vflag |= VV_FORCEINSMQ;
957                 err = insmntque(vp, zfsvfs->z_vfs);
958                 vp->v_vflag &= ~VV_FORCEINSMQ;
959                 KASSERT(err == 0, ("insmntque() failed: error %d", err));
960                 VOP_UNLOCK(vp, 0);
961                 err = 0;
962         } else {
963                 dmu_buf_rele(db, NULL);
964                 err = ENOENT;
965         }
966         ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
967         return (err);
968 }
969
970 int
971 zfs_rezget(znode_t *zp)
972 {
973         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
974         dmu_object_info_t doi;
975         dmu_buf_t *db;
976         uint64_t obj_num = zp->z_id;
977         int err;
978
979         ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
980
981         err = dmu_bonus_hold(zfsvfs->z_os, obj_num, NULL, &db);
982         if (err) {
983                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
984                 return (err);
985         }
986
987         dmu_object_info_from_db(db, &doi);
988         if (doi.doi_bonus_type != DMU_OT_ZNODE ||
989             doi.doi_bonus_size < sizeof (znode_phys_t)) {
990                 dmu_buf_rele(db, NULL);
991                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
992                 return (EINVAL);
993         }
994
995         if (((znode_phys_t *)db->db_data)->zp_gen != zp->z_gen) {
996                 dmu_buf_rele(db, NULL);
997                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
998                 return (EIO);
999         }
1000
1001         zfs_znode_dmu_init(zfsvfs, zp, db);
1002         zp->z_unlinked = (zp->z_phys->zp_links == 0);
1003         zp->z_blksz = doi.doi_data_block_size;
1004
1005         ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1006
1007         return (0);
1008 }
1009
1010 void
1011 zfs_znode_delete(znode_t *zp, dmu_tx_t *tx)
1012 {
1013         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1014         objset_t *os = zfsvfs->z_os;
1015         uint64_t obj = zp->z_id;
1016         uint64_t acl_obj = zp->z_phys->zp_acl.z_acl_extern_obj;
1017
1018         ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
1019         if (acl_obj)
1020                 VERIFY(0 == dmu_object_free(os, acl_obj, tx));
1021         VERIFY(0 == dmu_object_free(os, obj, tx));
1022         zfs_znode_dmu_fini(zp);
1023         ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
1024         zfs_znode_free(zp);
1025 }
1026
1027 void
1028 zfs_zinactive(znode_t *zp)
1029 {
1030         vnode_t *vp = ZTOV(zp);
1031         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1032         uint64_t z_id = zp->z_id;
1033         int vfslocked;
1034
1035         ASSERT(zp->z_dbuf && zp->z_phys);
1036
1037         /*
1038          * Don't allow a zfs_zget() while were trying to release this znode
1039          */
1040         ZFS_OBJ_HOLD_ENTER(zfsvfs, z_id);
1041
1042         mutex_enter(&zp->z_lock);
1043         VI_LOCK(vp);
1044         if (vp->v_count > 0) {
1045                 /*
1046                  * If the hold count is greater than zero, somebody has
1047                  * obtained a new reference on this znode while we were
1048                  * processing it here, so we are done.
1049                  */
1050                 VI_UNLOCK(vp);
1051                 mutex_exit(&zp->z_lock);
1052                 ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1053                 return;
1054         }
1055         VI_UNLOCK(vp);
1056
1057         /*
1058          * If this was the last reference to a file with no links,
1059          * remove the file from the file system.
1060          */
1061         if (zp->z_unlinked) {
1062                 mutex_exit(&zp->z_lock);
1063                 ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1064                 ASSERT(vp->v_count == 0);
1065                 vrecycle(vp, curthread);
1066                 vfslocked = VFS_LOCK_GIANT(zfsvfs->z_vfs);
1067                 zfs_rmnode(zp);
1068                 VFS_UNLOCK_GIANT(vfslocked);
1069                 return;
1070         }
1071         mutex_exit(&zp->z_lock);
1072         ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1073 }
1074
1075 void
1076 zfs_znode_free(znode_t *zp)
1077 {
1078         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1079
1080         ASSERT(ZTOV(zp) == NULL);
1081         mutex_enter(&zfsvfs->z_znodes_lock);
1082         POINTER_INVALIDATE(&zp->z_zfsvfs);
1083         list_remove(&zfsvfs->z_all_znodes, zp);
1084         mutex_exit(&zfsvfs->z_znodes_lock);
1085
1086         kmem_cache_free(znode_cache, zp);
1087
1088         VFS_RELE(zfsvfs->z_vfs);
1089 }
1090
1091 void
1092 zfs_time_stamper_locked(znode_t *zp, uint_t flag, dmu_tx_t *tx)
1093 {
1094         timestruc_t     now;
1095
1096         ASSERT(MUTEX_HELD(&zp->z_lock));
1097
1098         gethrestime(&now);
1099
1100         if (tx) {
1101                 dmu_buf_will_dirty(zp->z_dbuf, tx);
1102                 zp->z_atime_dirty = 0;
1103                 zp->z_seq++;
1104         } else {
1105                 zp->z_atime_dirty = 1;
1106         }
1107
1108         if (flag & AT_ATIME)
1109                 ZFS_TIME_ENCODE(&now, zp->z_phys->zp_atime);
1110
1111         if (flag & AT_MTIME) {
1112                 ZFS_TIME_ENCODE(&now, zp->z_phys->zp_mtime);
1113                 if (zp->z_zfsvfs->z_use_fuids)
1114                         zp->z_phys->zp_flags |= (ZFS_ARCHIVE | ZFS_AV_MODIFIED);
1115         }
1116
1117         if (flag & AT_CTIME) {
1118                 ZFS_TIME_ENCODE(&now, zp->z_phys->zp_ctime);
1119                 if (zp->z_zfsvfs->z_use_fuids)
1120                         zp->z_phys->zp_flags |= ZFS_ARCHIVE;
1121         }
1122 }
1123
1124 /*
1125  * Update the requested znode timestamps with the current time.
1126  * If we are in a transaction, then go ahead and mark the znode
1127  * dirty in the transaction so the timestamps will go to disk.
1128  * Otherwise, we will get pushed next time the znode is updated
1129  * in a transaction, or when this znode eventually goes inactive.
1130  *
1131  * Why is this OK?
1132  *  1 - Only the ACCESS time is ever updated outside of a transaction.
1133  *  2 - Multiple consecutive updates will be collapsed into a single
1134  *      znode update by the transaction grouping semantics of the DMU.
1135  */
1136 void
1137 zfs_time_stamper(znode_t *zp, uint_t flag, dmu_tx_t *tx)
1138 {
1139         mutex_enter(&zp->z_lock);
1140         zfs_time_stamper_locked(zp, flag, tx);
1141         mutex_exit(&zp->z_lock);
1142 }
1143
1144 /*
1145  * Grow the block size for a file.
1146  *
1147  *      IN:     zp      - znode of file to free data in.
1148  *              size    - requested block size
1149  *              tx      - open transaction.
1150  *
1151  * NOTE: this function assumes that the znode is write locked.
1152  */
1153 void
1154 zfs_grow_blocksize(znode_t *zp, uint64_t size, dmu_tx_t *tx)
1155 {
1156         int             error;
1157         u_longlong_t    dummy;
1158
1159         if (size <= zp->z_blksz)
1160                 return;
1161         /*
1162          * If the file size is already greater than the current blocksize,
1163          * we will not grow.  If there is more than one block in a file,
1164          * the blocksize cannot change.
1165          */
1166         if (zp->z_blksz && zp->z_phys->zp_size > zp->z_blksz)
1167                 return;
1168
1169         error = dmu_object_set_blocksize(zp->z_zfsvfs->z_os, zp->z_id,
1170             size, 0, tx);
1171         if (error == ENOTSUP)
1172                 return;
1173         ASSERT3U(error, ==, 0);
1174
1175         /* What blocksize did we actually get? */
1176         dmu_object_size_from_db(zp->z_dbuf, &zp->z_blksz, &dummy);
1177 }
1178
1179 /*
1180  * Increase the file length
1181  *
1182  *      IN:     zp      - znode of file to free data in.
1183  *              end     - new end-of-file
1184  *
1185  *      RETURN: 0 if success
1186  *              error code if failure
1187  */
1188 static int
1189 zfs_extend(znode_t *zp, uint64_t end)
1190 {
1191         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1192         dmu_tx_t *tx;
1193         rl_t *rl;
1194         uint64_t newblksz;
1195         int error;
1196
1197         /*
1198          * We will change zp_size, lock the whole file.
1199          */
1200         rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1201
1202         /*
1203          * Nothing to do if file already at desired length.
1204          */
1205         if (end <= zp->z_phys->zp_size) {
1206                 zfs_range_unlock(rl);
1207                 return (0);
1208         }
1209 top:
1210         tx = dmu_tx_create(zfsvfs->z_os);
1211         dmu_tx_hold_bonus(tx, zp->z_id);
1212         if (end > zp->z_blksz &&
1213             (!ISP2(zp->z_blksz) || zp->z_blksz < zfsvfs->z_max_blksz)) {
1214                 /*
1215                  * We are growing the file past the current block size.
1216                  */
1217                 if (zp->z_blksz > zp->z_zfsvfs->z_max_blksz) {
1218                         ASSERT(!ISP2(zp->z_blksz));
1219                         newblksz = MIN(end, SPA_MAXBLOCKSIZE);
1220                 } else {
1221                         newblksz = MIN(end, zp->z_zfsvfs->z_max_blksz);
1222                 }
1223                 dmu_tx_hold_write(tx, zp->z_id, 0, newblksz);
1224         } else {
1225                 newblksz = 0;
1226         }
1227
1228         error = dmu_tx_assign(tx, zfsvfs->z_assign);
1229         if (error) {
1230                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1231                         dmu_tx_wait(tx);
1232                         dmu_tx_abort(tx);
1233                         goto top;
1234                 }
1235                 dmu_tx_abort(tx);
1236                 zfs_range_unlock(rl);
1237                 return (error);
1238         }
1239         dmu_buf_will_dirty(zp->z_dbuf, tx);
1240
1241         if (newblksz)
1242                 zfs_grow_blocksize(zp, newblksz, tx);
1243
1244         zp->z_phys->zp_size = end;
1245
1246         zfs_range_unlock(rl);
1247
1248         dmu_tx_commit(tx);
1249
1250         rw_enter(&zp->z_map_lock, RW_WRITER);
1251         error = vinvalbuf(ZTOV(zp), V_SAVE, 0, 0);
1252         ASSERT(error == 0);
1253         vnode_pager_setsize(ZTOV(zp), end);
1254         rw_exit(&zp->z_map_lock);
1255
1256         return (0);
1257 }
1258
1259 /*
1260  * Free space in a file.
1261  *
1262  *      IN:     zp      - znode of file to free data in.
1263  *              off     - start of section to free.
1264  *              len     - length of section to free.
1265  *
1266  *      RETURN: 0 if success
1267  *              error code if failure
1268  */
1269 static int
1270 zfs_free_range(znode_t *zp, uint64_t off, uint64_t len)
1271 {
1272         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1273         rl_t *rl;
1274         int error;
1275
1276         /*
1277          * Lock the range being freed.
1278          */
1279         rl = zfs_range_lock(zp, off, len, RL_WRITER);
1280
1281         /*
1282          * Nothing to do if file already at desired length.
1283          */
1284         if (off >= zp->z_phys->zp_size) {
1285                 zfs_range_unlock(rl);
1286                 return (0);
1287         }
1288
1289         if (off + len > zp->z_phys->zp_size)
1290                 len = zp->z_phys->zp_size - off;
1291
1292         error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, off, len);
1293
1294         if (error == 0) {
1295                 /*
1296                  * In FreeBSD we cannot free block in the middle of a file,
1297                  * but only at the end of a file.
1298                  */
1299                 rw_enter(&zp->z_map_lock, RW_WRITER);
1300                 error = vinvalbuf(ZTOV(zp), V_SAVE, 0, 0);
1301                 ASSERT(error == 0);
1302                 vnode_pager_setsize(ZTOV(zp), off);
1303                 rw_exit(&zp->z_map_lock);
1304         }
1305
1306         zfs_range_unlock(rl);
1307
1308         return (error);
1309 }
1310
1311 /*
1312  * Truncate a file
1313  *
1314  *      IN:     zp      - znode of file to free data in.
1315  *              end     - new end-of-file.
1316  *
1317  *      RETURN: 0 if success
1318  *              error code if failure
1319  */
1320 static int
1321 zfs_trunc(znode_t *zp, uint64_t end)
1322 {
1323         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1324         vnode_t *vp = ZTOV(zp);
1325         dmu_tx_t *tx;
1326         rl_t *rl;
1327         int error;
1328
1329         /*
1330          * We will change zp_size, lock the whole file.
1331          */
1332         rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1333
1334         /*
1335          * Nothing to do if file already at desired length.
1336          */
1337         if (end >= zp->z_phys->zp_size) {
1338                 zfs_range_unlock(rl);
1339                 return (0);
1340         }
1341
1342         error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, end,  -1);
1343         if (error) {
1344                 zfs_range_unlock(rl);
1345                 return (error);
1346         }
1347 top:
1348         tx = dmu_tx_create(zfsvfs->z_os);
1349         dmu_tx_hold_bonus(tx, zp->z_id);
1350         error = dmu_tx_assign(tx, zfsvfs->z_assign);
1351         if (error) {
1352                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1353                         dmu_tx_wait(tx);
1354                         dmu_tx_abort(tx);
1355                         goto top;
1356                 }
1357                 dmu_tx_abort(tx);
1358                 zfs_range_unlock(rl);
1359                 return (error);
1360         }
1361         dmu_buf_will_dirty(zp->z_dbuf, tx);
1362
1363         zp->z_phys->zp_size = end;
1364
1365         dmu_tx_commit(tx);
1366
1367         zfs_range_unlock(rl);
1368
1369         /*
1370          * Clear any mapped pages in the truncated region.  This has to
1371          * happen outside of the transaction to avoid the possibility of
1372          * a deadlock with someone trying to push a page that we are
1373          * about to invalidate.
1374          */
1375         rw_enter(&zp->z_map_lock, RW_WRITER);
1376 #if 0
1377         error = vtruncbuf(vp, curthread->td_ucred, curthread, end, PAGE_SIZE);
1378 #else
1379         error = vinvalbuf(vp, V_SAVE, 0, 0);
1380         ASSERT(error == 0);
1381         vnode_pager_setsize(vp, end);
1382 #endif
1383         rw_exit(&zp->z_map_lock);
1384
1385         return (0);
1386 }
1387
1388 /*
1389  * Free space in a file
1390  *
1391  *      IN:     zp      - znode of file to free data in.
1392  *              off     - start of range
1393  *              len     - end of range (0 => EOF)
1394  *              flag    - current file open mode flags.
1395  *              log     - TRUE if this action should be logged
1396  *
1397  *      RETURN: 0 if success
1398  *              error code if failure
1399  */
1400 int
1401 zfs_freesp(znode_t *zp, uint64_t off, uint64_t len, int flag, boolean_t log)
1402 {
1403         vnode_t *vp = ZTOV(zp);
1404         dmu_tx_t *tx;
1405         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1406         zilog_t *zilog = zfsvfs->z_log;
1407         int error;
1408
1409         if (off > zp->z_phys->zp_size) {
1410                 error =  zfs_extend(zp, off+len);
1411                 if (error == 0 && log)
1412                         goto log;
1413                 else
1414                         return (error);
1415         }
1416
1417         if (len == 0) {
1418                 error = zfs_trunc(zp, off);
1419         } else {
1420                 if ((error = zfs_free_range(zp, off, len)) == 0 &&
1421                     off + len > zp->z_phys->zp_size)
1422                         error = zfs_extend(zp, off+len);
1423         }
1424         if (error || !log)
1425                 return (error);
1426 log:
1427         tx = dmu_tx_create(zfsvfs->z_os);
1428         dmu_tx_hold_bonus(tx, zp->z_id);
1429         error = dmu_tx_assign(tx, zfsvfs->z_assign);
1430         if (error) {
1431                 if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
1432                         dmu_tx_wait(tx);
1433                         dmu_tx_abort(tx);
1434                         goto log;
1435                 }
1436                 dmu_tx_abort(tx);
1437                 return (error);
1438         }
1439
1440         zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
1441         zfs_log_truncate(zilog, tx, TX_TRUNCATE, zp, off, len);
1442
1443         dmu_tx_commit(tx);
1444         return (0);
1445 }
1446
1447 void
1448 zfs_create_fs(objset_t *os, cred_t *cr, nvlist_t *zplprops, dmu_tx_t *tx)
1449 {
1450         zfsvfs_t        zfsvfs;
1451         uint64_t        moid, doid, version;
1452         uint64_t        sense = ZFS_CASE_SENSITIVE;
1453         uint64_t        norm = 0;
1454         nvpair_t        *elem;
1455         int             error;
1456         int             i;
1457         znode_t         *rootzp = NULL;
1458         vnode_t         vnode;
1459         vattr_t         vattr;
1460         znode_t         *zp;
1461
1462         /*
1463          * First attempt to create master node.
1464          */
1465         /*
1466          * In an empty objset, there are no blocks to read and thus
1467          * there can be no i/o errors (which we assert below).
1468          */
1469         moid = MASTER_NODE_OBJ;
1470         error = zap_create_claim(os, moid, DMU_OT_MASTER_NODE,
1471             DMU_OT_NONE, 0, tx);
1472         ASSERT(error == 0);
1473
1474         /*
1475          * Set starting attributes.
1476          */
1477         if (spa_version(dmu_objset_spa(os)) >= SPA_VERSION_FUID)
1478                 version = ZPL_VERSION;
1479         else
1480                 version = ZPL_VERSION_FUID - 1;
1481         error = zap_update(os, moid, ZPL_VERSION_STR,
1482             8, 1, &version, tx);
1483         elem = NULL;
1484         while ((elem = nvlist_next_nvpair(zplprops, elem)) != NULL) {
1485                 /* For the moment we expect all zpl props to be uint64_ts */
1486                 uint64_t val;
1487                 char *name;
1488
1489                 ASSERT(nvpair_type(elem) == DATA_TYPE_UINT64);
1490                 VERIFY(nvpair_value_uint64(elem, &val) == 0);
1491                 name = nvpair_name(elem);
1492                 if (strcmp(name, zfs_prop_to_name(ZFS_PROP_VERSION)) == 0) {
1493                         version = val;
1494                         error = zap_update(os, moid, ZPL_VERSION_STR,
1495                             8, 1, &version, tx);
1496                 } else {
1497                         error = zap_update(os, moid, name, 8, 1, &val, tx);
1498                 }
1499                 ASSERT(error == 0);
1500                 if (strcmp(name, zfs_prop_to_name(ZFS_PROP_NORMALIZE)) == 0)
1501                         norm = val;
1502                 else if (strcmp(name, zfs_prop_to_name(ZFS_PROP_CASE)) == 0)
1503                         sense = val;
1504         }
1505         ASSERT(version != 0);
1506
1507         /*
1508          * Create a delete queue.
1509          */
1510         doid = zap_create(os, DMU_OT_UNLINKED_SET, DMU_OT_NONE, 0, tx);
1511
1512         error = zap_add(os, moid, ZFS_UNLINKED_SET, 8, 1, &doid, tx);
1513         ASSERT(error == 0);
1514
1515         /*
1516          * Create root znode.  Create minimal znode/vnode/zfsvfs
1517          * to allow zfs_mknode to work.
1518          */
1519         VATTR_NULL(&vattr);
1520         vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
1521         vattr.va_type = VDIR;
1522         vattr.va_mode = S_IFDIR|0755;
1523         vattr.va_uid = crgetuid(cr);
1524         vattr.va_gid = crgetgid(cr);
1525
1526         rootzp = kmem_cache_alloc(znode_cache, KM_SLEEP);
1527         zfs_znode_cache_constructor(rootzp, NULL, 0);
1528         rootzp->z_unlinked = 0;
1529         rootzp->z_atime_dirty = 0;
1530
1531         vnode.v_type = VDIR;
1532         vnode.v_data = rootzp;
1533         rootzp->z_vnode = &vnode;
1534
1535         bzero(&zfsvfs, sizeof (zfsvfs_t));
1536
1537         zfsvfs.z_os = os;
1538         zfsvfs.z_assign = TXG_NOWAIT;
1539         zfsvfs.z_parent = &zfsvfs;
1540         zfsvfs.z_version = version;
1541         zfsvfs.z_use_fuids = USE_FUIDS(version, os);
1542         zfsvfs.z_norm = norm;
1543         /*
1544          * Fold case on file systems that are always or sometimes case
1545          * insensitive.
1546          */
1547         if (sense == ZFS_CASE_INSENSITIVE || sense == ZFS_CASE_MIXED)
1548                 zfsvfs.z_norm |= U8_TEXTPREP_TOUPPER;
1549
1550         mutex_init(&zfsvfs.z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
1551         list_create(&zfsvfs.z_all_znodes, sizeof (znode_t),
1552             offsetof(znode_t, z_link_node));
1553
1554         for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1555                 mutex_init(&zfsvfs.z_hold_mtx[i], NULL, MUTEX_DEFAULT, NULL);
1556
1557         ASSERT(!POINTER_IS_VALID(rootzp->z_zfsvfs));
1558         rootzp->z_zfsvfs = &zfsvfs;
1559         zfs_mknode(rootzp, &vattr, tx, cr, IS_ROOT_NODE, &zp, 0, NULL, NULL);
1560         ASSERT3P(zp, ==, rootzp);
1561         error = zap_add(os, moid, ZFS_ROOT_OBJ, 8, 1, &rootzp->z_id, tx);
1562         ASSERT(error == 0);
1563         POINTER_INVALIDATE(&rootzp->z_zfsvfs);
1564
1565         dmu_buf_rele(rootzp->z_dbuf, NULL);
1566         rootzp->z_dbuf = NULL;
1567         for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1568                 mutex_destroy(&zfsvfs.z_hold_mtx[i]);
1569         mutex_destroy(&zfsvfs.z_znodes_lock);
1570         rootzp->z_vnode = NULL;
1571         kmem_cache_free(znode_cache, rootzp);
1572 }
1573
1574 #endif /* _KERNEL */
1575 /*
1576  * Given an object number, return its parent object number and whether
1577  * or not the object is an extended attribute directory.
1578  */
1579 static int
1580 zfs_obj_to_pobj(objset_t *osp, uint64_t obj, uint64_t *pobjp, int *is_xattrdir)
1581 {
1582         dmu_buf_t *db;
1583         dmu_object_info_t doi;
1584         znode_phys_t *zp;
1585         int error;
1586
1587         if ((error = dmu_bonus_hold(osp, obj, FTAG, &db)) != 0)
1588                 return (error);
1589
1590         dmu_object_info_from_db(db, &doi);
1591         if (doi.doi_bonus_type != DMU_OT_ZNODE ||
1592             doi.doi_bonus_size < sizeof (znode_phys_t)) {
1593                 dmu_buf_rele(db, FTAG);
1594                 return (EINVAL);
1595         }
1596
1597         zp = db->db_data;
1598         *pobjp = zp->zp_parent;
1599         *is_xattrdir = ((zp->zp_flags & ZFS_XATTR) != 0) &&
1600             S_ISDIR(zp->zp_mode);
1601         dmu_buf_rele(db, FTAG);
1602
1603         return (0);
1604 }
1605
1606 int
1607 zfs_obj_to_path(objset_t *osp, uint64_t obj, char *buf, int len)
1608 {
1609         char *path = buf + len - 1;
1610         int error;
1611
1612         *path = '\0';
1613
1614         for (;;) {
1615                 uint64_t pobj;
1616                 char component[MAXNAMELEN + 2];
1617                 size_t complen;
1618                 int is_xattrdir;
1619
1620                 if ((error = zfs_obj_to_pobj(osp, obj, &pobj,
1621                     &is_xattrdir)) != 0)
1622                         break;
1623
1624                 if (pobj == obj) {
1625                         if (path[0] != '/')
1626                                 *--path = '/';
1627                         break;
1628                 }
1629
1630                 component[0] = '/';
1631                 if (is_xattrdir) {
1632                         (void) sprintf(component + 1, "<xattrdir>");
1633                 } else {
1634                         error = zap_value_search(osp, pobj, obj,
1635                             ZFS_DIRENT_OBJ(-1ULL), component + 1);
1636                         if (error != 0)
1637                                 break;
1638                 }
1639
1640                 complen = strlen(component);
1641                 path -= complen;
1642                 ASSERT(path >= buf);
1643                 bcopy(component, path, complen);
1644                 obj = pobj;
1645         }
1646
1647         if (error == 0)
1648                 (void) memmove(buf, path, buf + len - path);
1649         return (error);
1650 }