]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/zfs/zfs_ctldir.c
Don't use d_path() for automount mount point for chroot'd process
[FreeBSD/FreeBSD.git] / module / zfs / zfs_ctldir.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  *
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (C) 2011 Lawrence Livermore National Security, LLC.
25  * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
26  * LLNL-CODE-403049.
27  * Rewritten for Linux by:
28  *   Rohan Puri <rohan.puri15@gmail.com>
29  *   Brian Behlendorf <behlendorf1@llnl.gov>
30  * Copyright (c) 2013 by Delphix. All rights reserved.
31  * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
32  * Copyright (c) 2018 George Melikov. All Rights Reserved.
33  */
34
35 /*
36  * ZFS control directory (a.k.a. ".zfs")
37  *
38  * This directory provides a common location for all ZFS meta-objects.
39  * Currently, this is only the 'snapshot' and 'shares' directory, but this may
40  * expand in the future.  The elements are built dynamically, as the hierarchy
41  * does not actually exist on disk.
42  *
43  * For 'snapshot', we don't want to have all snapshots always mounted, because
44  * this would take up a huge amount of space in /etc/mnttab.  We have three
45  * types of objects:
46  *
47  *      ctldir ------> snapshotdir -------> snapshot
48  *                                             |
49  *                                             |
50  *                                             V
51  *                                         mounted fs
52  *
53  * The 'snapshot' node contains just enough information to lookup '..' and act
54  * as a mountpoint for the snapshot.  Whenever we lookup a specific snapshot, we
55  * perform an automount of the underlying filesystem and return the
56  * corresponding inode.
57  *
58  * All mounts are handled automatically by an user mode helper which invokes
59  * the mount procedure.  Unmounts are handled by allowing the mount
60  * point to expire so the kernel may automatically unmount it.
61  *
62  * The '.zfs', '.zfs/snapshot', and all directories created under
63  * '.zfs/snapshot' (ie: '.zfs/snapshot/<snapname>') all share the same
64  * zfsvfs_t as the head filesystem (what '.zfs' lives under).
65  *
66  * File systems mounted on top of the '.zfs/snapshot/<snapname>' paths
67  * (ie: snapshots) are complete ZFS filesystems and have their own unique
68  * zfsvfs_t.  However, the fsid reported by these mounts will be the same
69  * as that used by the parent zfsvfs_t to make NFS happy.
70  */
71
72 #include <sys/types.h>
73 #include <sys/param.h>
74 #include <sys/time.h>
75 #include <sys/sysmacros.h>
76 #include <sys/pathname.h>
77 #include <sys/vfs.h>
78 #include <sys/zfs_ctldir.h>
79 #include <sys/zfs_ioctl.h>
80 #include <sys/zfs_vfsops.h>
81 #include <sys/zfs_vnops.h>
82 #include <sys/stat.h>
83 #include <sys/dmu.h>
84 #include <sys/dmu_objset.h>
85 #include <sys/dsl_destroy.h>
86 #include <sys/dsl_deleg.h>
87 #include <sys/zpl.h>
88 #include <sys/mntent.h>
89 #include "zfs_namecheck.h"
90
91 /*
92  * Two AVL trees are maintained which contain all currently automounted
93  * snapshots.  Every automounted snapshots maps to a single zfs_snapentry_t
94  * entry which MUST:
95  *
96  *   - be attached to both trees, and
97  *   - be unique, no duplicate entries are allowed.
98  *
99  * The zfs_snapshots_by_name tree is indexed by the full dataset name
100  * while the zfs_snapshots_by_objsetid tree is indexed by the unique
101  * objsetid.  This allows for fast lookups either by name or objsetid.
102  */
103 static avl_tree_t zfs_snapshots_by_name;
104 static avl_tree_t zfs_snapshots_by_objsetid;
105 static krwlock_t zfs_snapshot_lock;
106
107 /*
108  * Control Directory Tunables (.zfs)
109  */
110 int zfs_expire_snapshot = ZFSCTL_EXPIRE_SNAPSHOT;
111 int zfs_admin_snapshot = 0;
112
113 typedef struct {
114         char            *se_name;       /* full snapshot name */
115         char            *se_path;       /* full mount path */
116         spa_t           *se_spa;        /* pool spa */
117         uint64_t        se_objsetid;    /* snapshot objset id */
118         struct dentry   *se_root_dentry; /* snapshot root dentry */
119         taskqid_t       se_taskqid;     /* scheduled unmount taskqid */
120         avl_node_t      se_node_name;   /* zfs_snapshots_by_name link */
121         avl_node_t      se_node_objsetid; /* zfs_snapshots_by_objsetid link */
122         zfs_refcount_t  se_refcount;    /* reference count */
123 } zfs_snapentry_t;
124
125 static void zfsctl_snapshot_unmount_delay_impl(zfs_snapentry_t *se, int delay);
126
127 /*
128  * Allocate a new zfs_snapentry_t being careful to make a copy of the
129  * the snapshot name and provided mount point.  No reference is taken.
130  */
131 static zfs_snapentry_t *
132 zfsctl_snapshot_alloc(char *full_name, char *full_path, spa_t *spa,
133     uint64_t objsetid, struct dentry *root_dentry)
134 {
135         zfs_snapentry_t *se;
136
137         se = kmem_zalloc(sizeof (zfs_snapentry_t), KM_SLEEP);
138
139         se->se_name = strdup(full_name);
140         se->se_path = strdup(full_path);
141         se->se_spa = spa;
142         se->se_objsetid = objsetid;
143         se->se_root_dentry = root_dentry;
144         se->se_taskqid = TASKQID_INVALID;
145
146         zfs_refcount_create(&se->se_refcount);
147
148         return (se);
149 }
150
151 /*
152  * Free a zfs_snapentry_t the caller must ensure there are no active
153  * references.
154  */
155 static void
156 zfsctl_snapshot_free(zfs_snapentry_t *se)
157 {
158         zfs_refcount_destroy(&se->se_refcount);
159         strfree(se->se_name);
160         strfree(se->se_path);
161
162         kmem_free(se, sizeof (zfs_snapentry_t));
163 }
164
165 /*
166  * Hold a reference on the zfs_snapentry_t.
167  */
168 static void
169 zfsctl_snapshot_hold(zfs_snapentry_t *se)
170 {
171         zfs_refcount_add(&se->se_refcount, NULL);
172 }
173
174 /*
175  * Release a reference on the zfs_snapentry_t.  When the number of
176  * references drops to zero the structure will be freed.
177  */
178 static void
179 zfsctl_snapshot_rele(zfs_snapentry_t *se)
180 {
181         if (zfs_refcount_remove(&se->se_refcount, NULL) == 0)
182                 zfsctl_snapshot_free(se);
183 }
184
185 /*
186  * Add a zfs_snapentry_t to both the zfs_snapshots_by_name and
187  * zfs_snapshots_by_objsetid trees.  While the zfs_snapentry_t is part
188  * of the trees a reference is held.
189  */
190 static void
191 zfsctl_snapshot_add(zfs_snapentry_t *se)
192 {
193         ASSERT(RW_WRITE_HELD(&zfs_snapshot_lock));
194         zfs_refcount_add(&se->se_refcount, NULL);
195         avl_add(&zfs_snapshots_by_name, se);
196         avl_add(&zfs_snapshots_by_objsetid, se);
197 }
198
199 /*
200  * Remove a zfs_snapentry_t from both the zfs_snapshots_by_name and
201  * zfs_snapshots_by_objsetid trees.  Upon removal a reference is dropped,
202  * this can result in the structure being freed if that was the last
203  * remaining reference.
204  */
205 static void
206 zfsctl_snapshot_remove(zfs_snapentry_t *se)
207 {
208         ASSERT(RW_WRITE_HELD(&zfs_snapshot_lock));
209         avl_remove(&zfs_snapshots_by_name, se);
210         avl_remove(&zfs_snapshots_by_objsetid, se);
211         zfsctl_snapshot_rele(se);
212 }
213
214 /*
215  * Snapshot name comparison function for the zfs_snapshots_by_name.
216  */
217 static int
218 snapentry_compare_by_name(const void *a, const void *b)
219 {
220         const zfs_snapentry_t *se_a = a;
221         const zfs_snapentry_t *se_b = b;
222         int ret;
223
224         ret = strcmp(se_a->se_name, se_b->se_name);
225
226         if (ret < 0)
227                 return (-1);
228         else if (ret > 0)
229                 return (1);
230         else
231                 return (0);
232 }
233
234 /*
235  * Snapshot name comparison function for the zfs_snapshots_by_objsetid.
236  */
237 static int
238 snapentry_compare_by_objsetid(const void *a, const void *b)
239 {
240         const zfs_snapentry_t *se_a = a;
241         const zfs_snapentry_t *se_b = b;
242
243         if (se_a->se_spa != se_b->se_spa)
244                 return ((ulong_t)se_a->se_spa < (ulong_t)se_b->se_spa ? -1 : 1);
245
246         if (se_a->se_objsetid < se_b->se_objsetid)
247                 return (-1);
248         else if (se_a->se_objsetid > se_b->se_objsetid)
249                 return (1);
250         else
251                 return (0);
252 }
253
254 /*
255  * Find a zfs_snapentry_t in zfs_snapshots_by_name.  If the snapname
256  * is found a pointer to the zfs_snapentry_t is returned and a reference
257  * taken on the structure.  The caller is responsible for dropping the
258  * reference with zfsctl_snapshot_rele().  If the snapname is not found
259  * NULL will be returned.
260  */
261 static zfs_snapentry_t *
262 zfsctl_snapshot_find_by_name(char *snapname)
263 {
264         zfs_snapentry_t *se, search;
265
266         ASSERT(RW_LOCK_HELD(&zfs_snapshot_lock));
267
268         search.se_name = snapname;
269         se = avl_find(&zfs_snapshots_by_name, &search, NULL);
270         if (se)
271                 zfs_refcount_add(&se->se_refcount, NULL);
272
273         return (se);
274 }
275
276 /*
277  * Find a zfs_snapentry_t in zfs_snapshots_by_objsetid given the objset id
278  * rather than the snapname.  In all other respects it behaves the same
279  * as zfsctl_snapshot_find_by_name().
280  */
281 static zfs_snapentry_t *
282 zfsctl_snapshot_find_by_objsetid(spa_t *spa, uint64_t objsetid)
283 {
284         zfs_snapentry_t *se, search;
285
286         ASSERT(RW_LOCK_HELD(&zfs_snapshot_lock));
287
288         search.se_spa = spa;
289         search.se_objsetid = objsetid;
290         se = avl_find(&zfs_snapshots_by_objsetid, &search, NULL);
291         if (se)
292                 zfs_refcount_add(&se->se_refcount, NULL);
293
294         return (se);
295 }
296
297 /*
298  * Rename a zfs_snapentry_t in the zfs_snapshots_by_name.  The structure is
299  * removed, renamed, and added back to the new correct location in the tree.
300  */
301 static int
302 zfsctl_snapshot_rename(char *old_snapname, char *new_snapname)
303 {
304         zfs_snapentry_t *se;
305
306         ASSERT(RW_WRITE_HELD(&zfs_snapshot_lock));
307
308         se = zfsctl_snapshot_find_by_name(old_snapname);
309         if (se == NULL)
310                 return (SET_ERROR(ENOENT));
311
312         zfsctl_snapshot_remove(se);
313         strfree(se->se_name);
314         se->se_name = strdup(new_snapname);
315         zfsctl_snapshot_add(se);
316         zfsctl_snapshot_rele(se);
317
318         return (0);
319 }
320
321 /*
322  * Delayed task responsible for unmounting an expired automounted snapshot.
323  */
324 static void
325 snapentry_expire(void *data)
326 {
327         zfs_snapentry_t *se = (zfs_snapentry_t *)data;
328         spa_t *spa = se->se_spa;
329         uint64_t objsetid = se->se_objsetid;
330
331         if (zfs_expire_snapshot <= 0) {
332                 zfsctl_snapshot_rele(se);
333                 return;
334         }
335
336         se->se_taskqid = TASKQID_INVALID;
337         (void) zfsctl_snapshot_unmount(se->se_name, MNT_EXPIRE);
338         zfsctl_snapshot_rele(se);
339
340         /*
341          * Reschedule the unmount if the zfs_snapentry_t wasn't removed.
342          * This can occur when the snapshot is busy.
343          */
344         rw_enter(&zfs_snapshot_lock, RW_READER);
345         if ((se = zfsctl_snapshot_find_by_objsetid(spa, objsetid)) != NULL) {
346                 zfsctl_snapshot_unmount_delay_impl(se, zfs_expire_snapshot);
347                 zfsctl_snapshot_rele(se);
348         }
349         rw_exit(&zfs_snapshot_lock);
350 }
351
352 /*
353  * Cancel an automatic unmount of a snapname.  This callback is responsible
354  * for dropping the reference on the zfs_snapentry_t which was taken when
355  * during dispatch.
356  */
357 static void
358 zfsctl_snapshot_unmount_cancel(zfs_snapentry_t *se)
359 {
360         if (taskq_cancel_id(system_delay_taskq, se->se_taskqid) == 0) {
361                 se->se_taskqid = TASKQID_INVALID;
362                 zfsctl_snapshot_rele(se);
363         }
364 }
365
366 /*
367  * Dispatch the unmount task for delayed handling with a hold protecting it.
368  */
369 static void
370 zfsctl_snapshot_unmount_delay_impl(zfs_snapentry_t *se, int delay)
371 {
372         ASSERT3S(se->se_taskqid, ==, TASKQID_INVALID);
373
374         if (delay <= 0)
375                 return;
376
377         zfsctl_snapshot_hold(se);
378         se->se_taskqid = taskq_dispatch_delay(system_delay_taskq,
379             snapentry_expire, se, TQ_SLEEP, ddi_get_lbolt() + delay * HZ);
380 }
381
382 /*
383  * Schedule an automatic unmount of objset id to occur in delay seconds from
384  * now.  Any previous delayed unmount will be cancelled in favor of the
385  * updated deadline.  A reference is taken by zfsctl_snapshot_find_by_name()
386  * and held until the outstanding task is handled or cancelled.
387  */
388 int
389 zfsctl_snapshot_unmount_delay(spa_t *spa, uint64_t objsetid, int delay)
390 {
391         zfs_snapentry_t *se;
392         int error = ENOENT;
393
394         rw_enter(&zfs_snapshot_lock, RW_READER);
395         if ((se = zfsctl_snapshot_find_by_objsetid(spa, objsetid)) != NULL) {
396                 zfsctl_snapshot_unmount_cancel(se);
397                 zfsctl_snapshot_unmount_delay_impl(se, delay);
398                 zfsctl_snapshot_rele(se);
399                 error = 0;
400         }
401         rw_exit(&zfs_snapshot_lock);
402
403         return (error);
404 }
405
406 /*
407  * Check if snapname is currently mounted.  Returned non-zero when mounted
408  * and zero when unmounted.
409  */
410 static boolean_t
411 zfsctl_snapshot_ismounted(char *snapname)
412 {
413         zfs_snapentry_t *se;
414         boolean_t ismounted = B_FALSE;
415
416         rw_enter(&zfs_snapshot_lock, RW_READER);
417         if ((se = zfsctl_snapshot_find_by_name(snapname)) != NULL) {
418                 zfsctl_snapshot_rele(se);
419                 ismounted = B_TRUE;
420         }
421         rw_exit(&zfs_snapshot_lock);
422
423         return (ismounted);
424 }
425
426 /*
427  * Check if the given inode is a part of the virtual .zfs directory.
428  */
429 boolean_t
430 zfsctl_is_node(struct inode *ip)
431 {
432         return (ITOZ(ip)->z_is_ctldir);
433 }
434
435 /*
436  * Check if the given inode is a .zfs/snapshots/snapname directory.
437  */
438 boolean_t
439 zfsctl_is_snapdir(struct inode *ip)
440 {
441         return (zfsctl_is_node(ip) && (ip->i_ino <= ZFSCTL_INO_SNAPDIRS));
442 }
443
444 /*
445  * Allocate a new inode with the passed id and ops.
446  */
447 static struct inode *
448 zfsctl_inode_alloc(zfsvfs_t *zfsvfs, uint64_t id,
449     const struct file_operations *fops, const struct inode_operations *ops)
450 {
451         inode_timespec_t now;
452         struct inode *ip;
453         znode_t *zp;
454
455         ip = new_inode(zfsvfs->z_sb);
456         if (ip == NULL)
457                 return (NULL);
458
459         now = current_time(ip);
460         zp = ITOZ(ip);
461         ASSERT3P(zp->z_dirlocks, ==, NULL);
462         ASSERT3P(zp->z_acl_cached, ==, NULL);
463         ASSERT3P(zp->z_xattr_cached, ==, NULL);
464         zp->z_id = id;
465         zp->z_unlinked = 0;
466         zp->z_atime_dirty = 0;
467         zp->z_zn_prefetch = 0;
468         zp->z_moved = 0;
469         zp->z_sa_hdl = NULL;
470         zp->z_blksz = 0;
471         zp->z_seq = 0;
472         zp->z_mapcnt = 0;
473         zp->z_size = 0;
474         zp->z_pflags = 0;
475         zp->z_mode = 0;
476         zp->z_sync_cnt = 0;
477         zp->z_is_mapped = B_FALSE;
478         zp->z_is_ctldir = B_TRUE;
479         zp->z_is_sa = B_FALSE;
480         zp->z_is_stale = B_FALSE;
481         ip->i_generation = 0;
482         ip->i_ino = id;
483         ip->i_mode = (S_IFDIR | S_IRWXUGO);
484         ip->i_uid = SUID_TO_KUID(0);
485         ip->i_gid = SGID_TO_KGID(0);
486         ip->i_blkbits = SPA_MINBLOCKSHIFT;
487         ip->i_atime = now;
488         ip->i_mtime = now;
489         ip->i_ctime = now;
490         ip->i_fop = fops;
491         ip->i_op = ops;
492 #if defined(IOP_XATTR)
493         ip->i_opflags &= ~IOP_XATTR;
494 #endif
495
496         if (insert_inode_locked(ip)) {
497                 unlock_new_inode(ip);
498                 iput(ip);
499                 return (NULL);
500         }
501
502         mutex_enter(&zfsvfs->z_znodes_lock);
503         list_insert_tail(&zfsvfs->z_all_znodes, zp);
504         zfsvfs->z_nr_znodes++;
505         membar_producer();
506         mutex_exit(&zfsvfs->z_znodes_lock);
507
508         unlock_new_inode(ip);
509
510         return (ip);
511 }
512
513 /*
514  * Lookup the inode with given id, it will be allocated if needed.
515  */
516 static struct inode *
517 zfsctl_inode_lookup(zfsvfs_t *zfsvfs, uint64_t id,
518     const struct file_operations *fops, const struct inode_operations *ops)
519 {
520         struct inode *ip = NULL;
521
522         while (ip == NULL) {
523                 ip = ilookup(zfsvfs->z_sb, (unsigned long)id);
524                 if (ip)
525                         break;
526
527                 /* May fail due to concurrent zfsctl_inode_alloc() */
528                 ip = zfsctl_inode_alloc(zfsvfs, id, fops, ops);
529         }
530
531         return (ip);
532 }
533
534 /*
535  * Create the '.zfs' directory.  This directory is cached as part of the VFS
536  * structure.  This results in a hold on the zfsvfs_t.  The code in zfs_umount()
537  * therefore checks against a vfs_count of 2 instead of 1.  This reference
538  * is removed when the ctldir is destroyed in the unmount.  All other entities
539  * under the '.zfs' directory are created dynamically as needed.
540  *
541  * Because the dynamically created '.zfs' directory entries assume the use
542  * of 64-bit inode numbers this support must be disabled on 32-bit systems.
543  */
544 int
545 zfsctl_create(zfsvfs_t *zfsvfs)
546 {
547         ASSERT(zfsvfs->z_ctldir == NULL);
548
549         zfsvfs->z_ctldir = zfsctl_inode_alloc(zfsvfs, ZFSCTL_INO_ROOT,
550             &zpl_fops_root, &zpl_ops_root);
551         if (zfsvfs->z_ctldir == NULL)
552                 return (SET_ERROR(ENOENT));
553
554         return (0);
555 }
556
557 /*
558  * Destroy the '.zfs' directory or remove a snapshot from zfs_snapshots_by_name.
559  * Only called when the filesystem is unmounted.
560  */
561 void
562 zfsctl_destroy(zfsvfs_t *zfsvfs)
563 {
564         if (zfsvfs->z_issnap) {
565                 zfs_snapentry_t *se;
566                 spa_t *spa = zfsvfs->z_os->os_spa;
567                 uint64_t objsetid = dmu_objset_id(zfsvfs->z_os);
568
569                 rw_enter(&zfs_snapshot_lock, RW_WRITER);
570                 se = zfsctl_snapshot_find_by_objsetid(spa, objsetid);
571                 if (se != NULL)
572                         zfsctl_snapshot_remove(se);
573                 rw_exit(&zfs_snapshot_lock);
574                 if (se != NULL) {
575                         zfsctl_snapshot_unmount_cancel(se);
576                         zfsctl_snapshot_rele(se);
577                 }
578         } else if (zfsvfs->z_ctldir) {
579                 iput(zfsvfs->z_ctldir);
580                 zfsvfs->z_ctldir = NULL;
581         }
582 }
583
584 /*
585  * Given a root znode, retrieve the associated .zfs directory.
586  * Add a hold to the vnode and return it.
587  */
588 struct inode *
589 zfsctl_root(znode_t *zp)
590 {
591         ASSERT(zfs_has_ctldir(zp));
592         igrab(ZTOZSB(zp)->z_ctldir);
593         return (ZTOZSB(zp)->z_ctldir);
594 }
595
596 /*
597  * Generate a long fid to indicate a snapdir. We encode whether snapdir is
598  * already monunted in gen field. We do this because nfsd lookup will not
599  * trigger automount. Next time the nfsd does fh_to_dentry, we will notice
600  * this and do automount and return ESTALE to force nfsd revalidate and follow
601  * mount.
602  */
603 static int
604 zfsctl_snapdir_fid(struct inode *ip, fid_t *fidp)
605 {
606         zfid_short_t *zfid = (zfid_short_t *)fidp;
607         zfid_long_t *zlfid = (zfid_long_t *)fidp;
608         uint32_t gen = 0;
609         uint64_t object;
610         uint64_t objsetid;
611         int i;
612         struct dentry *dentry;
613
614         if (fidp->fid_len < LONG_FID_LEN) {
615                 fidp->fid_len = LONG_FID_LEN;
616                 return (SET_ERROR(ENOSPC));
617         }
618
619         object = ip->i_ino;
620         objsetid = ZFSCTL_INO_SNAPDIRS - ip->i_ino;
621         zfid->zf_len = LONG_FID_LEN;
622
623         dentry = d_obtain_alias(igrab(ip));
624         if (!IS_ERR(dentry)) {
625                 gen = !!d_mountpoint(dentry);
626                 dput(dentry);
627         }
628
629         for (i = 0; i < sizeof (zfid->zf_object); i++)
630                 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
631
632         for (i = 0; i < sizeof (zfid->zf_gen); i++)
633                 zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
634
635         for (i = 0; i < sizeof (zlfid->zf_setid); i++)
636                 zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
637
638         for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
639                 zlfid->zf_setgen[i] = 0;
640
641         return (0);
642 }
643
644 /*
645  * Generate an appropriate fid for an entry in the .zfs directory.
646  */
647 int
648 zfsctl_fid(struct inode *ip, fid_t *fidp)
649 {
650         znode_t         *zp = ITOZ(ip);
651         zfsvfs_t        *zfsvfs = ITOZSB(ip);
652         uint64_t        object = zp->z_id;
653         zfid_short_t    *zfid;
654         int             i;
655
656         ZFS_ENTER(zfsvfs);
657
658         if (zfsctl_is_snapdir(ip)) {
659                 ZFS_EXIT(zfsvfs);
660                 return (zfsctl_snapdir_fid(ip, fidp));
661         }
662
663         if (fidp->fid_len < SHORT_FID_LEN) {
664                 fidp->fid_len = SHORT_FID_LEN;
665                 ZFS_EXIT(zfsvfs);
666                 return (SET_ERROR(ENOSPC));
667         }
668
669         zfid = (zfid_short_t *)fidp;
670
671         zfid->zf_len = SHORT_FID_LEN;
672
673         for (i = 0; i < sizeof (zfid->zf_object); i++)
674                 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
675
676         /* .zfs znodes always have a generation number of 0 */
677         for (i = 0; i < sizeof (zfid->zf_gen); i++)
678                 zfid->zf_gen[i] = 0;
679
680         ZFS_EXIT(zfsvfs);
681         return (0);
682 }
683
684 /*
685  * Construct a full dataset name in full_name: "pool/dataset@snap_name"
686  */
687 static int
688 zfsctl_snapshot_name(zfsvfs_t *zfsvfs, const char *snap_name, int len,
689     char *full_name)
690 {
691         objset_t *os = zfsvfs->z_os;
692
693         if (zfs_component_namecheck(snap_name, NULL, NULL) != 0)
694                 return (SET_ERROR(EILSEQ));
695
696         dmu_objset_name(os, full_name);
697         if ((strlen(full_name) + 1 + strlen(snap_name)) >= len)
698                 return (SET_ERROR(ENAMETOOLONG));
699
700         (void) strcat(full_name, "@");
701         (void) strcat(full_name, snap_name);
702
703         return (0);
704 }
705
706 /*
707  * Returns full path in full_path: "/pool/dataset/.zfs/snapshot/snap_name/"
708  */
709 static int
710 zfsctl_snapshot_path_objset(zfsvfs_t *zfsvfs, uint64_t objsetid,
711     int path_len, char *full_path)
712 {
713         objset_t *os = zfsvfs->z_os;
714         fstrans_cookie_t cookie;
715         char *snapname;
716         boolean_t case_conflict;
717         uint64_t id, pos = 0;
718         int error = 0;
719
720         if (zfsvfs->z_vfs->vfs_mntpoint == NULL)
721                 return (SET_ERROR(ENOENT));
722
723         cookie = spl_fstrans_mark();
724         snapname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
725
726         while (error == 0) {
727                 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
728                 error = dmu_snapshot_list_next(zfsvfs->z_os,
729                     ZFS_MAX_DATASET_NAME_LEN, snapname, &id, &pos,
730                     &case_conflict);
731                 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
732                 if (error)
733                         goto out;
734
735                 if (id == objsetid)
736                         break;
737         }
738
739         snprintf(full_path, path_len, "%s/.zfs/snapshot/%s",
740             zfsvfs->z_vfs->vfs_mntpoint, snapname);
741 out:
742         kmem_free(snapname, ZFS_MAX_DATASET_NAME_LEN);
743         spl_fstrans_unmark(cookie);
744
745         return (error);
746 }
747
748 /*
749  * Special case the handling of "..".
750  */
751 int
752 zfsctl_root_lookup(struct inode *dip, char *name, struct inode **ipp,
753     int flags, cred_t *cr, int *direntflags, pathname_t *realpnp)
754 {
755         zfsvfs_t *zfsvfs = ITOZSB(dip);
756         int error = 0;
757
758         ZFS_ENTER(zfsvfs);
759
760         if (strcmp(name, "..") == 0) {
761                 *ipp = dip->i_sb->s_root->d_inode;
762         } else if (strcmp(name, ZFS_SNAPDIR_NAME) == 0) {
763                 *ipp = zfsctl_inode_lookup(zfsvfs, ZFSCTL_INO_SNAPDIR,
764                     &zpl_fops_snapdir, &zpl_ops_snapdir);
765         } else if (strcmp(name, ZFS_SHAREDIR_NAME) == 0) {
766                 *ipp = zfsctl_inode_lookup(zfsvfs, ZFSCTL_INO_SHARES,
767                     &zpl_fops_shares, &zpl_ops_shares);
768         } else {
769                 *ipp = NULL;
770         }
771
772         if (*ipp == NULL)
773                 error = SET_ERROR(ENOENT);
774
775         ZFS_EXIT(zfsvfs);
776
777         return (error);
778 }
779
780 /*
781  * Lookup entry point for the 'snapshot' directory.  Try to open the
782  * snapshot if it exist, creating the pseudo filesystem inode as necessary.
783  */
784 int
785 zfsctl_snapdir_lookup(struct inode *dip, char *name, struct inode **ipp,
786     int flags, cred_t *cr, int *direntflags, pathname_t *realpnp)
787 {
788         zfsvfs_t *zfsvfs = ITOZSB(dip);
789         uint64_t id;
790         int error;
791
792         ZFS_ENTER(zfsvfs);
793
794         error = dmu_snapshot_lookup(zfsvfs->z_os, name, &id);
795         if (error) {
796                 ZFS_EXIT(zfsvfs);
797                 return (error);
798         }
799
800         *ipp = zfsctl_inode_lookup(zfsvfs, ZFSCTL_INO_SNAPDIRS - id,
801             &simple_dir_operations, &simple_dir_inode_operations);
802         if (*ipp == NULL)
803                 error = SET_ERROR(ENOENT);
804
805         ZFS_EXIT(zfsvfs);
806
807         return (error);
808 }
809
810 /*
811  * Renaming a directory under '.zfs/snapshot' will automatically trigger
812  * a rename of the snapshot to the new given name.  The rename is confined
813  * to the '.zfs/snapshot' directory snapshots cannot be moved elsewhere.
814  */
815 int
816 zfsctl_snapdir_rename(struct inode *sdip, char *snm,
817     struct inode *tdip, char *tnm, cred_t *cr, int flags)
818 {
819         zfsvfs_t *zfsvfs = ITOZSB(sdip);
820         char *to, *from, *real, *fsname;
821         int error;
822
823         if (!zfs_admin_snapshot)
824                 return (SET_ERROR(EACCES));
825
826         ZFS_ENTER(zfsvfs);
827
828         to = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
829         from = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
830         real = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
831         fsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
832
833         if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE) {
834                 error = dmu_snapshot_realname(zfsvfs->z_os, snm, real,
835                     ZFS_MAX_DATASET_NAME_LEN, NULL);
836                 if (error == 0) {
837                         snm = real;
838                 } else if (error != ENOTSUP) {
839                         goto out;
840                 }
841         }
842
843         dmu_objset_name(zfsvfs->z_os, fsname);
844
845         error = zfsctl_snapshot_name(ITOZSB(sdip), snm,
846             ZFS_MAX_DATASET_NAME_LEN, from);
847         if (error == 0)
848                 error = zfsctl_snapshot_name(ITOZSB(tdip), tnm,
849                     ZFS_MAX_DATASET_NAME_LEN, to);
850         if (error == 0)
851                 error = zfs_secpolicy_rename_perms(from, to, cr);
852         if (error != 0)
853                 goto out;
854
855         /*
856          * Cannot move snapshots out of the snapdir.
857          */
858         if (sdip != tdip) {
859                 error = SET_ERROR(EINVAL);
860                 goto out;
861         }
862
863         /*
864          * No-op when names are identical.
865          */
866         if (strcmp(snm, tnm) == 0) {
867                 error = 0;
868                 goto out;
869         }
870
871         rw_enter(&zfs_snapshot_lock, RW_WRITER);
872
873         error = dsl_dataset_rename_snapshot(fsname, snm, tnm, B_FALSE);
874         if (error == 0)
875                 (void) zfsctl_snapshot_rename(snm, tnm);
876
877         rw_exit(&zfs_snapshot_lock);
878 out:
879         kmem_free(from, ZFS_MAX_DATASET_NAME_LEN);
880         kmem_free(to, ZFS_MAX_DATASET_NAME_LEN);
881         kmem_free(real, ZFS_MAX_DATASET_NAME_LEN);
882         kmem_free(fsname, ZFS_MAX_DATASET_NAME_LEN);
883
884         ZFS_EXIT(zfsvfs);
885
886         return (error);
887 }
888
889 /*
890  * Removing a directory under '.zfs/snapshot' will automatically trigger
891  * the removal of the snapshot with the given name.
892  */
893 int
894 zfsctl_snapdir_remove(struct inode *dip, char *name, cred_t *cr, int flags)
895 {
896         zfsvfs_t *zfsvfs = ITOZSB(dip);
897         char *snapname, *real;
898         int error;
899
900         if (!zfs_admin_snapshot)
901                 return (SET_ERROR(EACCES));
902
903         ZFS_ENTER(zfsvfs);
904
905         snapname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
906         real = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
907
908         if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE) {
909                 error = dmu_snapshot_realname(zfsvfs->z_os, name, real,
910                     ZFS_MAX_DATASET_NAME_LEN, NULL);
911                 if (error == 0) {
912                         name = real;
913                 } else if (error != ENOTSUP) {
914                         goto out;
915                 }
916         }
917
918         error = zfsctl_snapshot_name(ITOZSB(dip), name,
919             ZFS_MAX_DATASET_NAME_LEN, snapname);
920         if (error == 0)
921                 error = zfs_secpolicy_destroy_perms(snapname, cr);
922         if (error != 0)
923                 goto out;
924
925         error = zfsctl_snapshot_unmount(snapname, MNT_FORCE);
926         if ((error == 0) || (error == ENOENT))
927                 error = dsl_destroy_snapshot(snapname, B_FALSE);
928 out:
929         kmem_free(snapname, ZFS_MAX_DATASET_NAME_LEN);
930         kmem_free(real, ZFS_MAX_DATASET_NAME_LEN);
931
932         ZFS_EXIT(zfsvfs);
933
934         return (error);
935 }
936
937 /*
938  * Creating a directory under '.zfs/snapshot' will automatically trigger
939  * the creation of a new snapshot with the given name.
940  */
941 int
942 zfsctl_snapdir_mkdir(struct inode *dip, char *dirname, vattr_t *vap,
943     struct inode **ipp, cred_t *cr, int flags)
944 {
945         zfsvfs_t *zfsvfs = ITOZSB(dip);
946         char *dsname;
947         int error;
948
949         if (!zfs_admin_snapshot)
950                 return (SET_ERROR(EACCES));
951
952         dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
953
954         if (zfs_component_namecheck(dirname, NULL, NULL) != 0) {
955                 error = SET_ERROR(EILSEQ);
956                 goto out;
957         }
958
959         dmu_objset_name(zfsvfs->z_os, dsname);
960
961         error = zfs_secpolicy_snapshot_perms(dsname, cr);
962         if (error != 0)
963                 goto out;
964
965         if (error == 0) {
966                 error = dmu_objset_snapshot_one(dsname, dirname);
967                 if (error != 0)
968                         goto out;
969
970                 error = zfsctl_snapdir_lookup(dip, dirname, ipp,
971                     0, cr, NULL, NULL);
972         }
973 out:
974         kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);
975
976         return (error);
977 }
978
979 /*
980  * Attempt to unmount a snapshot by making a call to user space.
981  * There is no assurance that this can or will succeed, is just a
982  * best effort.  In the case where it does fail, perhaps because
983  * it's in use, the unmount will fail harmlessly.
984  */
985 int
986 zfsctl_snapshot_unmount(char *snapname, int flags)
987 {
988         char *argv[] = { "/usr/bin/env", "umount", "-t", "zfs", "-n", NULL,
989             NULL };
990         char *envp[] = { NULL };
991         zfs_snapentry_t *se;
992         int error;
993
994         rw_enter(&zfs_snapshot_lock, RW_READER);
995         if ((se = zfsctl_snapshot_find_by_name(snapname)) == NULL) {
996                 rw_exit(&zfs_snapshot_lock);
997                 return (SET_ERROR(ENOENT));
998         }
999         rw_exit(&zfs_snapshot_lock);
1000
1001         if (flags & MNT_FORCE)
1002                 argv[4] = "-fn";
1003         argv[5] = se->se_path;
1004         dprintf("unmount; path=%s\n", se->se_path);
1005         error = call_usermodehelper(argv[0], argv, envp, UMH_WAIT_PROC);
1006         zfsctl_snapshot_rele(se);
1007
1008
1009         /*
1010          * The umount system utility will return 256 on error.  We must
1011          * assume this error is because the file system is busy so it is
1012          * converted to the more sensible EBUSY.
1013          */
1014         if (error)
1015                 error = SET_ERROR(EBUSY);
1016
1017         return (error);
1018 }
1019
1020 int
1021 zfsctl_snapshot_mount(struct path *path, int flags)
1022 {
1023         struct dentry *dentry = path->dentry;
1024         struct inode *ip = dentry->d_inode;
1025         zfsvfs_t *zfsvfs;
1026         zfsvfs_t *snap_zfsvfs;
1027         zfs_snapentry_t *se;
1028         char *full_name, *full_path;
1029         char *argv[] = { "/usr/bin/env", "mount", "-t", "zfs", "-n", NULL, NULL,
1030             NULL };
1031         char *envp[] = { NULL };
1032         int error;
1033         struct path spath;
1034
1035         if (ip == NULL)
1036                 return (SET_ERROR(EISDIR));
1037
1038         zfsvfs = ITOZSB(ip);
1039         ZFS_ENTER(zfsvfs);
1040
1041         full_name = kmem_zalloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
1042         full_path = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1043
1044         error = zfsctl_snapshot_name(zfsvfs, dname(dentry),
1045             ZFS_MAX_DATASET_NAME_LEN, full_name);
1046         if (error)
1047                 goto error;
1048
1049         /*
1050          * Construct a mount point path from sb of the ctldir inode and dirent
1051          * name, instead of from d_path(), so that chroot'd process doesn't fail
1052          * on mount.zfs(8).
1053          */
1054         snprintf(full_path, MAXPATHLEN, "%s/.zfs/snapshot/%s",
1055             zfsvfs->z_vfs->vfs_mntpoint, dname(dentry));
1056
1057         /*
1058          * Multiple concurrent automounts of a snapshot are never allowed.
1059          * The snapshot may be manually mounted as many times as desired.
1060          */
1061         if (zfsctl_snapshot_ismounted(full_name)) {
1062                 error = 0;
1063                 goto error;
1064         }
1065
1066         /*
1067          * Attempt to mount the snapshot from user space.  Normally this
1068          * would be done using the vfs_kern_mount() function, however that
1069          * function is marked GPL-only and cannot be used.  On error we
1070          * careful to log the real error to the console and return EISDIR
1071          * to safely abort the automount.  This should be very rare.
1072          *
1073          * If the user mode helper happens to return EBUSY, a concurrent
1074          * mount is already in progress in which case the error is ignored.
1075          * Take note that if the program was executed successfully the return
1076          * value from call_usermodehelper() will be (exitcode << 8 + signal).
1077          */
1078         dprintf("mount; name=%s path=%s\n", full_name, full_path);
1079         argv[5] = full_name;
1080         argv[6] = full_path;
1081         error = call_usermodehelper(argv[0], argv, envp, UMH_WAIT_PROC);
1082         if (error) {
1083                 if (!(error & MOUNT_BUSY << 8)) {
1084                         cmn_err(CE_WARN, "Unable to automount %s/%s: %d",
1085                             full_path, full_name, error);
1086                         error = SET_ERROR(EISDIR);
1087                 } else {
1088                         /*
1089                          * EBUSY, this could mean a concurrent mount, or the
1090                          * snapshot has already been mounted at completely
1091                          * different place. We return 0 so VFS will retry. For
1092                          * the latter case the VFS will retry several times
1093                          * and return ELOOP, which is probably not a very good
1094                          * behavior.
1095                          */
1096                         error = 0;
1097                 }
1098                 goto error;
1099         }
1100
1101         /*
1102          * Follow down in to the mounted snapshot and set MNT_SHRINKABLE
1103          * to identify this as an automounted filesystem.
1104          */
1105         spath = *path;
1106         path_get(&spath);
1107         if (zpl_follow_down_one(&spath)) {
1108                 snap_zfsvfs = ITOZSB(spath.dentry->d_inode);
1109                 snap_zfsvfs->z_parent = zfsvfs;
1110                 dentry = spath.dentry;
1111                 spath.mnt->mnt_flags |= MNT_SHRINKABLE;
1112
1113                 rw_enter(&zfs_snapshot_lock, RW_WRITER);
1114                 se = zfsctl_snapshot_alloc(full_name, full_path,
1115                     snap_zfsvfs->z_os->os_spa, dmu_objset_id(snap_zfsvfs->z_os),
1116                     dentry);
1117                 zfsctl_snapshot_add(se);
1118                 zfsctl_snapshot_unmount_delay_impl(se, zfs_expire_snapshot);
1119                 rw_exit(&zfs_snapshot_lock);
1120         }
1121         path_put(&spath);
1122 error:
1123         kmem_free(full_name, ZFS_MAX_DATASET_NAME_LEN);
1124         kmem_free(full_path, MAXPATHLEN);
1125
1126         ZFS_EXIT(zfsvfs);
1127
1128         return (error);
1129 }
1130
1131 /*
1132  * Get the snapdir inode from fid
1133  */
1134 int
1135 zfsctl_snapdir_vget(struct super_block *sb, uint64_t objsetid, int gen,
1136     struct inode **ipp)
1137 {
1138         int error;
1139         struct path path;
1140         char *mnt;
1141         struct dentry *dentry;
1142
1143         mnt = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1144
1145         error = zfsctl_snapshot_path_objset(sb->s_fs_info, objsetid,
1146             MAXPATHLEN, mnt);
1147         if (error)
1148                 goto out;
1149
1150         /* Trigger automount */
1151         error = -kern_path(mnt, LOOKUP_FOLLOW|LOOKUP_DIRECTORY, &path);
1152         if (error)
1153                 goto out;
1154
1155         path_put(&path);
1156         /*
1157          * Get the snapdir inode. Note, we don't want to use the above
1158          * path because it contains the root of the snapshot rather
1159          * than the snapdir.
1160          */
1161         *ipp = ilookup(sb, ZFSCTL_INO_SNAPDIRS - objsetid);
1162         if (*ipp == NULL) {
1163                 error = SET_ERROR(ENOENT);
1164                 goto out;
1165         }
1166
1167         /* check gen, see zfsctl_snapdir_fid */
1168         dentry = d_obtain_alias(igrab(*ipp));
1169         if (gen != (!IS_ERR(dentry) && d_mountpoint(dentry))) {
1170                 iput(*ipp);
1171                 *ipp = NULL;
1172                 error = SET_ERROR(ENOENT);
1173         }
1174         if (!IS_ERR(dentry))
1175                 dput(dentry);
1176 out:
1177         kmem_free(mnt, MAXPATHLEN);
1178         return (error);
1179 }
1180
1181 int
1182 zfsctl_shares_lookup(struct inode *dip, char *name, struct inode **ipp,
1183     int flags, cred_t *cr, int *direntflags, pathname_t *realpnp)
1184 {
1185         zfsvfs_t *zfsvfs = ITOZSB(dip);
1186         struct inode *ip;
1187         znode_t *dzp;
1188         int error;
1189
1190         ZFS_ENTER(zfsvfs);
1191
1192         if (zfsvfs->z_shares_dir == 0) {
1193                 ZFS_EXIT(zfsvfs);
1194                 return (SET_ERROR(ENOTSUP));
1195         }
1196
1197         if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &dzp)) == 0) {
1198                 error = zfs_lookup(ZTOI(dzp), name, &ip, 0, cr, NULL, NULL);
1199                 iput(ZTOI(dzp));
1200         }
1201
1202         ZFS_EXIT(zfsvfs);
1203
1204         return (error);
1205 }
1206
1207 /*
1208  * Initialize the various pieces we'll need to create and manipulate .zfs
1209  * directories.  Currently this is unused but available.
1210  */
1211 void
1212 zfsctl_init(void)
1213 {
1214         avl_create(&zfs_snapshots_by_name, snapentry_compare_by_name,
1215             sizeof (zfs_snapentry_t), offsetof(zfs_snapentry_t,
1216             se_node_name));
1217         avl_create(&zfs_snapshots_by_objsetid, snapentry_compare_by_objsetid,
1218             sizeof (zfs_snapentry_t), offsetof(zfs_snapentry_t,
1219             se_node_objsetid));
1220         rw_init(&zfs_snapshot_lock, NULL, RW_DEFAULT, NULL);
1221 }
1222
1223 /*
1224  * Cleanup the various pieces we needed for .zfs directories.  In particular
1225  * ensure the expiry timer is canceled safely.
1226  */
1227 void
1228 zfsctl_fini(void)
1229 {
1230         avl_destroy(&zfs_snapshots_by_name);
1231         avl_destroy(&zfs_snapshots_by_objsetid);
1232         rw_destroy(&zfs_snapshot_lock);
1233 }
1234
1235 module_param(zfs_admin_snapshot, int, 0644);
1236 MODULE_PARM_DESC(zfs_admin_snapshot, "Enable mkdir/rmdir/mv in .zfs/snapshot");
1237
1238 module_param(zfs_expire_snapshot, int, 0644);
1239 MODULE_PARM_DESC(zfs_expire_snapshot, "Seconds to expire .zfs/snapshot");