xref: /titanic_41/usr/src/uts/common/fs/zfs/zfs_ctldir.c (revision eb0cc229f19c437a6b538d3ac0d0443268290b7e)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * ZFS control directory (a.k.a. ".zfs")
30  *
31  * This directory provides a common location for all ZFS meta-objects.
32  * Currently, this is only the 'snapshot' directory, but this may expand in the
33  * future.  The elements are built using the GFS primitives, as the hierarchy
34  * does not actually exist on disk.
35  *
36  * For 'snapshot', we don't want to have all snapshots always mounted, because
37  * this would take up a huge amount of space in /etc/mnttab.  We have three
38  * types of objects:
39  *
40  * 	ctldir ------> snapshotdir -------> snapshot
41  *                                             |
42  *                                             |
43  *                                             V
44  *                                         mounted fs
45  *
46  * The 'snapshot' node contains just enough information to lookup '..' and act
47  * as a mountpoint for the snapshot.  Whenever we lookup a specific snapshot, we
48  * perform an automount of the underlying filesystem and return the
49  * corresponding vnode.
50  *
51  * All mounts are handled automatically by the kernel, but unmounts are
52  * (currently) handled from user land.  The main reason is that there is no
53  * reliable way to auto-unmount the filesystem when it's "no longer in use".
54  * When the user unmounts a filesystem, we call zfsctl_unmount(), which
55  * unmounts any snapshots within the snapshot directory.
56  *
57  * The '.zfs', '.zfs/snapshot', and all directories created under
58  * '.zfs/snapshot' (ie: '.zfs/snapshot/<snapname>') are all GFS nodes and
59  * share the same vfs_t as the head filesystem (what '.zfs' lives under).
60  *
61  * File systems mounted ontop of the GFS nodes '.zfs/snapshot/<snapname>'
62  * (ie: snapshots) are ZFS nodes and have their own unique vfs_t.
63  * However, vnodes within these mounted on file systems have their v_vfsp
64  * fields set to the head filesystem to make NFS happy (see
65  * zfsctl_snapdir_lookup()). We VFS_HOLD the head filesystem's vfs_t
66  * so that it cannot be freed until all snapshots have been unmounted.
67  */
68 
69 #include <fs/fs_subr.h>
70 #include <sys/zfs_ctldir.h>
71 #include <sys/zfs_ioctl.h>
72 #include <sys/zfs_vfsops.h>
73 #include <sys/vfs_opreg.h>
74 #include <sys/gfs.h>
75 #include <sys/stat.h>
76 #include <sys/dmu.h>
77 #include <sys/dsl_deleg.h>
78 #include <sys/mount.h>
79 
80 typedef struct zfsctl_node {
81 	gfs_dir_t	zc_gfs_private;
82 	uint64_t	zc_id;
83 	timestruc_t	zc_cmtime;	/* ctime and mtime, always the same */
84 } zfsctl_node_t;
85 
86 typedef struct zfsctl_snapdir {
87 	zfsctl_node_t	sd_node;
88 	kmutex_t	sd_lock;
89 	avl_tree_t	sd_snaps;
90 } zfsctl_snapdir_t;
91 
92 typedef struct {
93 	char		*se_name;
94 	vnode_t		*se_root;
95 	avl_node_t	se_node;
96 } zfs_snapentry_t;
97 
98 static int
99 snapentry_compare(const void *a, const void *b)
100 {
101 	const zfs_snapentry_t *sa = a;
102 	const zfs_snapentry_t *sb = b;
103 	int ret = strcmp(sa->se_name, sb->se_name);
104 
105 	if (ret < 0)
106 		return (-1);
107 	else if (ret > 0)
108 		return (1);
109 	else
110 		return (0);
111 }
112 
113 vnodeops_t *zfsctl_ops_root;
114 vnodeops_t *zfsctl_ops_snapdir;
115 vnodeops_t *zfsctl_ops_snapshot;
116 
117 static const fs_operation_def_t zfsctl_tops_root[];
118 static const fs_operation_def_t zfsctl_tops_snapdir[];
119 static const fs_operation_def_t zfsctl_tops_snapshot[];
120 
121 static vnode_t *zfsctl_mknode_snapdir(vnode_t *);
122 static vnode_t *zfsctl_snapshot_mknode(vnode_t *, uint64_t objset);
123 static int zfsctl_unmount_snap(zfs_snapentry_t *, int, cred_t *);
124 
125 static gfs_opsvec_t zfsctl_opsvec[] = {
126 	{ ".zfs", zfsctl_tops_root, &zfsctl_ops_root },
127 	{ ".zfs/snapshot", zfsctl_tops_snapdir, &zfsctl_ops_snapdir },
128 	{ ".zfs/snapshot/vnode", zfsctl_tops_snapshot, &zfsctl_ops_snapshot },
129 	{ NULL }
130 };
131 
132 /*
133  * Root directory elements.  We have only a single static entry, 'snapshot'.
134  */
135 static gfs_dirent_t zfsctl_root_entries[] = {
136 	{ "snapshot", zfsctl_mknode_snapdir, GFS_CACHE_VNODE },
137 	{ NULL }
138 };
139 
140 /* include . and .. in the calculation */
141 #define	NROOT_ENTRIES	((sizeof (zfsctl_root_entries) / \
142     sizeof (gfs_dirent_t)) + 1)
143 
144 
145 /*
146  * Initialize the various GFS pieces we'll need to create and manipulate .zfs
147  * directories.  This is called from the ZFS init routine, and initializes the
148  * vnode ops vectors that we'll be using.
149  */
150 void
151 zfsctl_init(void)
152 {
153 	VERIFY(gfs_make_opsvec(zfsctl_opsvec) == 0);
154 }
155 
156 void
157 zfsctl_fini(void)
158 {
159 	/*
160 	 * Remove vfsctl vnode ops
161 	 */
162 	if (zfsctl_ops_root)
163 		vn_freevnodeops(zfsctl_ops_root);
164 	if (zfsctl_ops_snapdir)
165 		vn_freevnodeops(zfsctl_ops_snapdir);
166 	if (zfsctl_ops_snapshot)
167 		vn_freevnodeops(zfsctl_ops_snapshot);
168 
169 	zfsctl_ops_root = NULL;
170 	zfsctl_ops_snapdir = NULL;
171 	zfsctl_ops_snapshot = NULL;
172 }
173 
174 /*
175  * Return the inode number associated with the 'snapshot' directory.
176  */
177 /* ARGSUSED */
178 static ino64_t
179 zfsctl_root_inode_cb(vnode_t *vp, int index)
180 {
181 	ASSERT(index == 0);
182 	return (ZFSCTL_INO_SNAPDIR);
183 }
184 
185 /*
186  * Create the '.zfs' directory.  This directory is cached as part of the VFS
187  * structure.  This results in a hold on the vfs_t.  The code in zfs_umount()
188  * therefore checks against a vfs_count of 2 instead of 1.  This reference
189  * is removed when the ctldir is destroyed in the unmount.
190  */
191 void
192 zfsctl_create(zfsvfs_t *zfsvfs)
193 {
194 	vnode_t *vp, *rvp;
195 	zfsctl_node_t *zcp;
196 
197 	ASSERT(zfsvfs->z_ctldir == NULL);
198 
199 	vp = gfs_root_create(sizeof (zfsctl_node_t), zfsvfs->z_vfs,
200 	    zfsctl_ops_root, ZFSCTL_INO_ROOT, zfsctl_root_entries,
201 	    zfsctl_root_inode_cb, MAXNAMELEN, NULL, NULL);
202 	zcp = vp->v_data;
203 	zcp->zc_id = ZFSCTL_INO_ROOT;
204 
205 	VERIFY(VFS_ROOT(zfsvfs->z_vfs, &rvp) == 0);
206 	ZFS_TIME_DECODE(&zcp->zc_cmtime, VTOZ(rvp)->z_phys->zp_crtime);
207 	VN_RELE(rvp);
208 
209 	/*
210 	 * We're only faking the fact that we have a root of a filesystem for
211 	 * the sake of the GFS interfaces.  Undo the flag manipulation it did
212 	 * for us.
213 	 */
214 	vp->v_flag &= ~(VROOT | VNOCACHE | VNOMAP | VNOSWAP | VNOMOUNT);
215 
216 	zfsvfs->z_ctldir = vp;
217 }
218 
219 /*
220  * Destroy the '.zfs' directory.  Only called when the filesystem is unmounted.
221  * There might still be more references if we were force unmounted, but only
222  * new zfs_inactive() calls can occur and they don't reference .zfs
223  */
224 void
225 zfsctl_destroy(zfsvfs_t *zfsvfs)
226 {
227 	VN_RELE(zfsvfs->z_ctldir);
228 	zfsvfs->z_ctldir = NULL;
229 }
230 
231 /*
232  * Given a root znode, retrieve the associated .zfs directory.
233  * Add a hold to the vnode and return it.
234  */
235 vnode_t *
236 zfsctl_root(znode_t *zp)
237 {
238 	ASSERT(zfs_has_ctldir(zp));
239 	VN_HOLD(zp->z_zfsvfs->z_ctldir);
240 	return (zp->z_zfsvfs->z_ctldir);
241 }
242 
243 /*
244  * Common open routine.  Disallow any write access.
245  */
246 /* ARGSUSED */
247 static int
248 zfsctl_common_open(vnode_t **vpp, int flags, cred_t *cr, caller_context_t *ct)
249 {
250 	if (flags & FWRITE)
251 		return (EACCES);
252 
253 	return (0);
254 }
255 
256 /*
257  * Common close routine.  Nothing to do here.
258  */
259 /* ARGSUSED */
260 static int
261 zfsctl_common_close(vnode_t *vpp, int flags, int count, offset_t off,
262     cred_t *cr, caller_context_t *ct)
263 {
264 	return (0);
265 }
266 
267 /*
268  * Common access routine.  Disallow writes.
269  */
270 /* ARGSUSED */
271 static int
272 zfsctl_common_access(vnode_t *vp, int mode, int flags, cred_t *cr,
273     caller_context_t *ct)
274 {
275 	if (mode & VWRITE)
276 		return (EACCES);
277 
278 	return (0);
279 }
280 
281 /*
282  * Common getattr function.  Fill in basic information.
283  */
284 static void
285 zfsctl_common_getattr(vnode_t *vp, vattr_t *vap)
286 {
287 	zfsctl_node_t	*zcp = vp->v_data;
288 	timestruc_t	now;
289 
290 	vap->va_uid = 0;
291 	vap->va_gid = 0;
292 	vap->va_rdev = 0;
293 	/*
294 	 * We are a purly virtual object, so we have no
295 	 * blocksize or allocated blocks.
296 	 */
297 	vap->va_blksize = 0;
298 	vap->va_nblocks = 0;
299 	vap->va_seq = 0;
300 	vap->va_fsid = vp->v_vfsp->vfs_dev;
301 	vap->va_mode = S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP |
302 	    S_IROTH | S_IXOTH;
303 	vap->va_type = VDIR;
304 	/*
305 	 * We live in the now (for atime).
306 	 */
307 	gethrestime(&now);
308 	vap->va_atime = now;
309 	vap->va_mtime = vap->va_ctime = zcp->zc_cmtime;
310 }
311 
312 /*ARGSUSED*/
313 static int
314 zfsctl_common_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
315 {
316 	zfsvfs_t	*zfsvfs = vp->v_vfsp->vfs_data;
317 	zfsctl_node_t	*zcp = vp->v_data;
318 	uint64_t	object = zcp->zc_id;
319 	zfid_short_t	*zfid;
320 	int		i;
321 
322 	ZFS_ENTER(zfsvfs);
323 
324 	if (fidp->fid_len < SHORT_FID_LEN) {
325 		fidp->fid_len = SHORT_FID_LEN;
326 		ZFS_EXIT(zfsvfs);
327 		return (ENOSPC);
328 	}
329 
330 	zfid = (zfid_short_t *)fidp;
331 
332 	zfid->zf_len = SHORT_FID_LEN;
333 
334 	for (i = 0; i < sizeof (zfid->zf_object); i++)
335 		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
336 
337 	/* .zfs znodes always have a generation number of 0 */
338 	for (i = 0; i < sizeof (zfid->zf_gen); i++)
339 		zfid->zf_gen[i] = 0;
340 
341 	ZFS_EXIT(zfsvfs);
342 	return (0);
343 }
344 
345 /*
346  * .zfs inode namespace
347  *
348  * We need to generate unique inode numbers for all files and directories
349  * within the .zfs pseudo-filesystem.  We use the following scheme:
350  *
351  * 	ENTRY			ZFSCTL_INODE
352  * 	.zfs			1
353  * 	.zfs/snapshot		2
354  * 	.zfs/snapshot/<snap>	objectid(snap)
355  */
356 
357 #define	ZFSCTL_INO_SNAP(id)	(id)
358 
359 /*
360  * Get root directory attributes.
361  */
362 /* ARGSUSED */
363 static int
364 zfsctl_root_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
365     caller_context_t *ct)
366 {
367 	zfsvfs_t *zfsvfs = vp->v_vfsp->vfs_data;
368 
369 	ZFS_ENTER(zfsvfs);
370 	vap->va_nodeid = ZFSCTL_INO_ROOT;
371 	vap->va_nlink = vap->va_size = NROOT_ENTRIES;
372 
373 	zfsctl_common_getattr(vp, vap);
374 	ZFS_EXIT(zfsvfs);
375 
376 	return (0);
377 }
378 
379 /*
380  * Special case the handling of "..".
381  */
382 /* ARGSUSED */
383 int
384 zfsctl_root_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, pathname_t *pnp,
385     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
386     int *direntflags, pathname_t *realpnp)
387 {
388 	zfsvfs_t *zfsvfs = dvp->v_vfsp->vfs_data;
389 	int err;
390 
391 	/*
392 	 * No extended attributes allowed under .zfs
393 	 */
394 	if (flags & LOOKUP_XATTR)
395 		return (EINVAL);
396 
397 	ZFS_ENTER(zfsvfs);
398 
399 	if (strcmp(nm, "..") == 0) {
400 		err = VFS_ROOT(dvp->v_vfsp, vpp);
401 	} else {
402 		err = gfs_dir_lookup(dvp, nm, vpp, cr);
403 	}
404 
405 	ZFS_EXIT(zfsvfs);
406 
407 	return (err);
408 }
409 
410 static const fs_operation_def_t zfsctl_tops_root[] = {
411 	{ VOPNAME_OPEN,		{ .vop_open = zfsctl_common_open }	},
412 	{ VOPNAME_CLOSE,	{ .vop_close = zfsctl_common_close }	},
413 	{ VOPNAME_IOCTL,	{ .error = fs_inval }			},
414 	{ VOPNAME_GETATTR,	{ .vop_getattr = zfsctl_root_getattr }	},
415 	{ VOPNAME_ACCESS,	{ .vop_access = zfsctl_common_access }	},
416 	{ VOPNAME_READDIR,	{ .vop_readdir = gfs_vop_readdir } 	},
417 	{ VOPNAME_LOOKUP,	{ .vop_lookup = zfsctl_root_lookup }	},
418 	{ VOPNAME_SEEK,		{ .vop_seek = fs_seek }			},
419 	{ VOPNAME_INACTIVE,	{ .vop_inactive = gfs_vop_inactive }	},
420 	{ VOPNAME_FID,		{ .vop_fid = zfsctl_common_fid	}	},
421 	{ NULL }
422 };
423 
424 static int
425 zfsctl_snapshot_zname(vnode_t *vp, const char *name, int len, char *zname)
426 {
427 	objset_t *os = ((zfsvfs_t *)((vp)->v_vfsp->vfs_data))->z_os;
428 
429 	dmu_objset_name(os, zname);
430 	if (strlen(zname) + 1 + strlen(name) >= len)
431 		return (ENAMETOOLONG);
432 	(void) strcat(zname, "@");
433 	(void) strcat(zname, name);
434 	return (0);
435 }
436 
437 static int
438 zfsctl_unmount_snap(zfs_snapentry_t *sep, int fflags, cred_t *cr)
439 {
440 	vnode_t *svp = sep->se_root;
441 	int error;
442 
443 	ASSERT(vn_ismntpt(svp));
444 
445 	/* this will be dropped by dounmount() */
446 	if ((error = vn_vfswlock(svp)) != 0)
447 		return (error);
448 
449 	VN_HOLD(svp);
450 	error = dounmount(vn_mountedvfs(svp), fflags, cr);
451 	if (error) {
452 		VN_RELE(svp);
453 		return (error);
454 	}
455 	VFS_RELE(svp->v_vfsp);
456 	/*
457 	 * We can't use VN_RELE(), as that will try to invoke
458 	 * zfsctl_snapdir_inactive(), which would cause us to destroy
459 	 * the sd_lock mutex held by our caller.
460 	 */
461 	ASSERT(svp->v_count == 1);
462 	gfs_vop_inactive(svp, cr, NULL);
463 
464 	kmem_free(sep->se_name, strlen(sep->se_name) + 1);
465 	kmem_free(sep, sizeof (zfs_snapentry_t));
466 
467 	return (0);
468 }
469 
470 static void
471 zfsctl_rename_snap(zfsctl_snapdir_t *sdp, zfs_snapentry_t *sep, const char *nm)
472 {
473 	avl_index_t where;
474 	vfs_t *vfsp;
475 	refstr_t *pathref;
476 	char newpath[MAXNAMELEN];
477 	char *tail;
478 
479 	ASSERT(MUTEX_HELD(&sdp->sd_lock));
480 	ASSERT(sep != NULL);
481 
482 	vfsp = vn_mountedvfs(sep->se_root);
483 	ASSERT(vfsp != NULL);
484 
485 	vfs_lock_wait(vfsp);
486 
487 	/*
488 	 * Change the name in the AVL tree.
489 	 */
490 	avl_remove(&sdp->sd_snaps, sep);
491 	kmem_free(sep->se_name, strlen(sep->se_name) + 1);
492 	sep->se_name = kmem_alloc(strlen(nm) + 1, KM_SLEEP);
493 	(void) strcpy(sep->se_name, nm);
494 	VERIFY(avl_find(&sdp->sd_snaps, sep, &where) == NULL);
495 	avl_insert(&sdp->sd_snaps, sep, where);
496 
497 	/*
498 	 * Change the current mountpoint info:
499 	 * 	- update the tail of the mntpoint path
500 	 *	- update the tail of the resource path
501 	 */
502 	pathref = vfs_getmntpoint(vfsp);
503 	(void) strncpy(newpath, refstr_value(pathref), sizeof (newpath));
504 	VERIFY((tail = strrchr(newpath, '/')) != NULL);
505 	*(tail+1) = '\0';
506 	ASSERT3U(strlen(newpath) + strlen(nm), <, sizeof (newpath));
507 	(void) strcat(newpath, nm);
508 	refstr_rele(pathref);
509 	vfs_setmntpoint(vfsp, newpath);
510 
511 	pathref = vfs_getresource(vfsp);
512 	(void) strncpy(newpath, refstr_value(pathref), sizeof (newpath));
513 	VERIFY((tail = strrchr(newpath, '@')) != NULL);
514 	*(tail+1) = '\0';
515 	ASSERT3U(strlen(newpath) + strlen(nm), <, sizeof (newpath));
516 	(void) strcat(newpath, nm);
517 	refstr_rele(pathref);
518 	vfs_setresource(vfsp, newpath);
519 
520 	vfs_unlock(vfsp);
521 }
522 
523 /*ARGSUSED*/
524 static int
525 zfsctl_snapdir_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm,
526     cred_t *cr, caller_context_t *ct, int flags)
527 {
528 	zfsctl_snapdir_t *sdp = sdvp->v_data;
529 	zfs_snapentry_t search, *sep;
530 	avl_index_t where;
531 	char from[MAXNAMELEN], to[MAXNAMELEN];
532 	int err;
533 
534 	err = zfsctl_snapshot_zname(sdvp, snm, MAXNAMELEN, from);
535 	if (err)
536 		return (err);
537 
538 	err = zfsctl_snapshot_zname(tdvp, tnm, MAXNAMELEN, to);
539 	if (err)
540 		return (err);
541 
542 	if (err = zfs_secpolicy_rename_perms(from, to, cr))
543 		return (err);
544 	/*
545 	 * Cannot move snapshots out of the snapdir.
546 	 */
547 	if (sdvp != tdvp)
548 		return (EINVAL);
549 
550 	if (strcmp(snm, tnm) == 0)
551 		return (0);
552 
553 	mutex_enter(&sdp->sd_lock);
554 
555 	search.se_name = (char *)snm;
556 	if ((sep = avl_find(&sdp->sd_snaps, &search, &where)) == NULL) {
557 		mutex_exit(&sdp->sd_lock);
558 		return (ENOENT);
559 	}
560 
561 	err = dmu_objset_rename(from, to, B_FALSE);
562 	if (err == 0)
563 		zfsctl_rename_snap(sdp, sep, tnm);
564 
565 	mutex_exit(&sdp->sd_lock);
566 
567 	return (err);
568 }
569 
570 /* ARGSUSED */
571 static int
572 zfsctl_snapdir_remove(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr,
573     caller_context_t *ct, int flags)
574 {
575 	zfsctl_snapdir_t *sdp = dvp->v_data;
576 	zfs_snapentry_t *sep;
577 	zfs_snapentry_t search;
578 	char snapname[MAXNAMELEN];
579 	int err;
580 
581 	err = zfsctl_snapshot_zname(dvp, name, MAXNAMELEN, snapname);
582 	if (err)
583 		return (err);
584 
585 	if (err = zfs_secpolicy_destroy_perms(snapname, cr))
586 		return (err);
587 
588 	mutex_enter(&sdp->sd_lock);
589 
590 	search.se_name = name;
591 	sep = avl_find(&sdp->sd_snaps, &search, NULL);
592 	if (sep) {
593 		avl_remove(&sdp->sd_snaps, sep);
594 		err = zfsctl_unmount_snap(sep, MS_FORCE, cr);
595 		if (err)
596 			avl_add(&sdp->sd_snaps, sep);
597 		else
598 			err = dmu_objset_destroy(snapname);
599 	} else {
600 		err = ENOENT;
601 	}
602 
603 	mutex_exit(&sdp->sd_lock);
604 
605 	return (err);
606 }
607 
608 /*
609  * This creates a snapshot under '.zfs/snapshot'.
610  */
611 /* ARGSUSED */
612 static int
613 zfsctl_snapdir_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t  **vpp,
614     cred_t *cr, caller_context_t *cc, int flags, vsecattr_t *vsecp)
615 {
616 	zfsvfs_t *zfsvfs = dvp->v_vfsp->vfs_data;
617 	char name[MAXNAMELEN];
618 	int err;
619 	static enum symfollow follow = NO_FOLLOW;
620 	static enum uio_seg seg = UIO_SYSSPACE;
621 
622 	dmu_objset_name(zfsvfs->z_os, name);
623 
624 	*vpp = NULL;
625 
626 	err = zfs_secpolicy_snapshot_perms(name, cr);
627 	if (err)
628 		return (err);
629 
630 	if (err == 0) {
631 		err = dmu_objset_snapshot(name, dirname, B_FALSE);
632 		if (err)
633 			return (err);
634 		err = lookupnameat(dirname, seg, follow, NULL, vpp, dvp);
635 	}
636 
637 	return (err);
638 }
639 
640 /*
641  * Lookup entry point for the 'snapshot' directory.  Try to open the
642  * snapshot if it exist, creating the pseudo filesystem vnode as necessary.
643  * Perform a mount of the associated dataset on top of the vnode.
644  */
645 /* ARGSUSED */
646 static int
647 zfsctl_snapdir_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, pathname_t *pnp,
648     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
649     int *direntflags, pathname_t *realpnp)
650 {
651 	zfsctl_snapdir_t *sdp = dvp->v_data;
652 	objset_t *snap;
653 	char snapname[MAXNAMELEN];
654 	char *mountpoint;
655 	zfs_snapentry_t *sep, search;
656 	struct mounta margs;
657 	vfs_t *vfsp;
658 	size_t mountpoint_len;
659 	avl_index_t where;
660 	zfsvfs_t *zfsvfs = dvp->v_vfsp->vfs_data;
661 	int err;
662 
663 	/*
664 	 * No extended attributes allowed under .zfs
665 	 */
666 	if (flags & LOOKUP_XATTR)
667 		return (EINVAL);
668 
669 	ASSERT(dvp->v_type == VDIR);
670 
671 	if (gfs_lookup_dot(vpp, dvp, zfsvfs->z_ctldir, nm) == 0)
672 		return (0);
673 
674 	/*
675 	 * If we get a recursive call, that means we got called
676 	 * from the domount() code while it was trying to look up the
677 	 * spec (which looks like a local path for zfs).  We need to
678 	 * add some flag to domount() to tell it not to do this lookup.
679 	 */
680 	if (MUTEX_HELD(&sdp->sd_lock))
681 		return (ENOENT);
682 
683 	ZFS_ENTER(zfsvfs);
684 
685 	mutex_enter(&sdp->sd_lock);
686 	search.se_name = (char *)nm;
687 	if ((sep = avl_find(&sdp->sd_snaps, &search, &where)) != NULL) {
688 		*vpp = sep->se_root;
689 		VN_HOLD(*vpp);
690 		err = traverse(vpp);
691 		if (err) {
692 			VN_RELE(*vpp);
693 			*vpp = NULL;
694 		} else if (*vpp == sep->se_root) {
695 			/*
696 			 * The snapshot was unmounted behind our backs,
697 			 * try to remount it.
698 			 */
699 			goto domount;
700 		} else {
701 			/*
702 			 * VROOT was set during the traverse call.  We need
703 			 * to clear it since we're pretending to be part
704 			 * of our parent's vfs.
705 			 */
706 			(*vpp)->v_flag &= ~VROOT;
707 		}
708 		mutex_exit(&sdp->sd_lock);
709 		ZFS_EXIT(zfsvfs);
710 		return (err);
711 	}
712 
713 	/*
714 	 * The requested snapshot is not currently mounted, look it up.
715 	 */
716 	err = zfsctl_snapshot_zname(dvp, nm, MAXNAMELEN, snapname);
717 	if (err) {
718 		mutex_exit(&sdp->sd_lock);
719 		ZFS_EXIT(zfsvfs);
720 		return (err);
721 	}
722 	if (dmu_objset_open(snapname, DMU_OST_ZFS,
723 	    DS_MODE_STANDARD | DS_MODE_READONLY, &snap) != 0) {
724 		mutex_exit(&sdp->sd_lock);
725 		ZFS_EXIT(zfsvfs);
726 		return (ENOENT);
727 	}
728 
729 	sep = kmem_alloc(sizeof (zfs_snapentry_t), KM_SLEEP);
730 	sep->se_name = kmem_alloc(strlen(nm) + 1, KM_SLEEP);
731 	(void) strcpy(sep->se_name, nm);
732 	*vpp = sep->se_root = zfsctl_snapshot_mknode(dvp, dmu_objset_id(snap));
733 	avl_insert(&sdp->sd_snaps, sep, where);
734 
735 	dmu_objset_close(snap);
736 domount:
737 	mountpoint_len = strlen(refstr_value(dvp->v_vfsp->vfs_mntpt)) +
738 	    strlen("/.zfs/snapshot/") + strlen(nm) + 1;
739 	mountpoint = kmem_alloc(mountpoint_len, KM_SLEEP);
740 	(void) snprintf(mountpoint, mountpoint_len, "%s/.zfs/snapshot/%s",
741 	    refstr_value(dvp->v_vfsp->vfs_mntpt), nm);
742 
743 	margs.spec = snapname;
744 	margs.dir = mountpoint;
745 	margs.flags = MS_SYSSPACE | MS_NOMNTTAB;
746 	margs.fstype = "zfs";
747 	margs.dataptr = NULL;
748 	margs.datalen = 0;
749 	margs.optptr = NULL;
750 	margs.optlen = 0;
751 
752 	err = domount("zfs", &margs, *vpp, kcred, &vfsp);
753 	kmem_free(mountpoint, mountpoint_len);
754 
755 	if (err == 0) {
756 		/*
757 		 * Return the mounted root rather than the covered mount point.
758 		 * Takes the GFS vnode at .zfs/snapshot/<snapname> and returns
759 		 * the ZFS vnode mounted on top of the GFS node.  This ZFS
760 		 * vnode is the root the newly created vfsp.
761 		 */
762 		VFS_RELE(vfsp);
763 		err = traverse(vpp);
764 	}
765 
766 	if (err == 0) {
767 		/*
768 		 * Fix up the root vnode mounted on .zfs/snapshot/<snapname>.
769 		 *
770 		 * This is where we lie about our v_vfsp in order to
771 		 * make .zfs/snapshot/<snapname> accessible over NFS
772 		 * without requiring manual mounts of <snapname>.
773 		 */
774 		ASSERT(VTOZ(*vpp)->z_zfsvfs != zfsvfs);
775 		VTOZ(*vpp)->z_zfsvfs->z_parent = zfsvfs;
776 		(*vpp)->v_vfsp = zfsvfs->z_vfs;
777 		(*vpp)->v_flag &= ~VROOT;
778 	}
779 	mutex_exit(&sdp->sd_lock);
780 	ZFS_EXIT(zfsvfs);
781 
782 	/*
783 	 * If we had an error, drop our hold on the vnode and
784 	 * zfsctl_snapshot_inactive() will clean up.
785 	 */
786 	if (err) {
787 		VN_RELE(*vpp);
788 		*vpp = NULL;
789 	}
790 	return (err);
791 }
792 
793 /* ARGSUSED */
794 static int
795 zfsctl_snapdir_readdir_cb(vnode_t *vp, void *dp, int *eofp,
796     offset_t *offp, offset_t *nextp, void *data, int flags)
797 {
798 	zfsvfs_t *zfsvfs = vp->v_vfsp->vfs_data;
799 	char snapname[MAXNAMELEN];
800 	uint64_t id, cookie;
801 	boolean_t case_conflict;
802 	int error;
803 
804 	ZFS_ENTER(zfsvfs);
805 
806 	cookie = *offp;
807 	error = dmu_snapshot_list_next(zfsvfs->z_os, MAXNAMELEN, snapname, &id,
808 	    &cookie, &case_conflict);
809 	if (error) {
810 		ZFS_EXIT(zfsvfs);
811 		if (error == ENOENT) {
812 			*eofp = 1;
813 			return (0);
814 		}
815 		return (error);
816 	}
817 
818 	if (flags & V_RDDIR_ENTFLAGS) {
819 		edirent_t *eodp = dp;
820 
821 		(void) strcpy(eodp->ed_name, snapname);
822 		eodp->ed_ino = ZFSCTL_INO_SNAP(id);
823 		eodp->ed_eflags = case_conflict ? ED_CASE_CONFLICT : 0;
824 	} else {
825 		struct dirent64 *odp = dp;
826 
827 		(void) strcpy(odp->d_name, snapname);
828 		odp->d_ino = ZFSCTL_INO_SNAP(id);
829 	}
830 	*nextp = cookie;
831 
832 	ZFS_EXIT(zfsvfs);
833 
834 	return (0);
835 }
836 
837 /*
838  * pvp is the '.zfs' directory (zfsctl_node_t).
839  * Creates vp, which is '.zfs/snapshot' (zfsctl_snapdir_t).
840  *
841  * This function is the callback to create a GFS vnode for '.zfs/snapshot'
842  * when a lookup is performed on .zfs for "snapshot".
843  */
844 vnode_t *
845 zfsctl_mknode_snapdir(vnode_t *pvp)
846 {
847 	vnode_t *vp;
848 	zfsctl_snapdir_t *sdp;
849 
850 	vp = gfs_dir_create(sizeof (zfsctl_snapdir_t), pvp,
851 	    zfsctl_ops_snapdir, NULL, NULL, MAXNAMELEN,
852 	    zfsctl_snapdir_readdir_cb, NULL);
853 	sdp = vp->v_data;
854 	sdp->sd_node.zc_id = ZFSCTL_INO_SNAPDIR;
855 	sdp->sd_node.zc_cmtime = ((zfsctl_node_t *)pvp->v_data)->zc_cmtime;
856 	mutex_init(&sdp->sd_lock, NULL, MUTEX_DEFAULT, NULL);
857 	avl_create(&sdp->sd_snaps, snapentry_compare,
858 	    sizeof (zfs_snapentry_t), offsetof(zfs_snapentry_t, se_node));
859 	return (vp);
860 }
861 
862 /* ARGSUSED */
863 static int
864 zfsctl_snapdir_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
865     caller_context_t *ct)
866 {
867 	zfsvfs_t *zfsvfs = vp->v_vfsp->vfs_data;
868 	zfsctl_snapdir_t *sdp = vp->v_data;
869 
870 	ZFS_ENTER(zfsvfs);
871 	zfsctl_common_getattr(vp, vap);
872 	vap->va_nodeid = gfs_file_inode(vp);
873 	vap->va_nlink = vap->va_size = avl_numnodes(&sdp->sd_snaps) + 2;
874 	ZFS_EXIT(zfsvfs);
875 
876 	return (0);
877 }
878 
879 /* ARGSUSED */
880 static void
881 zfsctl_snapdir_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
882 {
883 	zfsctl_snapdir_t *sdp = vp->v_data;
884 	void *private;
885 
886 	private = gfs_dir_inactive(vp);
887 	if (private != NULL) {
888 		ASSERT(avl_numnodes(&sdp->sd_snaps) == 0);
889 		mutex_destroy(&sdp->sd_lock);
890 		avl_destroy(&sdp->sd_snaps);
891 		kmem_free(private, sizeof (zfsctl_snapdir_t));
892 	}
893 }
894 
895 static const fs_operation_def_t zfsctl_tops_snapdir[] = {
896 	{ VOPNAME_OPEN,		{ .vop_open = zfsctl_common_open }	},
897 	{ VOPNAME_CLOSE,	{ .vop_close = zfsctl_common_close }	},
898 	{ VOPNAME_IOCTL,	{ .error = fs_inval }			},
899 	{ VOPNAME_GETATTR,	{ .vop_getattr = zfsctl_snapdir_getattr } },
900 	{ VOPNAME_ACCESS,	{ .vop_access = zfsctl_common_access }	},
901 	{ VOPNAME_RENAME,	{ .vop_rename = zfsctl_snapdir_rename }	},
902 	{ VOPNAME_RMDIR,	{ .vop_rmdir = zfsctl_snapdir_remove }	},
903 	{ VOPNAME_MKDIR,	{ .vop_mkdir = zfsctl_snapdir_mkdir }	},
904 	{ VOPNAME_READDIR,	{ .vop_readdir = gfs_vop_readdir }	},
905 	{ VOPNAME_LOOKUP,	{ .vop_lookup = zfsctl_snapdir_lookup }	},
906 	{ VOPNAME_SEEK,		{ .vop_seek = fs_seek }			},
907 	{ VOPNAME_INACTIVE,	{ .vop_inactive = zfsctl_snapdir_inactive } },
908 	{ VOPNAME_FID,		{ .vop_fid = zfsctl_common_fid }	},
909 	{ NULL }
910 };
911 
912 /*
913  * pvp is the GFS vnode '.zfs/snapshot'.
914  *
915  * This creates a GFS node under '.zfs/snapshot' representing each
916  * snapshot.  This newly created GFS node is what we mount snapshot
917  * vfs_t's ontop of.
918  */
919 static vnode_t *
920 zfsctl_snapshot_mknode(vnode_t *pvp, uint64_t objset)
921 {
922 	vnode_t *vp;
923 	zfsctl_node_t *zcp;
924 
925 	vp = gfs_dir_create(sizeof (zfsctl_node_t), pvp,
926 	    zfsctl_ops_snapshot, NULL, NULL, MAXNAMELEN, NULL, NULL);
927 	zcp = vp->v_data;
928 	zcp->zc_id = objset;
929 	VFS_HOLD(vp->v_vfsp);
930 
931 	return (vp);
932 }
933 
934 static void
935 zfsctl_snapshot_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
936 {
937 	zfsctl_snapdir_t *sdp;
938 	zfs_snapentry_t *sep, *next;
939 	vnode_t *dvp;
940 
941 	VERIFY(gfs_dir_lookup(vp, "..", &dvp, cr) == 0);
942 	sdp = dvp->v_data;
943 
944 	mutex_enter(&sdp->sd_lock);
945 
946 	if (vp->v_count > 1) {
947 		mutex_exit(&sdp->sd_lock);
948 		return;
949 	}
950 	ASSERT(!vn_ismntpt(vp));
951 
952 	sep = avl_first(&sdp->sd_snaps);
953 	while (sep != NULL) {
954 		next = AVL_NEXT(&sdp->sd_snaps, sep);
955 
956 		if (sep->se_root == vp) {
957 			avl_remove(&sdp->sd_snaps, sep);
958 			kmem_free(sep->se_name, strlen(sep->se_name) + 1);
959 			kmem_free(sep, sizeof (zfs_snapentry_t));
960 			break;
961 		}
962 		sep = next;
963 	}
964 	ASSERT(sep != NULL);
965 
966 	mutex_exit(&sdp->sd_lock);
967 	VN_RELE(dvp);
968 	VFS_RELE(vp->v_vfsp);
969 
970 	/*
971 	 * Dispose of the vnode for the snapshot mount point.
972 	 * This is safe to do because once this entry has been removed
973 	 * from the AVL tree, it can't be found again, so cannot become
974 	 * "active".  If we lookup the same name again we will end up
975 	 * creating a new vnode.
976 	 */
977 	gfs_vop_inactive(vp, cr, ct);
978 }
979 
980 
981 /*
982  * These VP's should never see the light of day.  They should always
983  * be covered.
984  */
985 static const fs_operation_def_t zfsctl_tops_snapshot[] = {
986 	VOPNAME_INACTIVE, { .vop_inactive =  zfsctl_snapshot_inactive },
987 	NULL, NULL
988 };
989 
990 int
991 zfsctl_lookup_objset(vfs_t *vfsp, uint64_t objsetid, zfsvfs_t **zfsvfsp)
992 {
993 	zfsvfs_t *zfsvfs = vfsp->vfs_data;
994 	vnode_t *dvp, *vp;
995 	zfsctl_snapdir_t *sdp;
996 	zfsctl_node_t *zcp;
997 	zfs_snapentry_t *sep;
998 	int error;
999 
1000 	ASSERT(zfsvfs->z_ctldir != NULL);
1001 	error = zfsctl_root_lookup(zfsvfs->z_ctldir, "snapshot", &dvp,
1002 	    NULL, 0, NULL, kcred, NULL, NULL, NULL);
1003 	if (error != 0)
1004 		return (error);
1005 	sdp = dvp->v_data;
1006 
1007 	mutex_enter(&sdp->sd_lock);
1008 	sep = avl_first(&sdp->sd_snaps);
1009 	while (sep != NULL) {
1010 		vp = sep->se_root;
1011 		zcp = vp->v_data;
1012 		if (zcp->zc_id == objsetid)
1013 			break;
1014 
1015 		sep = AVL_NEXT(&sdp->sd_snaps, sep);
1016 	}
1017 
1018 	if (sep != NULL) {
1019 		VN_HOLD(vp);
1020 		/*
1021 		 * Return the mounted root rather than the covered mount point.
1022 		 * Takes the GFS vnode at .zfs/snapshot/<snapshot objsetid>
1023 		 * and returns the ZFS vnode mounted on top of the GFS node.
1024 		 * This ZFS vnode is the root of the vfs for objset 'objsetid'.
1025 		 */
1026 		error = traverse(&vp);
1027 		if (error == 0) {
1028 			if (vp == sep->se_root)
1029 				error = EINVAL;
1030 			else
1031 				*zfsvfsp = VTOZ(vp)->z_zfsvfs;
1032 		}
1033 		mutex_exit(&sdp->sd_lock);
1034 		VN_RELE(vp);
1035 	} else {
1036 		error = EINVAL;
1037 		mutex_exit(&sdp->sd_lock);
1038 	}
1039 
1040 	VN_RELE(dvp);
1041 
1042 	return (error);
1043 }
1044 
1045 /*
1046  * Unmount any snapshots for the given filesystem.  This is called from
1047  * zfs_umount() - if we have a ctldir, then go through and unmount all the
1048  * snapshots.
1049  */
1050 int
1051 zfsctl_umount_snapshots(vfs_t *vfsp, int fflags, cred_t *cr)
1052 {
1053 	zfsvfs_t *zfsvfs = vfsp->vfs_data;
1054 	vnode_t *dvp;
1055 	zfsctl_snapdir_t *sdp;
1056 	zfs_snapentry_t *sep, *next;
1057 	int error;
1058 
1059 	ASSERT(zfsvfs->z_ctldir != NULL);
1060 	error = zfsctl_root_lookup(zfsvfs->z_ctldir, "snapshot", &dvp,
1061 	    NULL, 0, NULL, cr, NULL, NULL, NULL);
1062 	if (error != 0)
1063 		return (error);
1064 	sdp = dvp->v_data;
1065 
1066 	mutex_enter(&sdp->sd_lock);
1067 
1068 	sep = avl_first(&sdp->sd_snaps);
1069 	while (sep != NULL) {
1070 		next = AVL_NEXT(&sdp->sd_snaps, sep);
1071 
1072 		/*
1073 		 * If this snapshot is not mounted, then it must
1074 		 * have just been unmounted by somebody else, and
1075 		 * will be cleaned up by zfsctl_snapdir_inactive().
1076 		 */
1077 		if (vn_ismntpt(sep->se_root)) {
1078 			avl_remove(&sdp->sd_snaps, sep);
1079 			error = zfsctl_unmount_snap(sep, fflags, cr);
1080 			if (error) {
1081 				avl_add(&sdp->sd_snaps, sep);
1082 				break;
1083 			}
1084 		}
1085 		sep = next;
1086 	}
1087 
1088 	mutex_exit(&sdp->sd_lock);
1089 	VN_RELE(dvp);
1090 
1091 	return (error);
1092 }
1093