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