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