1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * This file and its contents are supplied under the terms of the
4 * Common Development and Distribution License ("CDDL"), version 1.0.
5 * You may only use this file in accordance with the terms of version
6 * 1.0 of the CDDL.
7 *
8 * A full copy of the text of the CDDL should have accompanied this
9 * source. A copy of the CDDL is also available via the Internet at
10 * https://opensource.org/license/CDDL-1.0.
11 */
12 /*
13 *
14 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
15 * Copyright (C) 2011 Lawrence Livermore National Security, LLC.
16 * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
17 * LLNL-CODE-403049.
18 * Rewritten for Linux by:
19 * Rohan Puri <rohan.puri15@gmail.com>
20 * Brian Behlendorf <behlendorf1@llnl.gov>
21 * Copyright (c) 2013 by Delphix. All rights reserved.
22 * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
23 * Copyright (c) 2018 George Melikov. All Rights Reserved.
24 * Copyright (c) 2019 Datto, Inc. All rights reserved.
25 * Copyright (c) 2020 The MathWorks, Inc. All rights reserved.
26 * Copyright (c) 2026, TrueNAS.
27 */
28
29 /*
30 * ZFS control directory (a.k.a. ".zfs")
31 *
32 * This directory provides a common location for all ZFS meta-objects.
33 * Currently, this is only the 'snapshot' and 'shares' directory, but this may
34 * expand in the future. The elements are built dynamically, as the hierarchy
35 * does not actually exist on disk.
36 */
37
38 /*
39 * # Snapdir overview
40 *
41 * The bulk of this file is the "snapdir" system, that manages automatically
42 * mounting snapshots when accessed through the .zfs/snapshot/<snapname>
43 * virtual directories.
44 *
45 * This on-demand system exists so we don't have all snapshots mounted at all
46 * times, which both uses memory and makes the mount table (read: `df` output)
47 * enormous.
48 *
49 * Instead, we create some virtual inodes and directory entries in the root of
50 * each dataset (subject to the `snapdir` property):
51 *
52 * .zfs/
53 * snapshot/
54 * snapshot_1/
55 * snapshot_2/
56 * snapshot_3/
57 * ...
58 *
59 * The dentries for the named snapshot nodes have a custom set of operations
60 * attached, most importantly d_automount = zpl_snapdir_automount(). When the
61 * kernel attempts a path walk through one of these nodes, the automount
62 * function is called, which in turn calls into zfsctl_snapshot_mount(). That
63 * function creates the mount and returns it, and the VFS splices it into the
64 * global filesystem tree, then retries the path walk, enters the new mount and
65 * continues as normal.
66 *
67 * When setting up the mount, we also set up the "expiry timer" task. After
68 * `zfs_expire_snapshot` seconds (default: 300), the task checks the if the
69 * mount has been idle for the entire interval. If it has, it is unmounted; if
70 * not, the timer is reset and will try again later. This is done to keep
71 * memory usage and the mount table tidy, by only keeping snapshot mounts
72 * around for the time they're in use.
73 *
74 * This overview is good enough for basic understanding of the system, but the
75 * details are rather more complex.
76 *
77 * ## Source location
78 *
79 * This description covers functions in three separate files:
80 *
81 * - zpl.h: zfs_snapentry_t, related enums and macros
82 * - zpl_ctldir.c: inode and dentry operations and utility functions
83 * - zfs_ctldir.c: mount creation, expiry task, unmount coordination
84 *
85 * This is fairly standard for the Linux ZPL, however the coupling between
86 * the two "sides" is rather tighter than other subsystems, since almost all
87 * of this is about manipulating the snapdir dentry in the right way.
88 *
89 * ## State: zfs_snapentry_t
90 *
91 * We manage the current state for each snapdir in a zfs_snapentry_t. This
92 * struct is allocated in zpl_snapdir_init_snapentry() when the dentry is first
93 * initialised, and destroyed in zpl_snapdir_release() when the kernel destroys
94 * the dentry. The two refer to each other; the snapentry is in
95 * dentry->d_fsdata, while the dentry is in se->se_dentry.
96 *
97 * The dentry and the snapentry have the same lifetime, and are entirely
98 * managed by the kernel from the dentry side. As such, there is no separate
99 * hold for the snapentry; to pin it when we need it, we use the a normal
100 * dget/dput pair.
101 *
102 * # Mounting: d_manage and d_automount
103 *
104 * The dentry_operations has two functions that are wired in to the kernel's
105 * mount traversal loop (__traverse_mounts()) for the automount system.
106 *
107 * Our d_automount is zpl_snapdir_automount(). On its own, it is almost
108 * entirely what you'd expect - it calls zfsctl_snapshot_mount(), and on
109 * success, passes the vfsmount back to the VFS.
110 *
111 * Our d_manage, zpl_snapdir_manage(), is rather more complicated. d_manage is
112 * also known as MANAGE_TRANSIT. It's a place where the filesystem can hold
113 * (block) callers while d_automount is in progress, since d_automount's
114 * purpose is to actually prepare and return the mount. d_manage has two
115 * different ways it can be called ("RCU-walk" and "REF-walk"), and a bunch of
116 * different returns to signal different things back to the kernel. Ultimately
117 * though we're checking if a mount or unmount is in progress by waiting for
118 * the SE_BUSY flag to clear, or we're return success to allow the thread to
119 * proceed into either the mount or d_automount, or we're returning some error
120 * code to request a different behaviour. This is exactly what this callback is
121 * for, so there's not much more to say here that isn't covered in the kernel
122 * docs and the comments.
123 *
124 * There is however one special feature we have that needs a bit more work to
125 * enable and so a bit more explanation. The `zfs_snapshot_no_setuid` tunable
126 * when enabled causes automounted snapshots to receive the `nosuid` mount
127 * option, preventing setuid executables on the snapshot to be run.
128 *
129 * The VFS unfortunately overwrites the options on the vfsmount returned by
130 * d_automount with those of the parent mount, without exception. So setting
131 * MNT_NOSUID on the mount has no effect, nor do superblock options like
132 * SB_NOSUID that would be transferred to the mount in a conventional mount.
133 *
134 * To work around this, when the first mount request arrives in
135 * zpl_snapdir_manage(), we note its task pointer in se_mount_task, then
136 * initiate a new path walk directly into the snapdir dentry via
137 * zpl_follow_down(). This arrives back in zpl_snapdir_manage(), where we
138 * recognise it as the se_mount_task and immediately let it proceed into
139 * zpl_snapdir_automount(). The mount happens and we return it and the VFS
140 * grafts it into the tree, overwriting the mount flags. zpl_follow_down()
141 * returns into zpl_snapdir_manage() with a reference to the vfsmount that
142 * was grafted. The mount is live, but not yet accessed because all threads
143 * are blocked in zpl_snapdir_manage(), waiting on SE_BUSY before they can be
144 * released into the mount. We have unfettered access to the vfsmount _after_
145 * the VFS has trampled it, and we call zfsctl_snapshot_finish_mount() to
146 * apply MNT_NOSUID if necessary.
147 *
148 * This workaround causes another problem, which we also have to work around.
149 * Normally a path walk comes with an "intent" via a set of LOOKUP_ flags
150 * describing what the path walk is for. Normally, the automount will only be
151 * triggered for functions that need to properly "enter" the mount. Since
152 * it's not the original calling thread that is triggering the automount,
153 * these flags are not honoured, resulting in even a simple stat() call on
154 * the unmounted snapdir to trigger the mount. To work around this, we check
155 * the lookup intent flags in zpl_snapdir_lookup() and zpl_snapdir_revalidate()
156 * and set the SE_WANT_MOUNT flag if anything wants the mount, and then decide
157 * whether or not to trigger it based on that flag.
158 *
159 * This explainer is longer than the code. I feel ok about that.
160 *
161 * ## Unmounting: invalidating the mountpoint
162 *
163 * Linux mounts are somewhat ephemeral. Technically, they're a separate
164 * object that binds a "lower" dentry (the "mountpoint") to an "upper" dentry
165 * (the "mount root", typically the root of a different filesystem). From
166 * there, they act as a "transit" point, controlling traversal from one
167 * filesystem to another, possibly applying changes to the operation along
168 * the way (eg changing namespaces). Ordinarily, the mountpoint dentry holds
169 * a reference to the mount, and the mount holds a reference to the root
170 * dentry. When files are opened, they also take references to the mount, which
171 * are released when the file is closed.
172 *
173 * It's these refcounts that keep the entire mount alive. The traditional
174 * umount(2) checks the refcount on the mount, and if it is 1 (ie just the
175 * mountpoint), it can be detached from the mountpoint, which lowers its
176 * refcount to 0, which release the root dentry, triggering a cascade of
177 * reference drops which tears down the entire filesystem structure. If the
178 * mount refcount is >1, then the filesystem is still in use, and umount
179 * fails with EBUSY.
180 *
181 * These refcounts are also what allow the myriad mount options. A "lazy"
182 * umount (MS_DETACH) omits the refcount check, it just detaches the mount
183 * from the mountpoint dentry. If there are no other references (ie its not
184 * in use), the cascade happens and we get a full unmount, otherwise it will
185 * remain alive until all references are released (eg files closed). This is
186 * the same mechanism allows "anonymous" mounts.
187 *
188 * Bind (MS_BIND) mounts follow from this: they create a new mount, with an
189 * existing dentry as the "root" (not even necessarily a filesytem root!).
190 * MS_MOVE meanwhile is just taking an existing mount and atomically detaching
191 * it from its mountpoint and attaching it to another.
192 *
193 * These are all fundamental features of the Linux VFS, and put us in an
194 * interesting position. While we can create a mount and attach it to a known
195 * dentry that we can control, we have no say in what happens after that.
196 * The mount we created might be unmounted by someone else, moved away, or
197 * a bind mount created. There could be a totally unrelated mount on the
198 * snapdir dentry, even for a non-ZFS filesystem. Or a whole stack of mounts.
199 * And, we will not know anything about them, and possibly have no way to
200 * control them.
201 *
202 * So, we instead focus on what we can control: the snapdir dentry (mountpoint)
203 * itself. Regardless of what might be "on top", we can always invalidate
204 * the dentry, reducing the refcount of any mount that might be attached to it.
205 * If there are no other references, then we get the reference drop cascade
206 * and effectively get an "unmount". If there are, then we have done the
207 * equivalent of a MS_DETACH unmount; the mount lives on "somewhere" until
208 * its users are finished, but the ctldir is clear.
209 *
210 * In all cases we care about, this is acceptable. If the mount is the one we
211 * mounted, then if its still in use, the next thing (eg dataset destruction)
212 * will fail with EBUSY, but that is correct anyway; it's not the snapdir's
213 * job to throw off users or things like that. If the operator has unmounted
214 * or moved the snapshot mount away, invalidating the dentry will do nothing,
215 * but that's fine too - the operator has done something strange, it's on them
216 * to sort it out. The same is true of mounting something weird on the snapdir;
217 * we don't know what's happening, but the operator has done something very
218 * odd and it's not up to us to second guess that.
219 *
220 * ## Multiple mounts
221 *
222 * The same dataset can be mounted in several places at once, sharing one
223 * superblock and so one control dentry per snapshot. A mount is keyed on
224 * (parent vfsmount, mountpoint dentry), so each place the dataset is mounted
225 * gets its own snapshot mount grafted onto that single shared control dentry.
226 * This is why zpl_snapdir_manage() tests for an existing mount with
227 * follow_down_one() (this parent) and not d_mountpoint() (true if _any_ parent
228 * has one) - getting that wrong loops the walk into automount retries (ELOOP).
229 * Conversely d_invalidate() tears down _every_ mount on the dentry regardless
230 * of parent, so one invalidate cleans up all of them at once.
231 *
232 * ## Mount expiry
233 *
234 * In zfsctl_snapshot_finish_mount(), we call zfsctl_snapshot_timer_set() to
235 * queue a delay task. When it fires, zfsctl_snapshot_timer_task() is called,
236 * which simply calls zfsctl_snapshot_invalidate(). If it's busy, the
237 * timer is re-armed and we try again next time.
238 *
239 * "Busy-ness" is determined by two timestmaps that are updated to the jiffy
240 * clock value when certain events occur:
241 *
242 * - se_atime is updated in zpl_snapdir_revalidate() and in
243 * zfsctl_snapdir_vget(), which are both places where the snapdir is crossed,
244 * ie something did a lookup inside the mounted snapshot.
245 *
246 * - z_snap_atime is updated in zfs_exit()->zfs_exit_fs() when a data access
247 * inside the snapshot completes.
248 *
249 * The snapshot is considered "busy" if the most recent of these timestamps
250 * is more recent than the expiry timout (zfs_expire_snapshot, 300s by
251 * default). Tracking both is necessary as lookups do not imply data access
252 * and vice-versa, especially for NFS which maintains direct object
253 * references and may never actually do a lookup.
254 *
255 * As above, "expiry" means invalidating the dentry, which simply remove the
256 * mount from view; if its still in use "on the inside" it will continue to
257 * work, and a new mount will be created on next lookup.
258 *
259 * ## Unmount by name
260 *
261 * Unmounting is a side-effect for many ZFS ioctls eg `zfs destroy`,
262 * `zfs rollback`, etc. zfsctl_snapshot_unmount() needs to find a mounted
263 * snapshot entirely by name. It does this by finding the zfsvfs for the
264 * containing dataset, then walking down through the control dir to find
265 * the snapdir dentry, retrieve the zfs_snapentry_t from it, and attempt
266 * an unmount. This is involved; see that function for details.
267 *
268 * ## NFS flush
269 *
270 * The in-kernel NFS server can pin dentries, blocking an unmount. We don't
271 * care about this in the expiry case, since the NFS cache will drop unused
272 * entries after a while.
273 *
274 * However, if we are trying to unmount a snapshot as part of some admin
275 * operation, we don't want the NFS cache being the only thing holding the
276 * snapshot alive, preventing the operation. We try to detect this possibilty
277 * in zfsctl_snapshot_unmount() by seeing if the snapshot is still alive
278 * somewhere, and in those cases call zfsctl_snapshot_unmount_nfs_flush()
279 * to flush the cache in the hopes it will release the mount. See those two
280 * functions for more info.
281 *
282 * ## Note for future spelunkers
283 *
284 * Much of the complexity here is due to ZFS wanting a lot more control over
285 * mounts (both snapshot and the more conventional kind) than the kernel wants
286 * or expects, while some of it is working around "missing" functionality that
287 * the kernel doesn't provide or expose (eg direct access to mount objects).
288 *
289 * There are two "obvious" shortcuts that appear to make the code a lot
290 * simpler but you should avoid, because they both induce use-after-frees:
291 *
292 * - Keeping a pointer to the snapshot's or the parent's vfsmount. You cannot
293 * mntget() either of these, as the kernel will consider a mount "busy" and
294 * not even consider releasing it if its refcount > 1 (ie the mountpoint
295 * only). Holding a snapshot ref would cause an operator unmount to EBUSY;
296 * Holding a parent ref would block the entire parent dataset's teardown.
297 * We only ever touch the mount transiently via follow_down_one(), and never
298 * store one.
299 *
300 * - Holding a backpointer from the snapshot's zfsvfs to the snapentry (to
301 * bump se_atime on data access). The snapshot superblock is shared across
302 * every mount of that snapshot, including container binds and manual mounts.
303 * Since it outlives the control dentry and its snapentry, its pointer would
304 * dangle. This is why se_atime is only ever bumped from the control side.
305 */
306
307 #include <sys/types.h>
308 #include <sys/param.h>
309 #include <sys/time.h>
310 #include <sys/sysmacros.h>
311 #include <sys/pathname.h>
312 #include <sys/vfs.h>
313 #include <sys/zfs_ctldir.h>
314 #include <sys/zfs_ioctl.h>
315 #include <sys/zfs_vfsops.h>
316 #include <sys/zfs_vnops.h>
317 #include <sys/stat.h>
318 #include <sys/dmu.h>
319 #include <sys/dmu_objset.h>
320 #include <sys/dsl_destroy.h>
321 #include <sys/dsl_deleg.h>
322 #include <sys/zpl.h>
323 #include <sys/mntent.h>
324 #include <sys/zfs_ioctl_impl.h>
325 #include <linux/fs_context.h>
326 #include <linux/workqueue_compat.h>
327 #include "zfs_namecheck.h"
328
329 /*
330 * Control Directory Tunables (.zfs)
331 */
332 int zfs_expire_snapshot = ZFSCTL_EXPIRE_SNAPSHOT;
333 static int zfs_admin_snapshot = 0;
334 static int zfs_snapshot_no_setuid = 0;
335
336 static void zfsctl_snapshot_timer_set(zfs_snapentry_t *se, unsigned long delay);
337 static int zfsctl_snapshot_invalidate(zfs_snapentry_t *se,
338 unsigned long *delay);
339
340 /*
341 * Delayed task responsible for unmounting an expired automounted snapshot.
342 */
343 static void
zfsctl_snapshot_timer_task(void * data)344 zfsctl_snapshot_timer_task(void *data)
345 {
346 zfs_snapentry_t *se = (zfs_snapentry_t *)data;
347
348 /*
349 * We need to protect against a tricky race here.
350 *
351 * The dentry manages the lifetime for the snapentry, and this async
352 * timer task has a pointer to the snapentry. If the dentry was to
353 * be destroyed while the timer is still queued or active, the
354 * snapentry would be destroyed out from under it.
355 *
356 * The obvious solution is to take an additional dentry reference when
357 * the timer is armed, and release it when it is canceled, but then
358 * the timer has effectively "pinned" the dentry - it can't be released
359 * until the timer runs to completion.
360 *
361 * So, in zpl_snapdir_release(), we move to cancel the timer in
362 * blocking mode, before the dentry is deallocated. This keeps the
363 * dentry (and so the snapentry) allocated.
364 *
365 * However, there is a gap. This timer task may run _after_ the last
366 * call to dput() (from anywhere) but before zpl_snapdir_release()
367 * calls in to cancel the timer. If that happens, we then end up in
368 * zfsctl_snapshot_invalidate() performing all manner of dentry
369 * tests on a dentry with zero references. We can't take a new
370 * reference at that point, the dentry is already "dead" from the
371 * perspective of any callers, and taking a reference on a dentry with
372 * zero references is invalid.
373 *
374 * To get around this, we make use of the fact that we can test if
375 * a dentry is hashed (visible & active) holding only the dentry
376 * lock, and if necessary we can take a dentry reference without
377 * dropping the lock. The dentry is unhashed by both d_invalidate()
378 * (our "unmount" stand-in) and if necessary before d_release() is
379 * called.
380 *
381 * However, while unhashed implies refcount 0, it's not true that
382 * refcount 0 implies unhashed. A still-hashed entry can have refcount
383 * 0 while also being "alive", waiting on the dcache LRU to be freed
384 * or reused. For this case, we also check if the dentry is a
385 * mountpoint. If it is, then its refcount can't be 0, and if it isn't,
386 * we don't care because we're only here to unmount things.
387 *
388 * (simply checking if its a mountpoint is not enough in the other
389 * direction; the dentry can be unhashed but still a mountpoint if
390 * we invalidated it but it is still in use, for example in
391 * zfsctl_snapdir_rename()).
392 */
393 spin_lock(&se->se_dentry->d_lock);
394 if (d_unhashed(se->se_dentry) || !d_mountpoint(se->se_dentry)) {
395 /* No longer visible, so just "finish" the task and eject. */
396 spin_unlock(&se->se_dentry->d_lock);
397 mutex_enter(&se->se_mtx);
398 se->se_taskqid = TASKQID_INVALID;
399 mutex_exit(&se->se_mtx);
400 return;
401 }
402
403 /* Take dentry hold while we do the unmount work. */
404 dget_dlock(se->se_dentry);
405 spin_unlock(&se->se_dentry->d_lock);
406
407 int err = 0;
408 unsigned long delay = 0;
409
410 if (zfs_expire_snapshot <= 0)
411 /* Expiry was disabled by the admin, do nothing. */
412 goto out;
413
414 err = zfsctl_snapshot_invalidate(se, &delay);
415
416 out:
417 mutex_enter(&se->se_mtx);
418 se->se_taskqid = TASKQID_INVALID;
419 mutex_exit(&se->se_mtx);
420
421 if (err != 0) {
422 ASSERT3U(err, ==, EAGAIN);
423 /*
424 * Snapdir was used within the expiry time, re-arm it for the
425 * next possible time it could expire.
426 */
427 zfsctl_snapshot_timer_set(se, delay);
428 }
429
430 dput(se->se_dentry);
431 }
432
433 /* Safely cancel the snapentry expiry timer. */
434 void
zfsctl_snapshot_timer_clear(zfs_snapentry_t * se)435 zfsctl_snapshot_timer_clear(zfs_snapentry_t *se)
436 {
437 taskqid_t tqid;
438
439 mutex_enter(&se->se_mtx);
440 tqid = se->se_taskqid;
441 mutex_exit(&se->se_mtx);
442
443 if (tqid == TASKQID_INVALID)
444 return;
445
446 if (taskq_cancel_id(system_delay_taskq, tqid, B_TRUE) != 0) {
447 /*
448 * Cancellation failed, so either the task already cleared
449 * it (and we won a race on se_mtx above), or the task is
450 * running right now and will clear it when done.
451 */
452 return;
453 }
454
455 mutex_enter(&se->se_mtx);
456 if (se->se_taskqid == tqid)
457 se->se_taskqid = TASKQID_INVALID;
458 mutex_exit(&se->se_mtx);
459 }
460
461 /*
462 * Arm the snapentry expire timer to fire in `delay` ticks. If already armed,
463 * do nothing.
464 */
465 static void
zfsctl_snapshot_timer_set(zfs_snapentry_t * se,unsigned long delay)466 zfsctl_snapshot_timer_set(zfs_snapentry_t *se, unsigned long delay)
467 {
468 /* Do nothing if the expire timer has been disabled. */
469 if (delay == 0)
470 return;
471
472 mutex_enter(&se->se_mtx);
473 if (se->se_taskqid != TASKQID_INVALID) {
474 /* Already armed, do nothing. */
475 mutex_exit(&se->se_mtx);
476 return;
477 }
478
479 se->se_taskqid = taskq_dispatch_delay(system_delay_taskq,
480 zfsctl_snapshot_timer_task, se, TQ_SLEEP, ddi_get_lbolt() + delay);
481 mutex_exit(&se->se_mtx);
482 }
483
484 /*
485 * Check if the given inode is a part of the virtual .zfs directory.
486 */
487 boolean_t
zfsctl_is_node(struct inode * ip)488 zfsctl_is_node(struct inode *ip)
489 {
490 return (ITOZ(ip)->z_is_ctldir);
491 }
492
493 /*
494 * Check if the given inode is a .zfs/snapshots/snapname directory.
495 */
496 boolean_t
zfsctl_is_snapdir(struct inode * ip)497 zfsctl_is_snapdir(struct inode *ip)
498 {
499 return (zfsctl_is_node(ip) && (ip->i_ino <= ZFSCTL_INO_SNAPDIRS));
500 }
501
502 /*
503 * Allocate a new inode with the passed id and ops.
504 */
505 static struct inode *
zfsctl_inode_alloc(zfsvfs_t * zfsvfs,uint64_t id,const struct file_operations * fops,const struct inode_operations * ops,uint64_t creation)506 zfsctl_inode_alloc(zfsvfs_t *zfsvfs, uint64_t id,
507 const struct file_operations *fops, const struct inode_operations *ops,
508 uint64_t creation)
509 {
510 struct inode *ip;
511 znode_t *zp;
512 inode_timespec_t now = {.tv_sec = creation};
513
514 ip = new_inode(zfsvfs->z_sb);
515 if (ip == NULL)
516 return (NULL);
517
518 if (!creation)
519 now = current_time(ip);
520 zp = ITOZ(ip);
521 ASSERT0P(zp->z_dirlocks);
522 ASSERT0P(zp->z_acl_cached);
523 ASSERT0P(zp->z_xattr_cached);
524 zp->z_id = id;
525 zp->z_unlinked = B_FALSE;
526 zp->z_atime_dirty = B_FALSE;
527 zp->z_zn_prefetch = B_FALSE;
528 zp->z_is_sa = B_FALSE;
529 zp->z_is_ctldir = B_TRUE;
530 zp->z_xattr_dir_absent = B_FALSE;
531 zp->z_sa_hdl = NULL;
532 zp->z_blksz = 0;
533 zp->z_seq = 0;
534 zp->z_mapcnt = 0;
535 zp->z_size = 0;
536 zp->z_pflags = 0;
537 zp->z_mode = 0;
538 zp->z_sync_cnt = 0;
539 ip->i_generation = 0;
540 ip->i_ino = id;
541 ip->i_mode = (S_IFDIR | S_IRWXUGO);
542 ip->i_uid = SUID_TO_KUID(0);
543 ip->i_gid = SGID_TO_KGID(0);
544 ip->i_blkbits = SPA_MINBLOCKSHIFT;
545 zpl_inode_set_atime_to_ts(ip, now);
546 zpl_inode_set_mtime_to_ts(ip, now);
547 zpl_inode_set_ctime_to_ts(ip, now);
548 ip->i_fop = fops;
549 ip->i_op = ops;
550 #if defined(IOP_XATTR)
551 ip->i_opflags &= ~IOP_XATTR;
552 #endif
553
554 if (insert_inode_locked(ip)) {
555 unlock_new_inode(ip);
556 iput(ip);
557 return (NULL);
558 }
559
560 mutex_enter(&zfsvfs->z_znodes_lock);
561 list_insert_tail(&zfsvfs->z_all_znodes, zp);
562 membar_producer();
563 mutex_exit(&zfsvfs->z_znodes_lock);
564
565 unlock_new_inode(ip);
566
567 return (ip);
568 }
569
570 /*
571 * Lookup the inode with given id, it will be allocated if needed.
572 */
573 static struct inode *
zfsctl_inode_lookup(zfsvfs_t * zfsvfs,uint64_t id,const struct file_operations * fops,const struct inode_operations * ops)574 zfsctl_inode_lookup(zfsvfs_t *zfsvfs, uint64_t id,
575 const struct file_operations *fops, const struct inode_operations *ops)
576 {
577 struct inode *ip = NULL;
578 uint64_t creation = 0;
579 dsl_dataset_t *snap_ds;
580 dsl_pool_t *pool;
581
582 while (ip == NULL) {
583 ip = ilookup(zfsvfs->z_sb, (unsigned long)id);
584 if (ip)
585 break;
586
587 if (id <= ZFSCTL_INO_SNAPDIRS && !creation) {
588 pool = dmu_objset_pool(zfsvfs->z_os);
589 dsl_pool_config_enter(pool, FTAG);
590 if (!dsl_dataset_hold_obj(pool,
591 ZFSCTL_INO_SNAPDIRS - id, FTAG, &snap_ds)) {
592 creation = dsl_get_creation(snap_ds);
593 dsl_dataset_rele(snap_ds, FTAG);
594 }
595 dsl_pool_config_exit(pool, FTAG);
596 }
597
598 /* May fail due to concurrent zfsctl_inode_alloc() */
599 ip = zfsctl_inode_alloc(zfsvfs, id, fops, ops, creation);
600 }
601
602 return (ip);
603 }
604
605 /*
606 * Create the '.zfs' directory. This directory is cached as part of the VFS
607 * structure. This results in a hold on the zfsvfs_t. The code in zfs_umount()
608 * therefore checks against a vfs_count of 2 instead of 1. This reference
609 * is removed when the ctldir is destroyed in the unmount. All other entities
610 * under the '.zfs' directory are created dynamically as needed.
611 *
612 * Because the dynamically created '.zfs' directory entries assume the use
613 * of 64-bit inode numbers this support must be disabled on 32-bit systems.
614 */
615 int
zfsctl_create(zfsvfs_t * zfsvfs)616 zfsctl_create(zfsvfs_t *zfsvfs)
617 {
618 ASSERT0P(zfsvfs->z_ctldir);
619
620 zfsvfs->z_ctldir = zfsctl_inode_alloc(zfsvfs, ZFSCTL_INO_ROOT,
621 &zpl_fops_root, &zpl_ops_root, 0);
622 if (zfsvfs->z_ctldir == NULL)
623 return (SET_ERROR(ENOENT));
624
625 return (0);
626 }
627
628 /*
629 * Destroy the '.zfs' directory or remove a snapshot from zfs_snapshots_by_name.
630 * Only called when the filesystem is unmounted.
631 */
632 void
zfsctl_destroy(zfsvfs_t * zfsvfs)633 zfsctl_destroy(zfsvfs_t *zfsvfs)
634 {
635 if (zfsvfs->z_ctldir) {
636 iput(zfsvfs->z_ctldir);
637 zfsvfs->z_ctldir = NULL;
638 }
639 }
640
641 /*
642 * Given a root znode, retrieve the associated .zfs directory.
643 * Add a hold to the vnode and return it.
644 */
645 struct inode *
zfsctl_root(znode_t * zp)646 zfsctl_root(znode_t *zp)
647 {
648 ASSERT(zfs_has_ctldir(zp));
649 /* Must have an existing ref, so igrab() cannot return NULL */
650 VERIFY3P(igrab(ZTOZSB(zp)->z_ctldir), !=, NULL);
651 return (ZTOZSB(zp)->z_ctldir);
652 }
653
654 /*
655 * Generate a long fid to indicate a snapdir. We encode whether snapdir is
656 * already mounted in gen field. We do this because nfsd lookup will not
657 * trigger automount. Next time the nfsd does fh_to_dentry, we will notice
658 * this and do automount and return ESTALE to force nfsd revalidate and follow
659 * mount.
660 */
661 static int
zfsctl_snapdir_fid(struct inode * ip,fid_t * fidp)662 zfsctl_snapdir_fid(struct inode *ip, fid_t *fidp)
663 {
664 zfid_short_t *zfid = (zfid_short_t *)fidp;
665 zfid_long_t *zlfid = (zfid_long_t *)fidp;
666 uint32_t gen = 0;
667 uint64_t object;
668 uint64_t objsetid;
669 int i;
670 struct dentry *dentry;
671
672 if (fidp->fid_len < LONG_FID_LEN) {
673 fidp->fid_len = LONG_FID_LEN;
674 return (SET_ERROR(ENOSPC));
675 }
676
677 object = ip->i_ino;
678 objsetid = ZFSCTL_INO_SNAPDIRS - ip->i_ino;
679 zfid->zf_len = LONG_FID_LEN;
680
681 dentry = d_obtain_alias(igrab(ip));
682 if (!IS_ERR(dentry)) {
683 gen = !!d_mountpoint(dentry);
684 dput(dentry);
685 }
686
687 for (i = 0; i < sizeof (zfid->zf_object); i++)
688 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
689
690 for (i = 0; i < sizeof (zfid->zf_gen); i++)
691 zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
692
693 for (i = 0; i < sizeof (zlfid->zf_setid); i++)
694 zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
695
696 for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
697 zlfid->zf_setgen[i] = 0;
698
699 return (0);
700 }
701
702 /*
703 * Generate an appropriate fid for an entry in the .zfs directory.
704 */
705 int
zfsctl_fid(struct inode * ip,fid_t * fidp)706 zfsctl_fid(struct inode *ip, fid_t *fidp)
707 {
708 znode_t *zp = ITOZ(ip);
709 zfsvfs_t *zfsvfs = ITOZSB(ip);
710 uint64_t object = zp->z_id;
711 zfid_short_t *zfid;
712 int i;
713 int error;
714
715 if ((error = zfs_enter(zfsvfs, FTAG)) != 0)
716 return (error);
717
718 if (zfsctl_is_snapdir(ip)) {
719 zfs_exit(zfsvfs, FTAG);
720 return (zfsctl_snapdir_fid(ip, fidp));
721 }
722
723 if (fidp->fid_len < SHORT_FID_LEN) {
724 fidp->fid_len = SHORT_FID_LEN;
725 zfs_exit(zfsvfs, FTAG);
726 return (SET_ERROR(ENOSPC));
727 }
728
729 zfid = (zfid_short_t *)fidp;
730
731 zfid->zf_len = SHORT_FID_LEN;
732
733 for (i = 0; i < sizeof (zfid->zf_object); i++)
734 zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
735
736 /* .zfs znodes always have a generation number of 0 */
737 for (i = 0; i < sizeof (zfid->zf_gen); i++)
738 zfid->zf_gen[i] = 0;
739
740 zfs_exit(zfsvfs, FTAG);
741 return (0);
742 }
743
744 /*
745 * Construct a full dataset name in full_name: "pool/dataset@snap_name"
746 */
747 static int
zfsctl_snapshot_name(zfsvfs_t * zfsvfs,const char * snap_name,int len,char * full_name)748 zfsctl_snapshot_name(zfsvfs_t *zfsvfs, const char *snap_name, int len,
749 char *full_name)
750 {
751 objset_t *os = zfsvfs->z_os;
752
753 if (zfs_component_namecheck(snap_name, NULL, NULL) != 0)
754 return (SET_ERROR(EILSEQ));
755
756 dmu_objset_name(os, full_name);
757 if ((strlen(full_name) + 1 + strlen(snap_name)) >= len)
758 return (SET_ERROR(ENAMETOOLONG));
759
760 (void) strcat(full_name, "@");
761 (void) strcat(full_name, snap_name);
762
763 return (0);
764 }
765
766 /*
767 * Returns full path in full_path: "/pool/dataset/.zfs/snapshot/snap_name/"
768 */
769 static int
zfsctl_snapshot_path_objset(zfsvfs_t * zfsvfs,uint64_t objsetid,int path_len,char * full_path)770 zfsctl_snapshot_path_objset(zfsvfs_t *zfsvfs, uint64_t objsetid,
771 int path_len, char *full_path)
772 {
773 objset_t *os = zfsvfs->z_os;
774 fstrans_cookie_t cookie;
775 char *snapname;
776 boolean_t case_conflict;
777 uint64_t id, pos = 0;
778 int error = 0;
779
780 cookie = spl_fstrans_mark();
781 snapname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
782
783 while (error == 0) {
784 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
785 error = dmu_snapshot_list_next(zfsvfs->z_os,
786 ZFS_MAX_DATASET_NAME_LEN, snapname, &id, &pos,
787 &case_conflict);
788 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
789 if (error)
790 goto out;
791
792 if (id == objsetid)
793 break;
794 }
795
796 mutex_enter(&zfsvfs->z_vfs->vfs_mntpt_lock);
797 if (zfsvfs->z_vfs->vfs_mntpoint != NULL) {
798 snprintf(full_path, path_len, "%s/.zfs/snapshot/%s",
799 zfsvfs->z_vfs->vfs_mntpoint, snapname);
800 } else
801 error = SET_ERROR(ENOENT);
802 mutex_exit(&zfsvfs->z_vfs->vfs_mntpt_lock);
803
804 out:
805 kmem_free(snapname, ZFS_MAX_DATASET_NAME_LEN);
806 spl_fstrans_unmark(cookie);
807
808 return (error);
809 }
810
811 /*
812 * Special case the handling of "..".
813 */
814 int
zfsctl_root_lookup(struct inode * dip,const char * name,struct inode ** ipp,int flags,cred_t * cr,int * direntflags,pathname_t * realpnp)815 zfsctl_root_lookup(struct inode *dip, const char *name, struct inode **ipp,
816 int flags, cred_t *cr, int *direntflags, pathname_t *realpnp)
817 {
818 zfsvfs_t *zfsvfs = ITOZSB(dip);
819 int error = 0;
820
821 if ((error = zfs_enter(zfsvfs, FTAG)) != 0)
822 return (error);
823
824 if (zfsvfs->z_show_ctldir == ZFS_SNAPDIR_DISABLED) {
825 *ipp = NULL;
826 } else if (strcmp(name, "..") == 0) {
827 *ipp = dip->i_sb->s_root->d_inode;
828 } else if (strcmp(name, ZFS_SNAPDIR_NAME) == 0) {
829 *ipp = zfsctl_inode_lookup(zfsvfs, ZFSCTL_INO_SNAPDIR,
830 &zpl_fops_snapdir, &zpl_ops_snapdir);
831 } else if (strcmp(name, ZFS_SHAREDIR_NAME) == 0) {
832 *ipp = zfsctl_inode_lookup(zfsvfs, ZFSCTL_INO_SHARES,
833 &zpl_fops_shares, &zpl_ops_shares);
834 } else {
835 *ipp = NULL;
836 }
837
838 if (*ipp == NULL)
839 error = SET_ERROR(ENOENT);
840
841 zfs_exit(zfsvfs, FTAG);
842
843 return (error);
844 }
845
846 /*
847 * Lookup entry point for the 'snapshot' directory. Try to open the
848 * snapshot if it exist, creating the pseudo filesystem inode as necessary.
849 */
850 int
zfsctl_snapdir_lookup(struct inode * dip,const char * name,struct inode ** ipp,int flags,cred_t * cr,int * direntflags,pathname_t * realpnp)851 zfsctl_snapdir_lookup(struct inode *dip, const char *name, struct inode **ipp,
852 int flags, cred_t *cr, int *direntflags, pathname_t *realpnp)
853 {
854 zfsvfs_t *zfsvfs = ITOZSB(dip);
855 uint64_t id;
856 int error;
857
858 if ((error = zfs_enter(zfsvfs, FTAG)) != 0)
859 return (error);
860
861 error = dmu_snapshot_lookup(zfsvfs->z_os, name, &id);
862 if (error) {
863 zfs_exit(zfsvfs, FTAG);
864 return (error);
865 }
866
867 *ipp = zfsctl_inode_lookup(zfsvfs, ZFSCTL_INO_SNAPDIRS - id,
868 &simple_dir_operations, &simple_dir_inode_operations);
869 if (*ipp == NULL)
870 error = SET_ERROR(ENOENT);
871
872 zfs_exit(zfsvfs, FTAG);
873
874 return (error);
875 }
876
877 /*
878 * Renaming a directory under '.zfs/snapshot' will automatically trigger
879 * a rename of the snapshot to the new given name. The rename is confined
880 * to the '.zfs/snapshot' directory snapshots cannot be moved elsewhere.
881 */
882 int
zfsctl_snapdir_rename(struct inode * sdip,struct dentry * sdentry,struct inode * tdip,struct dentry * tdentry,cred_t * cr)883 zfsctl_snapdir_rename(struct inode *sdip, struct dentry *sdentry,
884 struct inode *tdip, struct dentry *tdentry, cred_t *cr)
885 {
886 zfsvfs_t *zfsvfs = ITOZSB(sdip);
887 const char *snm = dname(sdentry);
888 const char *tnm = dname(tdentry);
889 char *to, *from, *real, *fsname;
890 int error;
891
892 if (!zfs_admin_snapshot)
893 return (SET_ERROR(EACCES));
894
895 if ((error = zfs_enter(zfsvfs, FTAG)) != 0)
896 return (error);
897
898 to = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
899 from = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
900 real = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
901 fsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
902
903 if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE) {
904 error = dmu_snapshot_realname(zfsvfs->z_os, snm, real,
905 ZFS_MAX_DATASET_NAME_LEN, NULL);
906 if (error == 0) {
907 snm = real;
908 } else if (error != ENOTSUP) {
909 goto out;
910 }
911 }
912
913 dmu_objset_name(zfsvfs->z_os, fsname);
914
915 error = zfsctl_snapshot_name(ITOZSB(sdip), snm,
916 ZFS_MAX_DATASET_NAME_LEN, from);
917 if (error == 0)
918 error = zfsctl_snapshot_name(ITOZSB(tdip), tnm,
919 ZFS_MAX_DATASET_NAME_LEN, to);
920 if (error == 0)
921 error = zfs_secpolicy_rename_perms(from, to, cr);
922 if (error != 0)
923 goto out;
924
925 /*
926 * Cannot move snapshots out of the snapdir.
927 */
928 if (sdip != tdip) {
929 error = SET_ERROR(EINVAL);
930 goto out;
931 }
932
933 /*
934 * No-op when names are identical.
935 */
936 if (strcmp(snm, tnm) == 0) {
937 error = 0;
938 goto out;
939 }
940
941 zfs_snapentry_t *se = sdentry->d_fsdata;
942 ASSERT3P(se, !=, NULL);
943
944 /*
945 * Snapshots can be renamed while mounted, so we do not need the
946 * full unmount check; detaching from the control dir is enough.
947 */
948 zfsctl_snapshot_invalidate(se, NULL);
949
950 error = dsl_dataset_rename_snapshot(fsname, snm, tnm, B_FALSE);
951
952 out:
953 kmem_free(from, ZFS_MAX_DATASET_NAME_LEN);
954 kmem_free(to, ZFS_MAX_DATASET_NAME_LEN);
955 kmem_free(real, ZFS_MAX_DATASET_NAME_LEN);
956 kmem_free(fsname, ZFS_MAX_DATASET_NAME_LEN);
957
958 zfs_exit(zfsvfs, FTAG);
959
960 return (error);
961 }
962
963 /*
964 * Removing a directory under '.zfs/snapshot' will automatically trigger
965 * the removal of the snapshot with the given name.
966 */
967 int
zfsctl_snapdir_remove(struct inode * dip,struct dentry * dentry,cred_t * cr)968 zfsctl_snapdir_remove(struct inode *dip, struct dentry *dentry, cred_t *cr)
969 {
970 zfsvfs_t *zfsvfs = ITOZSB(dip);
971 const char *name = dname(dentry);
972 char *snapname, *real;
973 int error;
974
975 if (!zfs_admin_snapshot)
976 return (SET_ERROR(EACCES));
977
978 if ((error = zfs_enter(zfsvfs, FTAG)) != 0)
979 return (error);
980
981 snapname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
982 real = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
983
984 if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE) {
985 error = dmu_snapshot_realname(zfsvfs->z_os, name, real,
986 ZFS_MAX_DATASET_NAME_LEN, NULL);
987 if (error == 0) {
988 name = real;
989 } else if (error != ENOTSUP) {
990 goto out;
991 }
992 }
993
994 error = zfsctl_snapshot_name(ITOZSB(dip), name,
995 ZFS_MAX_DATASET_NAME_LEN, snapname);
996 if (error == 0)
997 error = zfs_secpolicy_destroy_perms(snapname, cr);
998 if (error != 0)
999 goto out;
1000
1001 out:
1002 zfs_exit(zfsvfs, FTAG);
1003
1004 if (error == 0) {
1005 /*
1006 * We have the dentry here so could pass it down to an "inner"
1007 * version of zfsctl_snapshot_unmount(), but we'd still have
1008 * to pass the name down for the locking there.
1009 *
1010 * Snapshot delete through admin snapdir operation should be
1011 * rare enough that any gain isn't worth the extra code
1012 * complexity, but the option is there for the future.
1013 */
1014 zfsctl_snapshot_unmount(snapname);
1015 error = dsl_destroy_snapshot(snapname, B_FALSE);
1016 }
1017
1018 kmem_free(snapname, ZFS_MAX_DATASET_NAME_LEN);
1019 kmem_free(real, ZFS_MAX_DATASET_NAME_LEN);
1020
1021 return (error);
1022 }
1023
1024 /*
1025 * Creating a directory under '.zfs/snapshot' will automatically trigger
1026 * the creation of a new snapshot with the given name.
1027 */
1028 int
zfsctl_snapdir_mkdir(struct inode * dip,const char * dirname,vattr_t * vap,struct inode ** ipp,cred_t * cr,int flags)1029 zfsctl_snapdir_mkdir(struct inode *dip, const char *dirname, vattr_t *vap,
1030 struct inode **ipp, cred_t *cr, int flags)
1031 {
1032 zfsvfs_t *zfsvfs = ITOZSB(dip);
1033 char *dsname;
1034 int error;
1035
1036 if (!zfs_admin_snapshot)
1037 return (SET_ERROR(EACCES));
1038
1039 dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
1040
1041 if (zfs_component_namecheck(dirname, NULL, NULL) != 0) {
1042 error = SET_ERROR(EILSEQ);
1043 goto out;
1044 }
1045
1046 dmu_objset_name(zfsvfs->z_os, dsname);
1047
1048 error = zfs_secpolicy_snapshot_perms(dsname, cr);
1049 if (error != 0)
1050 goto out;
1051
1052 if (error == 0) {
1053 error = dmu_objset_snapshot_one(dsname, dirname);
1054 if (error != 0)
1055 goto out;
1056
1057 error = zfsctl_snapdir_lookup(dip, dirname, ipp,
1058 0, cr, NULL, NULL);
1059 }
1060 out:
1061 kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);
1062
1063 return (error);
1064 }
1065
1066 /*
1067 * Invalidate a snapdir
1068 *
1069 * As described elsewhere, we can't perform a true unmount; all we can do is
1070 * detach it from the parent and trust other mechanisms to drain it, or handle
1071 * it being in use. We also must be prepared for something unexpected being
1072 * mounted on the snapdir, or nothing at all.
1073 *
1074 * Most of this function is studying the current situation and trying to
1075 * decide if we do detach it, the "unmount" (ie filesystem teardown) will
1076 * happen immediately after.
1077 *
1078 * In the very common cases where the admin is not doing any additional mount
1079 * manipulation and there's nothing currently using the dataset, this will
1080 * usually succeed, which should be good enough.
1081 */
1082 typedef struct {
1083 zfs_snapentry_t *sba_snapentry;
1084 uint64_t sba_atime;
1085 } zfsctl_snapshot_sb_atime_cb_args_t;
1086
1087 static void
zfsctl_snapshot_sb_atime_cb(struct super_block * sb,void * sbap)1088 zfsctl_snapshot_sb_atime_cb(struct super_block *sb, void *sbap)
1089 {
1090 zfsvfs_t *zfsvfs = sb->s_fs_info;
1091 if (zfsvfs == NULL)
1092 return;
1093
1094 zfsctl_snapshot_sb_atime_cb_args_t *sba = sbap;
1095 if (dmu_objset_spa(zfsvfs->z_os) != sba->sba_snapentry->se_spa ||
1096 dmu_objset_id(zfsvfs->z_os) != sba->sba_snapentry->se_objsetid)
1097 return;
1098
1099 sba->sba_atime = atomic_load_64(&zfsvfs->z_snap_atime);
1100 }
1101
1102 static int
zfsctl_snapshot_invalidate(zfs_snapentry_t * se,unsigned long * delay)1103 zfsctl_snapshot_invalidate(zfs_snapentry_t *se, unsigned long *delay)
1104 {
1105 /*
1106 * Wait for any pending automount or unmount to complete before
1107 * attempting unmount.
1108 */
1109 mutex_enter(&se->se_mtx);
1110 while (SE_TEST(se, SE_BUSY))
1111 cv_wait(&se->se_cv, &se->se_mtx);
1112 if (d_unhashed(se->se_dentry)) {
1113 /* Someone else invalidated it while we were waiting. */
1114 mutex_exit(&se->se_mtx);
1115 return (0);
1116 }
1117 SE_SET(se, SE_BUSY);
1118 mutex_exit(&se->se_mtx);
1119
1120 if (delay != NULL && d_mountpoint(se->se_dentry)) {
1121 /*
1122 * This is the expiry task. Consider if the snapdir dentry
1123 * or the snapshot data has been accessed within the expiry
1124 * period and defer if so.
1125 */
1126
1127 unsigned long atime = atomic_load_64(&se->se_atime);
1128
1129 /*
1130 * Search for the superblock for the dataset we mounted, and
1131 * grab its access time. We have to search because we can't
1132 * hold a reference back to the zfsvfs or superblock, because
1133 * that would pin it and prevent it being destroyed. We will
1134 * never outlive our reference spa though, so there's no risk
1135 * of the spa pointer being invalid.
1136 */
1137 zfsctl_snapshot_sb_atime_cb_args_t sba = {
1138 .sba_snapentry = se,
1139 .sba_atime = 0,
1140 };
1141 iterate_supers_type(&zpl_fs_type,
1142 zfsctl_snapshot_sb_atime_cb, &sba);
1143
1144 atime = MAX(atime, sba.sba_atime);
1145
1146 unsigned long expiry = atime +
1147 (MAX(zfs_expire_snapshot, 0) * HZ);
1148 unsigned long now = jiffies;
1149
1150 if (time_before(now, expiry)) {
1151 /*
1152 * It was used more recently than the expiry time. Pass
1153 * the remaining time back to the caller for rearming.
1154 */
1155 *delay = expiry - now;
1156
1157 mutex_enter(&se->se_mtx);
1158 SE_CLEAR(se, SE_BUSY);
1159 cv_broadcast(&se->se_cv);
1160 mutex_exit(&se->se_mtx);
1161
1162 return (SET_ERROR(EAGAIN));
1163 }
1164 }
1165
1166 /*
1167 * Take a hold to keep the dentry+snapentry alive after invalidate
1168 * so we can signal if necessary.
1169 */
1170 dget(se->se_dentry);
1171
1172 /* Detach the control dentry from the parent dataset. */
1173 d_invalidate(se->se_dentry);
1174
1175 /* Signal any waiters in zpl_snapdir_manage(). */
1176 mutex_enter(&se->se_mtx);
1177 SE_CLEAR(se, SE_BUSY);
1178 cv_broadcast(&se->se_cv);
1179 mutex_exit(&se->se_mtx);
1180
1181 /*
1182 * Release our hold, which may be the last one. If so, the snapentry
1183 * may be destroyed immediately, so must not be used after this.
1184 */
1185 dput(se->se_dentry);
1186
1187 return (0);
1188 }
1189
1190 /*
1191 * Unmount snapshot by name.
1192 *
1193 * Some admin ops (eg `zfs destroy`) request an unmount before they begin
1194 * their work. We have no way to know at any given moment if the snapshot is
1195 * definitely mounted - on our snapdir or anywhere else - because some other
1196 * task may in the process of mounting or unmounting it. As such, this is
1197 * always best effort.
1198 */
1199
1200 /*
1201 * Check if the named snapshot is definitely unmounted. Returns true if it
1202 * is, false if its not or we're unsure.
1203 *
1204 * We check long holds here, rather than using getzfsvfs(), because there is
1205 * a significant timing gap between "filesystem unmounted" and "owning long
1206 * hold released". That does mean that other long holds (`zfs send`,
1207 * `zfs diff`, etc) can cause a false return here, but that's ok - it will
1208 * just mean we try some different things, and if it turns out the hold is
1209 * unrelated, the next operation (eg `dsl_destroy_snapshot()`) will return
1210 * `EBUSY` anyway, which is correct.
1211 */
1212 static bool
zfsctl_snapshot_unmount_check(const char * snapname)1213 zfsctl_snapshot_unmount_check(const char *snapname)
1214 {
1215 dsl_pool_t *dp;
1216 if (dsl_pool_hold(snapname, FTAG, &dp) != 0)
1217 return (true);
1218
1219 dsl_dataset_t *ds;
1220 if (dsl_dataset_hold(dp, snapname, FTAG, &ds) != 0) {
1221 dsl_pool_rele(dp, FTAG);
1222 return (true);
1223 }
1224
1225 bool held = dsl_dataset_long_held(ds);
1226 dsl_dataset_rele(ds, FTAG);
1227 dsl_pool_rele(dp, FTAG);
1228
1229 return (!held);
1230 }
1231
1232 /*
1233 * Wait for the named snapshot to be unmounted. tqid is the task that is trying
1234 * to force the unmount. Returns true when the snapshot is unmounted, false if
1235 * still in use at the deadline.
1236 *
1237 * Despite setting MNT_INTERNAL, the final dput()/mntput() may still put on a
1238 * delay queue if there is associated teardown to be done (eg alt namespaces
1239 * for mount propagation). zfsctl_snapshot_unmount() is usually called from a
1240 * user thread (an ioctl), which uses a per-task workqueue for this purpose,
1241 * and empties it on return to userspace. This too late for an operation like
1242 * `zfs destroy` that does the unmount in preparation for the real operation.
1243 *
1244 * When the final dput()/mntput() is done from a kernel thread, then it is
1245 * queued onto a system workqueue instead. So, we put those possible "last put"
1246 * calls on system_taskq and wait for them, and then call here to wait for the
1247 * unmount to occur, if it is going to occur.
1248 *
1249 * Delayed work queueing runs on a jiffy timer, so the mntput() may not be on
1250 * the queue yet when we call zpl_flush_delay_workqueue(). So, we sleep for one
1251 * jiffy each iteration, and flush the queue each time, for 40 milliseconds.
1252 * Most of the time we'll see the task within 2-3 jiffies so this is quite a
1253 * generous timeout. Worst case, we pause a while, timeout, and eventually
1254 * return EBUSY.
1255 *
1256 * if tqid is TASKQID_INVALID, this does a single check unmount check then
1257 * returns, as there's no point waiting if no task was dispatched.
1258 */
1259 static bool
zfsctl_snapshot_unmount_wait(const char * snapname,taskqid_t tqid)1260 zfsctl_snapshot_unmount_wait(const char *snapname, taskqid_t tqid)
1261 {
1262 if (tqid == TASKQID_INVALID)
1263 return (zfsctl_snapshot_unmount_check(snapname));
1264
1265 taskq_wait_id(system_taskq, tqid);
1266
1267 unsigned long deadline = jiffies + MSEC_TO_TICK(40);
1268
1269 while (!zfsctl_snapshot_unmount_check(snapname)) {
1270 if (time_after_eq(jiffies, deadline))
1271 return (false);
1272
1273 schedule_timeout_idle(1);
1274 zpl_flush_delay_workqueue();
1275 }
1276
1277 return (true);
1278 }
1279
1280 /*
1281 * Invalidate task. Note that the `dput()` is what will actually trigger
1282 * the (delayed-)unmount, so it has to be in the task too.
1283 */
1284 static void
zfsctl_snapshot_unmount_invalidate_task(void * arg)1285 zfsctl_snapshot_unmount_invalidate_task(void *arg)
1286 {
1287 struct dentry *dentry = arg;
1288 zfs_snapentry_t *se = dentry->d_fsdata;
1289
1290 zfsctl_snapshot_invalidate(se, NULL);
1291 dput(dentry);
1292 }
1293
1294 /*
1295 * Flush the kernel's NFS export table.
1296 *
1297 * If the snapshot dir has been used over NFS, the relevant entries in the
1298 * svc_expkey_cache and svc_export_cache caches hold references to the snapshot
1299 * mount point.
1300 *
1301 * A full flush is aggressive (flushes everything), but easy to implement. The
1302 * alternative is to use the channel endpoints to find and evict the specific
1303 * paths related to the path we're unmounting, but that's a lot more involved
1304 * for minimal gain.
1305 */
1306 static void
zfsctl_snapshot_unmount_nfs_flush(void)1307 zfsctl_snapshot_unmount_nfs_flush(void)
1308 {
1309 /*
1310 * We use a userspace callout for this, as there are no kernel APIs
1311 * available to do this from outside the NFS server, and simulating
1312 * access to sunrpc cache file endpoints from within the kernel
1313 * requires userspace-mapped data buffer, which we do not have.
1314 *
1315 * `exportfs -f` would do what we need here, however that flushes all
1316 * nfsd caches, not just the ones with pinned dentries, but also may
1317 * not be installed or on a consistent path (unlikely on a NFS-using
1318 * machine, but still). The shell is guaranteed to be at /bin/sh, so
1319 * we can rely on it.
1320 *
1321 * Userspace callouts are always called with root privileges in the
1322 * init namespaces, so the only thing that prevents this from working
1323 * is if /proc is not mounted. That's the most unlikely thing of all,
1324 * and since this is best-effort, it will have to do.
1325 */
1326 char *argv[] = {
1327 "/bin/sh", "-c",
1328 "echo 1 > /proc/net/rpc/nfsd.h/flush ; "
1329 "echo 1 > /proc/net/rpc/nfsd.export/flush", NULL };
1330 char *envp[] = { NULL };
1331
1332 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_PROC);
1333 }
1334
1335 /*
1336 * The public entry point. Try to unmount the snapshot with the given name.
1337 * We only consider the snapdir; additional mounts elsewhere will not be
1338 * touched.
1339 *
1340 * Since this is best-effort, always returns 0.
1341 */
1342 int
zfsctl_snapshot_unmount(const char * snapname)1343 zfsctl_snapshot_unmount(const char *snapname)
1344 {
1345 taskqid_t tqid = TASKQID_INVALID;
1346
1347 /* Incoming snapname is 'pool/dataset@snap'. Split on the '@' */
1348 char *ds = kmem_strdup(snapname);
1349 char *snap = strchr(ds, '@');
1350 if (snap == NULL) {
1351 kmem_strfree(ds);
1352 return (0);
1353 }
1354 *snap++ = '\0';
1355
1356 /* Get a handle on the dataset itself, which holds the control dir. */
1357 zfsvfs_t *zfsvfs = NULL;
1358 int err = getzfsvfs(ds, &zfsvfs);
1359 if (err != 0) {
1360 ASSERT0P(zfsvfs);
1361 kmem_strfree(ds);
1362 return (0);
1363 }
1364
1365 /* Find the virtual inode for the `.zfs/snapshot` dir. */
1366 struct inode *snapdir_ip = ilookup(zfsvfs->z_sb, ZFSCTL_INO_SNAPDIR);
1367 if (snapdir_ip == NULL) {
1368 zfs_vfs_rele(zfsvfs);
1369 kmem_strfree(ds);
1370 return (0);
1371 }
1372
1373 /*
1374 * And its associated dentry.
1375 *
1376 * Note that from this point, we always proceed into the "wait" step
1377 * even if we don't find what we're looking for in the ctldir, because
1378 * once the ctldir inode structure is established we might not be
1379 * finding things because we're racing against setup or teardown
1380 * elsewhere in the system, and so there still might be a leftover
1381 * mount that we should try to force out if we can.
1382 */
1383 struct dentry *snapdir_dentry = d_find_alias(snapdir_ip);
1384 iput(snapdir_ip);
1385 if (snapdir_dentry == NULL) {
1386 zfs_vfs_rele(zfsvfs);
1387 kmem_strfree(ds);
1388 goto wait;
1389 }
1390
1391 /*
1392 * Now hash the snapshot name, and use it to lookup the snapdir
1393 * of the same name.
1394 */
1395 struct qstr qname = QSTR_INIT(snap, strlen(snap));
1396 qname.hash = full_name_hash(snapdir_dentry, snap, qname.len);
1397 struct dentry *dentry = d_lookup(snapdir_dentry, &qname);
1398
1399 dput(snapdir_dentry);
1400 kmem_strfree(ds);
1401 zfs_vfs_rele(zfsvfs);
1402
1403 /*
1404 * Sanity; we should always have a dentry with an attached snapentry,
1405 * but if we don't, we can't do anything else except try to push a
1406 * background expiry along.
1407 */
1408 if (dentry == NULL)
1409 goto wait;
1410 if (dentry->d_fsdata == NULL) {
1411 dput(dentry);
1412 goto wait;
1413 }
1414
1415 /*
1416 * If there's nothing mounted on this dentry, then we don't need to
1417 * invalidate it, but we should still try to wait for our snapshot
1418 * to expire and try to force it along.
1419 *
1420 * We continue to invalidate if anything is mounted here, because
1421 * the operator may have mounted an unrelated filesystem here, and
1422 * this is the only way it will be detached during an admin operation.
1423 */
1424 if (!d_mountpoint(dentry)) {
1425 dput(dentry);
1426 goto wait;
1427 }
1428
1429 /*
1430 * Do invalidate + dput on system_taskq thread to force delayed mntput
1431 * (if required) onto system_wq. If dispatch fails for some reason,
1432 * call it directly and we'll just have to live with a possible EBUSY
1433 * down the line.
1434 */
1435 tqid = taskq_dispatch(system_taskq,
1436 zfsctl_snapshot_unmount_invalidate_task, dentry, TQ_SLEEP|TQ_FRONT);
1437 if (tqid == TASKQID_INVALID)
1438 zfsctl_snapshot_unmount_invalidate_task(dentry);
1439
1440 wait:
1441 /*
1442 * Wait for unmount. We do this regardless of whether or not we
1443 * found the snapdir dentry above; it might have been expired out
1444 * elsewhere in the system while the mount was still in use.
1445 */
1446 if (zfsctl_snapshot_unmount_wait(snapname, tqid))
1447 return (0);
1448
1449 /*
1450 * Still mounted. NFS caches might be pinning it. If so, then flushing
1451 * them will release the mount. Note that we do this after trying our
1452 * best to force the unmount in other ways, because the NFS cache
1453 * flush is global, and if the dataset and the whole system is
1454 * actually busy, then overdoing this is going to hurt NFS performance.
1455 */
1456 zfsctl_snapshot_unmount_nfs_flush();
1457
1458 /*
1459 * No wait required after NFS flush; if it resulted in unmount, it
1460 * happened on the return to userspace and so there's nothing to wait
1461 * for.
1462 */
1463
1464 return (0);
1465 }
1466
1467 /*
1468 * Mount. This is the actual work behind the d_automount endpoint. On success,
1469 * the mount is returned in *mntp, and the manage->automount->manage ceremony
1470 * will get it all properly wired into the tree and any waiters released.
1471 */
1472 int
zfsctl_snapshot_mount(struct path * path,struct vfsmount ** mntp)1473 zfsctl_snapshot_mount(struct path *path, struct vfsmount **mntp)
1474 {
1475 struct dentry *dentry = path->dentry;
1476 struct inode *ip = dentry->d_inode;
1477 zfsvfs_t *zfsvfs;
1478 zfsvfs_t *snap_zfsvfs;
1479 zfs_snapentry_t *se;
1480 char snapname[ZFS_MAX_DATASET_NAME_LEN];
1481 int error;
1482
1483 ASSERT3P(ip, !=, NULL);
1484
1485 /*
1486 * ip is the snapdir inode itself, so zfsvfs is the parent (real)
1487 * dataset. We only need to take the hold in order to compute the
1488 * snapshot name; the calling dentry is what's actually holding it
1489 * alive.
1490 */
1491 zfsvfs = ITOZSB(ip);
1492 if ((error = zfs_enter(zfsvfs, FTAG)) != 0)
1493 return (error);
1494
1495 error = zfsctl_snapshot_name(zfsvfs, dname(dentry),
1496 sizeof (snapname), snapname);
1497
1498 zfs_exit(zfsvfs, FTAG);
1499 if (error)
1500 return (error);
1501
1502 /*
1503 * A "submount" inherits its options, propagation group, namespaces,
1504 * etc from the reference dentry.
1505 */
1506 struct fs_context *fc =
1507 fs_context_for_submount(dentry->d_sb->s_type, dentry);
1508 if (IS_ERR(fc))
1509 return (-PTR_ERR(fc));
1510
1511 /* The full snapshot name is the "source" (see zpl_get_tree()) */
1512 error = -zpl_vfs_parse_fs_string(fc, "source", snapname);
1513 if (error != 0) {
1514 put_fs_context(fc);
1515 return (error);
1516 }
1517
1518 /* Create the mount! */
1519 struct vfsmount *mnt = fc_mount(fc);
1520 put_fs_context(fc);
1521
1522 if (IS_ERR(mnt))
1523 return (-PTR_ERR(mnt));
1524
1525 snap_zfsvfs = ITOZSB(mnt->mnt_root->d_inode);
1526 snap_zfsvfs->z_parent = zfsvfs;
1527
1528 se = dentry->d_fsdata;
1529
1530 /* Clear any leftover timer from previous iteration. */
1531 zfsctl_snapshot_timer_clear(se);
1532
1533 /* Fill out the snapentry with lookup helpers */
1534 se->se_spa = dmu_objset_spa(snap_zfsvfs->z_os);
1535 se->se_objsetid = dmu_objset_id(snap_zfsvfs->z_os);
1536
1537 *mntp = mnt;
1538
1539 return (0);
1540 }
1541
1542 /*
1543 * Called after the mount is spliced into the filesystem tree but before path
1544 * walks are allowed to proceed into it. See zpl_ctldir.c for more info.
1545 */
1546 void
zfsctl_snapshot_finish_mount(zfs_snapentry_t * se,struct vfsmount * mnt)1547 zfsctl_snapshot_finish_mount(zfs_snapentry_t *se, struct vfsmount *mnt)
1548 {
1549 /*
1550 * MNT_INTERNAL makes the mount "internal", and so give more chance
1551 * that it will unmounted when the last reference is dropped rather
1552 * than being put on a delay queue. It's not foolproof (some
1553 * mount-propagation configurations will still see it deferred) but
1554 * when it works it reduces the work we need to do in
1555 * zfsctl_snapshot_unmount(), and when it doesn't it's harmless.
1556 */
1557 mnt->mnt_flags |= MNT_INTERNAL;
1558
1559 /*
1560 * Add any additional user flags which would have been swallowed if we
1561 * set them when the mount was created.
1562 */
1563 if (zfs_snapshot_no_setuid)
1564 mnt->mnt_flags |= MNT_NOSUID;
1565
1566 /* Start the expiry timer. */
1567 se->se_atime = jiffies;
1568 zfsctl_snapshot_timer_set(se, zfs_expire_snapshot * HZ);
1569 }
1570
1571 /*
1572 * Get the snapdir inode from fid
1573 */
1574 int
zfsctl_snapdir_vget(struct super_block * sb,uint64_t objsetid,int gen,struct inode ** ipp)1575 zfsctl_snapdir_vget(struct super_block *sb, uint64_t objsetid, int gen,
1576 struct inode **ipp)
1577 {
1578 zfsvfs_t *zfsvfs = sb->s_fs_info;
1579 int error;
1580 struct path path;
1581 char *mnt;
1582 struct dentry *dentry;
1583
1584 mnt = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1585
1586 error = zfsctl_snapshot_path_objset(zfsvfs, objsetid, MAXPATHLEN, mnt);
1587 if (error)
1588 goto out;
1589
1590 /* Trigger automount */
1591 error = -kern_path(mnt, LOOKUP_FOLLOW|LOOKUP_DIRECTORY, &path);
1592 if (error)
1593 goto out;
1594
1595 path_put(&path);
1596 /*
1597 * Get the snapdir inode. Note, we don't want to use the above
1598 * path because it contains the root of the snapshot rather
1599 * than the snapdir.
1600 */
1601 *ipp = ilookup(sb, ZFSCTL_INO_SNAPDIRS - objsetid);
1602 if (*ipp == NULL) {
1603 error = SET_ERROR(ENOENT);
1604 goto out;
1605 }
1606
1607 /* check gen, see zfsctl_snapdir_fid */
1608 dentry = d_obtain_alias(igrab(*ipp));
1609 if (gen != (!IS_ERR(dentry) && d_mountpoint(dentry))) {
1610 iput(*ipp);
1611 *ipp = NULL;
1612 error = SET_ERROR(ENOENT);
1613 }
1614 if (!IS_ERR(dentry)) {
1615 /*
1616 * Cold-open via NFS will have a disconnected dentry here,
1617 * don't assume there's an associated snapentry here.
1618 */
1619 if (error == 0 && dentry->d_fsdata != NULL) {
1620 zfs_snapentry_t *se = dentry->d_fsdata;
1621 atomic_store_64(&se->se_atime, jiffies);
1622 }
1623 dput(dentry);
1624 }
1625
1626 out:
1627 kmem_free(mnt, MAXPATHLEN);
1628 return (error);
1629 }
1630
1631 int
zfsctl_shares_lookup(struct inode * dip,char * name,struct inode ** ipp,int flags,cred_t * cr,int * direntflags,pathname_t * realpnp)1632 zfsctl_shares_lookup(struct inode *dip, char *name, struct inode **ipp,
1633 int flags, cred_t *cr, int *direntflags, pathname_t *realpnp)
1634 {
1635 zfsvfs_t *zfsvfs = ITOZSB(dip);
1636 znode_t *zp;
1637 znode_t *dzp;
1638 int error;
1639
1640 if ((error = zfs_enter(zfsvfs, FTAG)) != 0)
1641 return (error);
1642
1643 if (zfsvfs->z_shares_dir == 0) {
1644 zfs_exit(zfsvfs, FTAG);
1645 return (SET_ERROR(ENOTSUP));
1646 }
1647
1648 if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &dzp)) == 0) {
1649 error = zfs_lookup(dzp, name, &zp, 0, cr, NULL, NULL);
1650 zrele(dzp);
1651 }
1652
1653 zfs_exit(zfsvfs, FTAG);
1654
1655 return (error);
1656 }
1657
1658 module_param(zfs_admin_snapshot, int, 0644);
1659 MODULE_PARM_DESC(zfs_admin_snapshot, "Enable mkdir/rmdir/mv in .zfs/snapshot");
1660
1661 module_param(zfs_expire_snapshot, int, 0644);
1662 MODULE_PARM_DESC(zfs_expire_snapshot, "Seconds to expire .zfs/snapshot");
1663
1664 module_param(zfs_snapshot_no_setuid, int, 0644);
1665 MODULE_PARM_DESC(zfs_snapshot_no_setuid,
1666 "Disable setuid/setgid for automounts in .zfs/snapshot");
1667