udev: String substitutions can be done in ENV, too
[systemd_ALT.git] / src / core / mount.c
blobd3cba02aa5ece18b9347db38544ea58e3d0c955d
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <errno.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <sys/epoll.h>
8 #include "sd-messages.h"
10 #include "alloc-util.h"
11 #include "dbus-mount.h"
12 #include "dbus-unit.h"
13 #include "device.h"
14 #include "exit-status.h"
15 #include "format-util.h"
16 #include "fs-util.h"
17 #include "fstab-util.h"
18 #include "initrd-util.h"
19 #include "libmount-util.h"
20 #include "log.h"
21 #include "manager.h"
22 #include "mkdir-label.h"
23 #include "mount-setup.h"
24 #include "mount.h"
25 #include "mountpoint-util.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "process-util.h"
29 #include "serialize.h"
30 #include "special.h"
31 #include "stat-util.h"
32 #include "string-table.h"
33 #include "string-util.h"
34 #include "strv.h"
35 #include "unit-name.h"
36 #include "unit.h"
38 #define RETRY_UMOUNT_MAX 32
40 static const UnitActiveState state_translation_table[_MOUNT_STATE_MAX] = {
41 [MOUNT_DEAD] = UNIT_INACTIVE,
42 [MOUNT_MOUNTING] = UNIT_ACTIVATING,
43 [MOUNT_MOUNTING_DONE] = UNIT_ACTIVATING,
44 [MOUNT_MOUNTED] = UNIT_ACTIVE,
45 [MOUNT_REMOUNTING] = UNIT_RELOADING,
46 [MOUNT_UNMOUNTING] = UNIT_DEACTIVATING,
47 [MOUNT_REMOUNTING_SIGTERM] = UNIT_RELOADING,
48 [MOUNT_REMOUNTING_SIGKILL] = UNIT_RELOADING,
49 [MOUNT_UNMOUNTING_SIGTERM] = UNIT_DEACTIVATING,
50 [MOUNT_UNMOUNTING_SIGKILL] = UNIT_DEACTIVATING,
51 [MOUNT_FAILED] = UNIT_FAILED,
52 [MOUNT_CLEANING] = UNIT_MAINTENANCE,
55 static int mount_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
56 static int mount_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
57 static void mount_enter_dead(Mount *m, MountResult f);
58 static void mount_enter_mounted(Mount *m, MountResult f);
59 static void mount_cycle_clear(Mount *m);
60 static int mount_process_proc_self_mountinfo(Manager *m);
62 static bool MOUNT_STATE_WITH_PROCESS(MountState state) {
63 return IN_SET(state,
64 MOUNT_MOUNTING,
65 MOUNT_MOUNTING_DONE,
66 MOUNT_REMOUNTING,
67 MOUNT_REMOUNTING_SIGTERM,
68 MOUNT_REMOUNTING_SIGKILL,
69 MOUNT_UNMOUNTING,
70 MOUNT_UNMOUNTING_SIGTERM,
71 MOUNT_UNMOUNTING_SIGKILL,
72 MOUNT_CLEANING);
75 static MountParameters* get_mount_parameters_fragment(Mount *m) {
76 assert(m);
78 if (m->from_fragment)
79 return &m->parameters_fragment;
81 return NULL;
84 static MountParameters* get_mount_parameters(Mount *m) {
85 assert(m);
87 if (m->from_proc_self_mountinfo)
88 return &m->parameters_proc_self_mountinfo;
90 return get_mount_parameters_fragment(m);
93 static bool mount_is_network(const MountParameters *p) {
94 assert(p);
96 if (fstab_test_option(p->options, "_netdev\0"))
97 return true;
99 if (p->fstype && fstype_is_network(p->fstype))
100 return true;
102 return false;
105 static bool mount_is_nofail(const Mount *m) {
106 assert(m);
108 if (!m->from_fragment)
109 return false;
111 return fstab_test_yes_no_option(m->parameters_fragment.options, "nofail\0" "fail\0");
114 static bool mount_is_loop(const MountParameters *p) {
115 assert(p);
117 if (fstab_test_option(p->options, "loop\0"))
118 return true;
120 return false;
123 static bool mount_is_bind(const MountParameters *p) {
124 assert(p);
125 return fstab_is_bind(p->options, p->fstype);
128 static bool mount_is_bound_to_device(Mount *m) {
129 const MountParameters *p;
131 assert(m);
133 /* Determines whether to place a Requires= or BindsTo= dependency on the backing device unit. We do
134 * this by checking for the x-systemd.device-bound mount option. Iff it is set we use BindsTo=,
135 * otherwise Requires=. But note that we might combine the latter with StopPropagatedFrom=, see
136 * below. */
138 p = get_mount_parameters(m);
139 if (!p)
140 return false;
142 return fstab_test_option(p->options, "x-systemd.device-bound\0");
145 static bool mount_propagate_stop(Mount *m) {
146 assert(m);
148 if (mount_is_bound_to_device(m)) /* If we are using BindsTo= the stop propagation is implicit, no need to bother */
149 return false;
151 return m->from_fragment; /* let's propagate stop whenever this is an explicitly configured unit,
152 * otherwise let's not bother. */
155 static bool mount_needs_quota(const MountParameters *p) {
156 assert(p);
158 if (p->fstype && !fstype_needs_quota(p->fstype))
159 return false;
161 if (mount_is_bind(p))
162 return false;
164 return fstab_test_option(p->options,
165 "usrquota\0" "grpquota\0" "quota\0" "usrjquota\0" "grpjquota\0");
168 static void mount_init(Unit *u) {
169 Mount *m = MOUNT(u);
171 assert(m);
172 assert(u);
173 assert(u->load_state == UNIT_STUB);
175 m->timeout_usec = u->manager->default_timeout_start_usec;
177 m->exec_context.std_output = u->manager->default_std_output;
178 m->exec_context.std_error = u->manager->default_std_error;
180 m->directory_mode = 0755;
182 /* We need to make sure that /usr/bin/mount is always called
183 * in the same process group as us, so that the autofs kernel
184 * side doesn't send us another mount request while we are
185 * already trying to comply its last one. */
186 m->exec_context.same_pgrp = true;
188 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
190 u->ignore_on_isolate = true;
193 static int mount_arm_timer(Mount *m, usec_t usec) {
194 int r;
196 assert(m);
198 if (usec == USEC_INFINITY)
199 return sd_event_source_set_enabled(m->timer_event_source, SD_EVENT_OFF);
201 if (m->timer_event_source) {
202 r = sd_event_source_set_time(m->timer_event_source, usec);
203 if (r < 0)
204 return r;
206 return sd_event_source_set_enabled(m->timer_event_source, SD_EVENT_ONESHOT);
209 r = sd_event_add_time(
210 UNIT(m)->manager->event,
211 &m->timer_event_source,
212 CLOCK_MONOTONIC,
213 usec, 0,
214 mount_dispatch_timer, m);
215 if (r < 0)
216 return r;
218 (void) sd_event_source_set_description(m->timer_event_source, "mount-timer");
220 return 0;
223 static void mount_unwatch_control_pid(Mount *m) {
224 assert(m);
226 if (m->control_pid <= 0)
227 return;
229 unit_unwatch_pid(UNIT(m), TAKE_PID(m->control_pid));
232 static void mount_parameters_done(MountParameters *p) {
233 assert(p);
235 p->what = mfree(p->what);
236 p->options = mfree(p->options);
237 p->fstype = mfree(p->fstype);
240 static void mount_done(Unit *u) {
241 Mount *m = MOUNT(u);
243 assert(m);
245 m->where = mfree(m->where);
247 mount_parameters_done(&m->parameters_proc_self_mountinfo);
248 mount_parameters_done(&m->parameters_fragment);
250 m->exec_runtime = exec_runtime_free(m->exec_runtime);
251 exec_command_done_array(m->exec_command, _MOUNT_EXEC_COMMAND_MAX);
252 m->control_command = NULL;
254 mount_unwatch_control_pid(m);
256 m->timer_event_source = sd_event_source_disable_unref(m->timer_event_source);
259 static int update_parameters_proc_self_mountinfo(
260 Mount *m,
261 const char *what,
262 const char *options,
263 const char *fstype) {
265 MountParameters *p;
266 int r, q, w;
268 p = &m->parameters_proc_self_mountinfo;
270 r = free_and_strdup(&p->what, what);
271 if (r < 0)
272 return r;
274 q = free_and_strdup(&p->options, options);
275 if (q < 0)
276 return q;
278 w = free_and_strdup(&p->fstype, fstype);
279 if (w < 0)
280 return w;
282 return r > 0 || q > 0 || w > 0;
285 static int mount_add_mount_dependencies(Mount *m) {
286 MountParameters *pm;
287 Unit *other;
288 Set *s;
289 int r;
291 assert(m);
293 if (!path_equal(m->where, "/")) {
294 _cleanup_free_ char *parent = NULL;
296 /* Adds in links to other mount points that might lie further up in the hierarchy */
298 r = path_extract_directory(m->where, &parent);
299 if (r < 0)
300 return r;
302 r = unit_require_mounts_for(UNIT(m), parent, UNIT_DEPENDENCY_IMPLICIT);
303 if (r < 0)
304 return r;
307 /* Adds in dependencies to other mount points that might be needed for the source path (if this is a bind mount
308 * or a loop mount) to be available. */
309 pm = get_mount_parameters_fragment(m);
310 if (pm && pm->what &&
311 path_is_absolute(pm->what) &&
312 (mount_is_bind(pm) || mount_is_loop(pm) || !mount_is_network(pm))) {
314 r = unit_require_mounts_for(UNIT(m), pm->what, UNIT_DEPENDENCY_FILE);
315 if (r < 0)
316 return r;
319 /* Adds in dependencies to other units that use this path or paths further down in the hierarchy */
320 s = manager_get_units_requiring_mounts_for(UNIT(m)->manager, m->where);
321 SET_FOREACH(other, s) {
323 if (other->load_state != UNIT_LOADED)
324 continue;
326 if (other == UNIT(m))
327 continue;
329 r = unit_add_dependency(other, UNIT_AFTER, UNIT(m), true, UNIT_DEPENDENCY_PATH);
330 if (r < 0)
331 return r;
333 if (UNIT(m)->fragment_path) {
334 /* If we have fragment configuration, then make this dependency required */
335 r = unit_add_dependency(other, UNIT_REQUIRES, UNIT(m), true, UNIT_DEPENDENCY_PATH);
336 if (r < 0)
337 return r;
341 return 0;
344 static int mount_add_device_dependencies(Mount *m) {
345 UnitDependencyMask mask;
346 MountParameters *p;
347 UnitDependency dep;
348 int r;
350 assert(m);
352 log_unit_trace(UNIT(m), "Processing implicit device dependencies");
354 p = get_mount_parameters(m);
355 if (!p) {
356 log_unit_trace(UNIT(m), "Missing mount parameters, skipping implicit device dependencies");
357 return 0;
360 if (!p->what) {
361 log_unit_trace(UNIT(m), "Missing mount source, skipping implicit device dependencies");
362 return 0;
365 if (mount_is_bind(p)) {
366 log_unit_trace(UNIT(m), "Mount unit is a bind mount, skipping implicit device dependencies");
367 return 0;
370 if (!is_device_path(p->what)) {
371 log_unit_trace(UNIT(m), "Mount source is not a device path, skipping implicit device dependencies");
372 return 0;
375 /* /dev/root is a really weird thing, it's not a real device, but just a path the kernel exports for
376 * the root file system specified on the kernel command line. Ignore it here. */
377 if (PATH_IN_SET(p->what, "/dev/root", "/dev/nfs")) {
378 log_unit_trace(UNIT(m), "Mount source is in /dev/root or /dev/nfs, skipping implicit device dependencies");
379 return 0;
382 if (path_equal(m->where, "/")) {
383 log_unit_trace(UNIT(m), "Mount destination is '/', skipping implicit device dependencies");
384 return 0;
387 /* Mount units from /proc/self/mountinfo are not bound to devices by default since they're subject to
388 * races when mounts are established by other tools with different backing devices than what we
389 * maintain. The user can still force this to be a BindsTo= dependency with an appropriate option (or
390 * udev property) so the mount units are automatically stopped when the device disappears
391 * suddenly. */
392 dep = mount_is_bound_to_device(m) ? UNIT_BINDS_TO : UNIT_REQUIRES;
394 /* We always use 'what' from /proc/self/mountinfo if mounted */
395 mask = m->from_proc_self_mountinfo ? UNIT_DEPENDENCY_MOUNTINFO : UNIT_DEPENDENCY_MOUNT_FILE;
397 r = unit_add_node_dependency(UNIT(m), p->what, dep, mask);
398 if (r < 0)
399 return r;
400 if (r > 0)
401 log_unit_trace(UNIT(m), "Added %s dependency on %s", unit_dependency_to_string(dep), p->what);
403 if (mount_propagate_stop(m)) {
404 r = unit_add_node_dependency(UNIT(m), p->what, UNIT_STOP_PROPAGATED_FROM, mask);
405 if (r < 0)
406 return r;
407 if (r > 0)
408 log_unit_trace(UNIT(m), "Added %s dependency on %s",
409 unit_dependency_to_string(UNIT_STOP_PROPAGATED_FROM), p->what);
412 r = unit_add_blockdev_dependency(UNIT(m), p->what, mask);
413 if (r > 0)
414 log_unit_trace(UNIT(m), "Added %s dependency on %s", unit_dependency_to_string(UNIT_AFTER), p->what);
416 return 0;
419 static int mount_add_quota_dependencies(Mount *m) {
420 MountParameters *p;
421 int r;
423 assert(m);
425 if (!MANAGER_IS_SYSTEM(UNIT(m)->manager))
426 return 0;
428 p = get_mount_parameters_fragment(m);
429 if (!p)
430 return 0;
432 if (!mount_needs_quota(p))
433 return 0;
435 r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_BEFORE, UNIT_WANTS, SPECIAL_QUOTACHECK_SERVICE,
436 /* add_reference= */ true, UNIT_DEPENDENCY_FILE);
437 if (r < 0)
438 return r;
440 r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_BEFORE, UNIT_WANTS, SPECIAL_QUOTAON_SERVICE,
441 /* add_reference= */true, UNIT_DEPENDENCY_FILE);
442 if (r < 0)
443 return r;
445 return 0;
448 static bool mount_is_extrinsic(Unit *u) {
449 MountParameters *p;
450 Mount *m = MOUNT(u);
451 assert(m);
453 /* Returns true for all units that are "magic" and should be excluded from the usual
454 * start-up and shutdown dependencies. We call them "extrinsic" here, as they are generally
455 * mounted outside of the systemd dependency logic. We shouldn't attempt to manage them
456 * ourselves but it's fine if the user operates on them with us. */
458 /* We only automatically manage mounts if we are in system mode */
459 if (MANAGER_IS_USER(u->manager))
460 return true;
462 p = get_mount_parameters(m);
463 if (p && fstab_is_extrinsic(m->where, p->options))
464 return true;
466 return false;
469 static bool mount_is_credentials(Mount *m) {
470 const char *e;
472 assert(m);
474 /* Returns true if this is a credentials mount. We don't want automatic dependencies on credential
475 * mounts, since they are managed by us for even the earliest services, and we never want anything to
476 * be ordered before them hence. */
478 e = path_startswith(m->where, UNIT(m)->manager->prefix[EXEC_DIRECTORY_RUNTIME]);
479 if (!e)
480 return false;
482 return !isempty(path_startswith(e, "credentials"));
485 static int mount_add_default_ordering_dependencies(Mount *m, MountParameters *p, UnitDependencyMask mask) {
486 const char *after, *before, *e;
487 int r;
489 assert(m);
491 e = path_startswith(m->where, "/sysroot");
492 if (e && in_initrd()) {
493 /* All mounts under /sysroot need to happen later, at initrd-fs.target time. IOW,
494 * it's not technically part of the basic initrd filesystem itself, and so
495 * shouldn't inherit the default Before=local-fs.target dependency. However,
496 * these mounts still need to start after local-fs-pre.target, as a sync point
497 * for things like systemd-hibernate-resume.service that should start before
498 * any mounts. */
500 after = SPECIAL_LOCAL_FS_PRE_TARGET;
501 before = isempty(e) ? SPECIAL_INITRD_ROOT_FS_TARGET : SPECIAL_INITRD_FS_TARGET;
503 } else if (in_initrd() && path_startswith(m->where, "/sysusr/usr")) {
504 after = SPECIAL_LOCAL_FS_PRE_TARGET;
505 before = SPECIAL_INITRD_USR_FS_TARGET;
507 } else if (mount_is_credentials(m))
508 after = before = NULL;
510 else if (mount_is_network(p)) {
511 after = SPECIAL_REMOTE_FS_PRE_TARGET;
512 before = SPECIAL_REMOTE_FS_TARGET;
514 } else {
515 after = SPECIAL_LOCAL_FS_PRE_TARGET;
516 before = SPECIAL_LOCAL_FS_TARGET;
519 if (before && !mount_is_nofail(m)) {
520 r = unit_add_dependency_by_name(UNIT(m), UNIT_BEFORE, before, /* add_reference= */ true, mask);
521 if (r < 0)
522 return r;
525 if (after) {
526 r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, after, /* add_reference= */ true, mask);
527 if (r < 0)
528 return r;
531 r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET,
532 /* add_reference= */ true, mask);
533 if (r < 0)
534 return r;
536 /* If this is a tmpfs mount then we have to unmount it before we try to deactivate swaps */
537 if (streq_ptr(p->fstype, "tmpfs") && !mount_is_credentials(m)) {
538 r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, SPECIAL_SWAP_TARGET,
539 /* add_reference= */ true, mask);
540 if (r < 0)
541 return r;
544 return 0;
547 static int mount_add_default_network_dependencies(Mount *m, MountParameters *p, UnitDependencyMask mask) {
548 int r;
550 assert(m);
552 if (!mount_is_network(p))
553 return 0;
555 /* We order ourselves after network.target. This is primarily useful at shutdown: services that take
556 * down the network should order themselves before network.target, so that they are shut down only
557 * after this mount unit is stopped. */
559 r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, SPECIAL_NETWORK_TARGET,
560 /* add_reference= */ true, mask);
561 if (r < 0)
562 return r;
564 /* We pull in network-online.target, and order ourselves after it. This is useful at start-up to
565 * actively pull in tools that want to be started before we start mounting network file systems, and
566 * whose purpose it is to delay this until the network is "up". */
568 return unit_add_two_dependencies_by_name(UNIT(m), UNIT_WANTS, UNIT_AFTER, SPECIAL_NETWORK_ONLINE_TARGET,
569 /* add_reference= */ true, mask);
572 static int mount_add_default_dependencies(Mount *m) {
573 UnitDependencyMask mask;
574 MountParameters *p;
575 int r;
577 assert(m);
579 if (!UNIT(m)->default_dependencies)
580 return 0;
582 /* We do not add any default dependencies to /, /usr or /run/initramfs/, since they are
583 * guaranteed to stay mounted the whole time, since our system is on it. Also, don't
584 * bother with anything mounted below virtual file systems, it's also going to be virtual,
585 * and hence not worth the effort. */
586 if (mount_is_extrinsic(UNIT(m)))
587 return 0;
589 p = get_mount_parameters(m);
590 if (!p)
591 return 0;
593 mask = m->from_proc_self_mountinfo ? UNIT_DEPENDENCY_MOUNTINFO : UNIT_DEPENDENCY_MOUNT_FILE;
595 r = mount_add_default_ordering_dependencies(m, p, mask);
596 if (r < 0)
597 return r;
599 r = mount_add_default_network_dependencies(m, p, mask);
600 if (r < 0)
601 return r;
603 return 0;
606 static int mount_verify(Mount *m) {
607 _cleanup_free_ char *e = NULL;
608 MountParameters *p;
609 int r;
611 assert(m);
612 assert(UNIT(m)->load_state == UNIT_LOADED);
614 if (!m->from_fragment && !m->from_proc_self_mountinfo && !UNIT(m)->perpetual)
615 return -ENOENT;
617 r = unit_name_from_path(m->where, ".mount", &e);
618 if (r < 0)
619 return log_unit_error_errno(UNIT(m), r, "Failed to generate unit name from mount path: %m");
621 if (!unit_has_name(UNIT(m), e))
622 return log_unit_error_errno(UNIT(m), SYNTHETIC_ERRNO(ENOEXEC), "Where= setting doesn't match unit name. Refusing.");
624 if (mount_point_is_api(m->where) || mount_point_ignore(m->where))
625 return log_unit_error_errno(UNIT(m), SYNTHETIC_ERRNO(ENOEXEC), "Cannot create mount unit for API file system %s. Refusing.", m->where);
627 p = get_mount_parameters_fragment(m);
628 if (p && !p->what && !UNIT(m)->perpetual)
629 return log_unit_error_errno(UNIT(m), SYNTHETIC_ERRNO(ENOEXEC),
630 "What= setting is missing. Refusing.");
632 if (m->exec_context.pam_name && m->kill_context.kill_mode != KILL_CONTROL_GROUP)
633 return log_unit_error_errno(UNIT(m), SYNTHETIC_ERRNO(ENOEXEC), "Unit has PAM enabled. Kill mode must be set to control-group'. Refusing.");
635 return 0;
638 static int mount_add_non_exec_dependencies(Mount *m) {
639 int r;
641 assert(m);
643 /* We may be called due to this mount appearing in /proc/self/mountinfo, hence we clear all existing
644 * dependencies that were initialized from the unit file but whose final value really depends on the
645 * content of /proc/self/mountinfo. Some (such as m->where) might have become stale now. */
646 unit_remove_dependencies(UNIT(m), UNIT_DEPENDENCY_MOUNTINFO | UNIT_DEPENDENCY_MOUNT_FILE);
648 if (!m->where)
649 return 0;
651 /* Adds in all dependencies directly responsible for ordering the mount, as opposed to dependencies
652 * resulting from the ExecContext and such. */
654 r = mount_add_device_dependencies(m);
655 if (r < 0)
656 return r;
658 r = mount_add_mount_dependencies(m);
659 if (r < 0)
660 return r;
662 r = mount_add_quota_dependencies(m);
663 if (r < 0)
664 return r;
666 r = mount_add_default_dependencies(m);
667 if (r < 0)
668 return r;
670 return 0;
673 static int mount_add_extras(Mount *m) {
674 Unit *u = UNIT(m);
675 int r;
677 assert(m);
679 /* Note: this call might be called after we already have been loaded once (and even when it has already been
680 * activated), in case data from /proc/self/mountinfo has changed. This means all code here needs to be ready
681 * to run with an already set up unit. */
683 if (u->fragment_path)
684 m->from_fragment = true;
686 if (!m->where) {
687 r = unit_name_to_path(u->id, &m->where);
688 if (r == -ENAMETOOLONG)
689 log_unit_error_errno(u, r, "Failed to derive mount point path from unit name, because unit name is hashed. "
690 "Set \"Where=\" in the unit file explicitly.");
691 if (r < 0)
692 return r;
695 path_simplify(m->where);
697 if (!u->description) {
698 r = unit_set_description(u, m->where);
699 if (r < 0)
700 return r;
703 r = unit_patch_contexts(u);
704 if (r < 0)
705 return r;
707 r = unit_add_exec_dependencies(u, &m->exec_context);
708 if (r < 0)
709 return r;
711 r = unit_set_default_slice(u);
712 if (r < 0)
713 return r;
715 r = mount_add_non_exec_dependencies(m);
716 if (r < 0)
717 return r;
719 return 0;
722 static void mount_load_root_mount(Unit *u) {
723 assert(u);
725 if (!unit_has_name(u, SPECIAL_ROOT_MOUNT))
726 return;
728 u->perpetual = true;
729 u->default_dependencies = false;
731 /* The stdio/kmsg bridge socket is on /, in order to avoid a dep loop, don't use kmsg logging for -.mount */
732 MOUNT(u)->exec_context.std_output = EXEC_OUTPUT_NULL;
733 MOUNT(u)->exec_context.std_input = EXEC_INPUT_NULL;
735 if (!u->description)
736 u->description = strdup("Root Mount");
739 static int mount_load(Unit *u) {
740 Mount *m = MOUNT(u);
741 int r, q = 0;
743 assert(m);
744 assert(u);
745 assert(u->load_state == UNIT_STUB);
747 mount_load_root_mount(u);
749 bool fragment_optional = m->from_proc_self_mountinfo || u->perpetual;
750 r = unit_load_fragment_and_dropin(u, !fragment_optional);
752 /* Add in some extras. Note we do this in all cases (even if we failed to load the unit) when announced by the
753 * kernel, because we need some things to be set up no matter what when the kernel establishes a mount and thus
754 * we need to update the state in our unit to track it. After all, consider that we don't allow changing the
755 * 'slice' field for a unit once it is active. */
756 if (u->load_state == UNIT_LOADED || m->from_proc_self_mountinfo || u->perpetual)
757 q = mount_add_extras(m);
759 if (r < 0)
760 return r;
761 if (q < 0)
762 return q;
763 if (u->load_state != UNIT_LOADED)
764 return 0;
766 return mount_verify(m);
769 static void mount_set_state(Mount *m, MountState state) {
770 MountState old_state;
771 assert(m);
773 if (m->state != state)
774 bus_unit_send_pending_change_signal(UNIT(m), false);
776 old_state = m->state;
777 m->state = state;
779 if (!MOUNT_STATE_WITH_PROCESS(state)) {
780 m->timer_event_source = sd_event_source_disable_unref(m->timer_event_source);
781 mount_unwatch_control_pid(m);
782 m->control_command = NULL;
783 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
786 if (state != old_state)
787 log_unit_debug(UNIT(m), "Changed %s -> %s", mount_state_to_string(old_state), mount_state_to_string(state));
789 unit_notify(UNIT(m), state_translation_table[old_state], state_translation_table[state], m->reload_result == MOUNT_SUCCESS);
792 static int mount_coldplug(Unit *u) {
793 Mount *m = MOUNT(u);
794 int r;
796 assert(m);
797 assert(m->state == MOUNT_DEAD);
799 if (m->deserialized_state == m->state)
800 return 0;
802 if (m->control_pid > 0 &&
803 pid_is_unwaited(m->control_pid) &&
804 MOUNT_STATE_WITH_PROCESS(m->deserialized_state)) {
806 r = unit_watch_pid(UNIT(m), m->control_pid, false);
807 if (r < 0)
808 return r;
810 r = mount_arm_timer(m, usec_add(u->state_change_timestamp.monotonic, m->timeout_usec));
811 if (r < 0)
812 return r;
815 if (!IN_SET(m->deserialized_state, MOUNT_DEAD, MOUNT_FAILED))
816 (void) unit_setup_exec_runtime(u);
818 mount_set_state(m, m->deserialized_state);
819 return 0;
822 static void mount_catchup(Unit *u) {
823 Mount *m = MOUNT(ASSERT_PTR(u));
825 assert(m);
827 /* Adjust the deserialized state. See comments in mount_process_proc_self_mountinfo(). */
828 if (m->from_proc_self_mountinfo)
829 switch (m->state) {
830 case MOUNT_DEAD:
831 case MOUNT_FAILED:
832 assert(m->control_pid == 0);
833 (void) unit_acquire_invocation_id(u);
834 mount_cycle_clear(m);
835 mount_enter_mounted(m, MOUNT_SUCCESS);
836 break;
837 case MOUNT_MOUNTING:
838 assert(m->control_pid > 0);
839 mount_set_state(m, MOUNT_MOUNTING_DONE);
840 break;
841 default:
842 break;
844 else
845 switch (m->state) {
846 case MOUNT_MOUNTING_DONE:
847 assert(m->control_pid > 0);
848 mount_set_state(m, MOUNT_MOUNTING);
849 break;
850 case MOUNT_MOUNTED:
851 assert(m->control_pid == 0);
852 mount_enter_dead(m, MOUNT_SUCCESS);
853 break;
854 default:
855 break;
859 static void mount_dump(Unit *u, FILE *f, const char *prefix) {
860 Mount *m = MOUNT(u);
861 MountParameters *p;
863 assert(m);
864 assert(f);
866 p = get_mount_parameters(m);
868 fprintf(f,
869 "%sMount State: %s\n"
870 "%sResult: %s\n"
871 "%sClean Result: %s\n"
872 "%sWhere: %s\n"
873 "%sWhat: %s\n"
874 "%sFile System Type: %s\n"
875 "%sOptions: %s\n"
876 "%sFrom /proc/self/mountinfo: %s\n"
877 "%sFrom fragment: %s\n"
878 "%sExtrinsic: %s\n"
879 "%sDirectoryMode: %04o\n"
880 "%sSloppyOptions: %s\n"
881 "%sLazyUnmount: %s\n"
882 "%sForceUnmount: %s\n"
883 "%sReadWriteOnly: %s\n"
884 "%sTimeoutSec: %s\n",
885 prefix, mount_state_to_string(m->state),
886 prefix, mount_result_to_string(m->result),
887 prefix, mount_result_to_string(m->clean_result),
888 prefix, m->where,
889 prefix, p ? strna(p->what) : "n/a",
890 prefix, p ? strna(p->fstype) : "n/a",
891 prefix, p ? strna(p->options) : "n/a",
892 prefix, yes_no(m->from_proc_self_mountinfo),
893 prefix, yes_no(m->from_fragment),
894 prefix, yes_no(mount_is_extrinsic(u)),
895 prefix, m->directory_mode,
896 prefix, yes_no(m->sloppy_options),
897 prefix, yes_no(m->lazy_unmount),
898 prefix, yes_no(m->force_unmount),
899 prefix, yes_no(m->read_write_only),
900 prefix, FORMAT_TIMESPAN(m->timeout_usec, USEC_PER_SEC));
902 if (m->control_pid > 0)
903 fprintf(f,
904 "%sControl PID: "PID_FMT"\n",
905 prefix, m->control_pid);
907 exec_context_dump(&m->exec_context, f, prefix);
908 kill_context_dump(&m->kill_context, f, prefix);
909 cgroup_context_dump(UNIT(m), f, prefix);
912 static int mount_spawn(Mount *m, ExecCommand *c, pid_t *ret_pid) {
914 _cleanup_(exec_params_clear) ExecParameters exec_params = {
915 .flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN,
916 .stdin_fd = -EBADF,
917 .stdout_fd = -EBADF,
918 .stderr_fd = -EBADF,
919 .exec_fd = -EBADF,
921 pid_t pid;
922 int r;
924 assert(m);
925 assert(c);
926 assert(ret_pid);
928 r = unit_prepare_exec(UNIT(m));
929 if (r < 0)
930 return r;
932 r = mount_arm_timer(m, usec_add(now(CLOCK_MONOTONIC), m->timeout_usec));
933 if (r < 0)
934 return r;
936 r = unit_set_exec_params(UNIT(m), &exec_params);
937 if (r < 0)
938 return r;
940 r = exec_spawn(UNIT(m),
942 &m->exec_context,
943 &exec_params,
944 m->exec_runtime,
945 &m->cgroup_context,
946 &pid);
947 if (r < 0)
948 return r;
950 r = unit_watch_pid(UNIT(m), pid, true);
951 if (r < 0)
952 return r;
954 *ret_pid = pid;
955 return 0;
958 static void mount_enter_dead(Mount *m, MountResult f) {
959 assert(m);
961 if (m->result == MOUNT_SUCCESS)
962 m->result = f;
964 unit_log_result(UNIT(m), m->result == MOUNT_SUCCESS, mount_result_to_string(m->result));
965 unit_warn_leftover_processes(UNIT(m), unit_log_leftover_process_stop);
967 mount_set_state(m, m->result != MOUNT_SUCCESS ? MOUNT_FAILED : MOUNT_DEAD);
969 m->exec_runtime = exec_runtime_destroy(m->exec_runtime);
971 unit_destroy_runtime_data(UNIT(m), &m->exec_context);
973 unit_unref_uid_gid(UNIT(m), true);
975 /* Any dependencies based on /proc/self/mountinfo are now stale. Let's re-generate dependencies from
976 * .mount unit. */
977 (void) mount_add_non_exec_dependencies(m);
980 static void mount_enter_mounted(Mount *m, MountResult f) {
981 assert(m);
983 if (m->result == MOUNT_SUCCESS)
984 m->result = f;
986 mount_set_state(m, MOUNT_MOUNTED);
989 static void mount_enter_dead_or_mounted(Mount *m, MountResult f) {
990 assert(m);
992 /* Enter DEAD or MOUNTED state, depending on what the kernel currently says about the mount point. We use this
993 * whenever we executed an operation, so that our internal state reflects what the kernel says again, after all
994 * ultimately we just mirror the kernel's internal state on this. */
996 if (m->from_proc_self_mountinfo)
997 mount_enter_mounted(m, f);
998 else
999 mount_enter_dead(m, f);
1002 static int state_to_kill_operation(MountState state) {
1003 switch (state) {
1005 case MOUNT_REMOUNTING_SIGTERM:
1006 return KILL_RESTART;
1008 case MOUNT_UNMOUNTING_SIGTERM:
1009 return KILL_TERMINATE;
1011 case MOUNT_REMOUNTING_SIGKILL:
1012 case MOUNT_UNMOUNTING_SIGKILL:
1013 return KILL_KILL;
1015 default:
1016 return _KILL_OPERATION_INVALID;
1020 static void mount_enter_signal(Mount *m, MountState state, MountResult f) {
1021 int r;
1023 assert(m);
1025 if (m->result == MOUNT_SUCCESS)
1026 m->result = f;
1028 r = unit_kill_context(
1029 UNIT(m),
1030 &m->kill_context,
1031 state_to_kill_operation(state),
1033 m->control_pid,
1034 false);
1035 if (r < 0)
1036 goto fail;
1038 if (r > 0) {
1039 r = mount_arm_timer(m, usec_add(now(CLOCK_MONOTONIC), m->timeout_usec));
1040 if (r < 0)
1041 goto fail;
1043 mount_set_state(m, state);
1044 } else if (state == MOUNT_REMOUNTING_SIGTERM && m->kill_context.send_sigkill)
1045 mount_enter_signal(m, MOUNT_REMOUNTING_SIGKILL, MOUNT_SUCCESS);
1046 else if (IN_SET(state, MOUNT_REMOUNTING_SIGTERM, MOUNT_REMOUNTING_SIGKILL))
1047 mount_enter_mounted(m, MOUNT_SUCCESS);
1048 else if (state == MOUNT_UNMOUNTING_SIGTERM && m->kill_context.send_sigkill)
1049 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, MOUNT_SUCCESS);
1050 else
1051 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS);
1053 return;
1055 fail:
1056 log_unit_warning_errno(UNIT(m), r, "Failed to kill processes: %m");
1057 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_RESOURCES);
1060 static void mount_enter_unmounting(Mount *m) {
1061 int r;
1063 assert(m);
1065 /* Start counting our attempts */
1066 if (!IN_SET(m->state,
1067 MOUNT_UNMOUNTING,
1068 MOUNT_UNMOUNTING_SIGTERM,
1069 MOUNT_UNMOUNTING_SIGKILL))
1070 m->n_retry_umount = 0;
1072 m->control_command_id = MOUNT_EXEC_UNMOUNT;
1073 m->control_command = m->exec_command + MOUNT_EXEC_UNMOUNT;
1075 r = exec_command_set(m->control_command, UMOUNT_PATH, m->where, "-c", NULL);
1076 if (r >= 0 && m->lazy_unmount)
1077 r = exec_command_append(m->control_command, "-l", NULL);
1078 if (r >= 0 && m->force_unmount)
1079 r = exec_command_append(m->control_command, "-f", NULL);
1080 if (r < 0)
1081 goto fail;
1083 mount_unwatch_control_pid(m);
1085 r = mount_spawn(m, m->control_command, &m->control_pid);
1086 if (r < 0)
1087 goto fail;
1089 mount_set_state(m, MOUNT_UNMOUNTING);
1091 return;
1093 fail:
1094 log_unit_warning_errno(UNIT(m), r, "Failed to run 'umount' task: %m");
1095 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_RESOURCES);
1098 static void mount_enter_mounting(Mount *m) {
1099 int r;
1100 MountParameters *p;
1101 bool source_is_dir = true;
1103 assert(m);
1105 r = unit_fail_if_noncanonical(UNIT(m), m->where);
1106 if (r < 0)
1107 goto fail;
1109 p = get_mount_parameters_fragment(m);
1110 if (p && mount_is_bind(p)) {
1111 r = is_dir(p->what, /* follow = */ true);
1112 if (r < 0 && r != -ENOENT)
1113 log_unit_info_errno(UNIT(m), r, "Failed to determine type of bind mount source '%s', ignoring: %m", p->what);
1114 else if (r == 0)
1115 source_is_dir = false;
1118 if (source_is_dir)
1119 r = mkdir_p_label(m->where, m->directory_mode);
1120 else
1121 r = touch_file(m->where, /* parents = */ true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
1122 if (r < 0 && r != -EEXIST)
1123 log_unit_warning_errno(UNIT(m), r, "Failed to create mount point '%s', ignoring: %m", m->where);
1125 if (source_is_dir)
1126 unit_warn_if_dir_nonempty(UNIT(m), m->where);
1127 unit_warn_leftover_processes(UNIT(m), unit_log_leftover_process_start);
1129 m->control_command_id = MOUNT_EXEC_MOUNT;
1130 m->control_command = m->exec_command + MOUNT_EXEC_MOUNT;
1132 /* Create the source directory for bind-mounts if needed */
1133 if (p && mount_is_bind(p)) {
1134 r = mkdir_p_label(p->what, m->directory_mode);
1135 /* mkdir_p_label() can return -EEXIST if the target path exists and is not a directory - which is
1136 * totally OK, in case the user wants us to overmount a non-directory inode. Also -EROFS can be
1137 * returned on read-only filesystem. Moreover, -EACCES (and also maybe -EPERM?) may be returned
1138 * when the path is on NFS. See issue #24120. All such errors will be logged in the debug level. */
1139 if (r < 0 && r != -EEXIST)
1140 log_unit_full_errno(UNIT(m),
1141 (r == -EROFS || ERRNO_IS_PRIVILEGE(r)) ? LOG_DEBUG : LOG_WARNING,
1142 r, "Failed to make bind mount source '%s', ignoring: %m", p->what);
1145 if (p) {
1146 _cleanup_free_ char *opts = NULL;
1148 r = fstab_filter_options(p->options, "nofail\0" "noauto\0" "auto\0", NULL, NULL, NULL, &opts);
1149 if (r < 0)
1150 goto fail;
1152 r = exec_command_set(m->control_command, MOUNT_PATH, p->what, m->where, NULL);
1153 if (r >= 0 && m->sloppy_options)
1154 r = exec_command_append(m->control_command, "-s", NULL);
1155 if (r >= 0 && m->read_write_only)
1156 r = exec_command_append(m->control_command, "-w", NULL);
1157 if (r >= 0 && p->fstype)
1158 r = exec_command_append(m->control_command, "-t", p->fstype, NULL);
1159 if (r >= 0 && !isempty(opts))
1160 r = exec_command_append(m->control_command, "-o", opts, NULL);
1161 } else
1162 r = -ENOENT;
1163 if (r < 0)
1164 goto fail;
1166 mount_unwatch_control_pid(m);
1168 r = mount_spawn(m, m->control_command, &m->control_pid);
1169 if (r < 0)
1170 goto fail;
1172 mount_set_state(m, MOUNT_MOUNTING);
1174 return;
1176 fail:
1177 log_unit_warning_errno(UNIT(m), r, "Failed to run 'mount' task: %m");
1178 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_RESOURCES);
1181 static void mount_set_reload_result(Mount *m, MountResult result) {
1182 assert(m);
1184 /* Only store the first error we encounter */
1185 if (m->reload_result != MOUNT_SUCCESS)
1186 return;
1188 m->reload_result = result;
1191 static void mount_enter_remounting(Mount *m) {
1192 int r;
1193 MountParameters *p;
1195 assert(m);
1197 /* Reset reload result when we are about to start a new remount operation */
1198 m->reload_result = MOUNT_SUCCESS;
1200 m->control_command_id = MOUNT_EXEC_REMOUNT;
1201 m->control_command = m->exec_command + MOUNT_EXEC_REMOUNT;
1203 p = get_mount_parameters_fragment(m);
1204 if (p) {
1205 const char *o;
1207 if (p->options)
1208 o = strjoina("remount,", p->options);
1209 else
1210 o = "remount";
1212 r = exec_command_set(m->control_command, MOUNT_PATH,
1213 p->what, m->where,
1214 "-o", o, NULL);
1215 if (r >= 0 && m->sloppy_options)
1216 r = exec_command_append(m->control_command, "-s", NULL);
1217 if (r >= 0 && m->read_write_only)
1218 r = exec_command_append(m->control_command, "-w", NULL);
1219 if (r >= 0 && p->fstype)
1220 r = exec_command_append(m->control_command, "-t", p->fstype, NULL);
1221 } else
1222 r = -ENOENT;
1223 if (r < 0)
1224 goto fail;
1226 mount_unwatch_control_pid(m);
1228 r = mount_spawn(m, m->control_command, &m->control_pid);
1229 if (r < 0)
1230 goto fail;
1232 mount_set_state(m, MOUNT_REMOUNTING);
1234 return;
1236 fail:
1237 log_unit_warning_errno(UNIT(m), r, "Failed to run 'remount' task: %m");
1238 mount_set_reload_result(m, MOUNT_FAILURE_RESOURCES);
1239 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS);
1242 static void mount_cycle_clear(Mount *m) {
1243 assert(m);
1245 /* Clear all state we shall forget for this new cycle */
1247 m->result = MOUNT_SUCCESS;
1248 m->reload_result = MOUNT_SUCCESS;
1249 exec_command_reset_status_array(m->exec_command, _MOUNT_EXEC_COMMAND_MAX);
1250 UNIT(m)->reset_accounting = true;
1253 static int mount_start(Unit *u) {
1254 Mount *m = MOUNT(u);
1255 int r;
1257 assert(m);
1259 /* We cannot fulfill this request right now, try again later
1260 * please! */
1261 if (IN_SET(m->state,
1262 MOUNT_UNMOUNTING,
1263 MOUNT_UNMOUNTING_SIGTERM,
1264 MOUNT_UNMOUNTING_SIGKILL,
1265 MOUNT_CLEANING))
1266 return -EAGAIN;
1268 /* Already on it! */
1269 if (IN_SET(m->state, MOUNT_MOUNTING, MOUNT_MOUNTING_DONE))
1270 return 0;
1272 assert(IN_SET(m->state, MOUNT_DEAD, MOUNT_FAILED));
1274 r = unit_acquire_invocation_id(u);
1275 if (r < 0)
1276 return r;
1278 mount_cycle_clear(m);
1279 mount_enter_mounting(m);
1281 return 1;
1284 static int mount_stop(Unit *u) {
1285 Mount *m = MOUNT(u);
1287 assert(m);
1289 switch (m->state) {
1291 case MOUNT_UNMOUNTING:
1292 case MOUNT_UNMOUNTING_SIGKILL:
1293 case MOUNT_UNMOUNTING_SIGTERM:
1294 /* Already on it */
1295 return 0;
1297 case MOUNT_MOUNTING:
1298 case MOUNT_MOUNTING_DONE:
1299 case MOUNT_REMOUNTING:
1300 /* If we are still waiting for /bin/mount, we go directly into kill mode. */
1301 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGTERM, MOUNT_SUCCESS);
1302 return 0;
1304 case MOUNT_REMOUNTING_SIGTERM:
1305 /* If we are already waiting for a hung remount, convert this to the matching unmounting state */
1306 mount_set_state(m, MOUNT_UNMOUNTING_SIGTERM);
1307 return 0;
1309 case MOUNT_REMOUNTING_SIGKILL:
1310 /* as above */
1311 mount_set_state(m, MOUNT_UNMOUNTING_SIGKILL);
1312 return 0;
1314 case MOUNT_MOUNTED:
1315 mount_enter_unmounting(m);
1316 return 1;
1318 case MOUNT_CLEANING:
1319 /* If we are currently cleaning, then abort it, brutally. */
1320 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, MOUNT_SUCCESS);
1321 return 0;
1323 default:
1324 assert_not_reached();
1328 static int mount_reload(Unit *u) {
1329 Mount *m = MOUNT(u);
1331 assert(m);
1332 assert(m->state == MOUNT_MOUNTED);
1334 mount_enter_remounting(m);
1336 return 1;
1339 static int mount_serialize(Unit *u, FILE *f, FDSet *fds) {
1340 Mount *m = MOUNT(u);
1342 assert(m);
1343 assert(f);
1344 assert(fds);
1346 (void) serialize_item(f, "state", mount_state_to_string(m->state));
1347 (void) serialize_item(f, "result", mount_result_to_string(m->result));
1348 (void) serialize_item(f, "reload-result", mount_result_to_string(m->reload_result));
1349 (void) serialize_item_format(f, "n-retry-umount", "%u", m->n_retry_umount);
1351 if (m->control_pid > 0)
1352 (void) serialize_item_format(f, "control-pid", PID_FMT, m->control_pid);
1354 if (m->control_command_id >= 0)
1355 (void) serialize_item(f, "control-command", mount_exec_command_to_string(m->control_command_id));
1357 return 0;
1360 static int mount_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1361 Mount *m = MOUNT(u);
1362 int r;
1364 assert(m);
1365 assert(u);
1366 assert(key);
1367 assert(value);
1368 assert(fds);
1370 if (streq(key, "state")) {
1371 MountState state;
1373 state = mount_state_from_string(value);
1374 if (state < 0)
1375 log_unit_debug_errno(u, state, "Failed to parse state value: %s", value);
1376 else
1377 m->deserialized_state = state;
1379 } else if (streq(key, "result")) {
1380 MountResult f;
1382 f = mount_result_from_string(value);
1383 if (f < 0)
1384 log_unit_debug_errno(u, f, "Failed to parse result value: %s", value);
1385 else if (f != MOUNT_SUCCESS)
1386 m->result = f;
1388 } else if (streq(key, "reload-result")) {
1389 MountResult f;
1391 f = mount_result_from_string(value);
1392 if (f < 0)
1393 log_unit_debug_errno(u, f, "Failed to parse reload result value: %s", value);
1394 else if (f != MOUNT_SUCCESS)
1395 m->reload_result = f;
1397 } else if (streq(key, "n-retry-umount")) {
1399 r = safe_atou(value, &m->n_retry_umount);
1400 if (r < 0)
1401 log_unit_debug_errno(u, r, "Failed to parse n-retry-umount value: %s", value);
1403 } else if (streq(key, "control-pid")) {
1405 r = parse_pid(value, &m->control_pid);
1406 if (r < 0)
1407 log_unit_debug_errno(u, r, "Failed to parse control-pid value: %s", value);
1409 } else if (streq(key, "control-command")) {
1410 MountExecCommand id;
1412 id = mount_exec_command_from_string(value);
1413 if (id < 0)
1414 log_unit_debug_errno(u, id, "Failed to parse exec-command value: %s", value);
1415 else {
1416 m->control_command_id = id;
1417 m->control_command = m->exec_command + id;
1419 } else
1420 log_unit_debug(u, "Unknown serialization key: %s", key);
1422 return 0;
1425 _pure_ static UnitActiveState mount_active_state(Unit *u) {
1426 assert(u);
1428 return state_translation_table[MOUNT(u)->state];
1431 _pure_ static const char *mount_sub_state_to_string(Unit *u) {
1432 assert(u);
1434 return mount_state_to_string(MOUNT(u)->state);
1437 _pure_ static bool mount_may_gc(Unit *u) {
1438 Mount *m = MOUNT(u);
1440 assert(m);
1442 if (m->from_proc_self_mountinfo)
1443 return false;
1445 return true;
1448 static void mount_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1449 Mount *m = MOUNT(u);
1450 MountResult f;
1452 assert(m);
1453 assert(pid >= 0);
1455 if (pid != m->control_pid)
1456 return;
1458 /* So here's the thing, we really want to know before /usr/bin/mount or /usr/bin/umount exit whether
1459 * they established/remove a mount. This is important when mounting, but even more so when unmounting
1460 * since we need to deal with nested mounts and otherwise cannot safely determine whether to repeat
1461 * the unmounts. In theory, the kernel fires /proc/self/mountinfo changes off before returning from
1462 * the mount() or umount() syscalls, and thus we should see the changes to the proc file before we
1463 * process the waitid() for the /usr/bin/(u)mount processes. However, this is unfortunately racy: we
1464 * have to waitid() for processes using P_ALL (since we need to reap unexpected children that got
1465 * reparented to PID 1), but when using P_ALL we might end up reaping processes that terminated just
1466 * instants ago, i.e. already after our last event loop iteration (i.e. after the last point we might
1467 * have noticed /proc/self/mountinfo events via epoll). This means event loop priorities for
1468 * processing SIGCHLD vs. /proc/self/mountinfo IO events are not as relevant as we want. To fix that
1469 * race, let's explicitly scan /proc/self/mountinfo before we start processing /usr/bin/(u)mount
1470 * dying. It's ugly, but it makes our ordering systematic again, and makes sure we always see
1471 * /proc/self/mountinfo changes before our mount/umount exits. */
1472 (void) mount_process_proc_self_mountinfo(u->manager);
1474 m->control_pid = 0;
1476 if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL))
1477 f = MOUNT_SUCCESS;
1478 else if (code == CLD_EXITED)
1479 f = MOUNT_FAILURE_EXIT_CODE;
1480 else if (code == CLD_KILLED)
1481 f = MOUNT_FAILURE_SIGNAL;
1482 else if (code == CLD_DUMPED)
1483 f = MOUNT_FAILURE_CORE_DUMP;
1484 else
1485 assert_not_reached();
1487 if (IN_SET(m->state, MOUNT_REMOUNTING, MOUNT_REMOUNTING_SIGKILL, MOUNT_REMOUNTING_SIGTERM))
1488 mount_set_reload_result(m, f);
1489 else if (m->result == MOUNT_SUCCESS)
1490 m->result = f;
1492 if (m->control_command) {
1493 exec_status_exit(&m->control_command->exec_status, &m->exec_context, pid, code, status);
1495 m->control_command = NULL;
1496 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
1499 unit_log_process_exit(
1501 "Mount process",
1502 mount_exec_command_to_string(m->control_command_id),
1503 f == MOUNT_SUCCESS,
1504 code, status);
1506 /* Note that due to the io event priority logic, we can be sure the new mountinfo is loaded
1507 * before we process the SIGCHLD for the mount command. */
1509 switch (m->state) {
1511 case MOUNT_MOUNTING:
1512 /* Our mount point has not appeared in mountinfo. Something went wrong. */
1514 if (f == MOUNT_SUCCESS) {
1515 /* Either /bin/mount has an unexpected definition of success,
1516 * or someone raced us and we lost. */
1517 log_unit_warning(UNIT(m), "Mount process finished, but there is no mount.");
1518 f = MOUNT_FAILURE_PROTOCOL;
1520 mount_enter_dead(m, f);
1521 break;
1523 case MOUNT_MOUNTING_DONE:
1524 mount_enter_mounted(m, f);
1525 break;
1527 case MOUNT_REMOUNTING:
1528 case MOUNT_REMOUNTING_SIGTERM:
1529 case MOUNT_REMOUNTING_SIGKILL:
1530 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS);
1531 break;
1533 case MOUNT_UNMOUNTING:
1535 if (f == MOUNT_SUCCESS && m->from_proc_self_mountinfo) {
1537 /* Still a mount point? If so, let's try again. Most likely there were multiple mount points
1538 * stacked on top of each other. We might exceed the timeout specified by the user overall,
1539 * but we will stop as soon as any one umount times out. */
1541 if (m->n_retry_umount < RETRY_UMOUNT_MAX) {
1542 log_unit_debug(u, "Mount still present, trying again.");
1543 m->n_retry_umount++;
1544 mount_enter_unmounting(m);
1545 } else {
1546 log_unit_warning(u, "Mount still present after %u attempts to unmount, giving up.", m->n_retry_umount);
1547 mount_enter_mounted(m, f);
1549 } else
1550 mount_enter_dead_or_mounted(m, f);
1552 break;
1554 case MOUNT_UNMOUNTING_SIGKILL:
1555 case MOUNT_UNMOUNTING_SIGTERM:
1556 mount_enter_dead_or_mounted(m, f);
1557 break;
1559 case MOUNT_CLEANING:
1560 if (m->clean_result == MOUNT_SUCCESS)
1561 m->clean_result = f;
1563 mount_enter_dead(m, MOUNT_SUCCESS);
1564 break;
1566 default:
1567 assert_not_reached();
1570 /* Notify clients about changed exit status */
1571 unit_add_to_dbus_queue(u);
1574 static int mount_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
1575 Mount *m = MOUNT(userdata);
1577 assert(m);
1578 assert(m->timer_event_source == source);
1580 switch (m->state) {
1582 case MOUNT_MOUNTING:
1583 case MOUNT_MOUNTING_DONE:
1584 log_unit_warning(UNIT(m), "Mounting timed out. Terminating.");
1585 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGTERM, MOUNT_FAILURE_TIMEOUT);
1586 break;
1588 case MOUNT_REMOUNTING:
1589 log_unit_warning(UNIT(m), "Remounting timed out. Terminating remount process.");
1590 mount_set_reload_result(m, MOUNT_FAILURE_TIMEOUT);
1591 mount_enter_signal(m, MOUNT_REMOUNTING_SIGTERM, MOUNT_SUCCESS);
1592 break;
1594 case MOUNT_REMOUNTING_SIGTERM:
1595 mount_set_reload_result(m, MOUNT_FAILURE_TIMEOUT);
1597 if (m->kill_context.send_sigkill) {
1598 log_unit_warning(UNIT(m), "Remounting timed out. Killing.");
1599 mount_enter_signal(m, MOUNT_REMOUNTING_SIGKILL, MOUNT_SUCCESS);
1600 } else {
1601 log_unit_warning(UNIT(m), "Remounting timed out. Skipping SIGKILL. Ignoring.");
1602 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS);
1604 break;
1606 case MOUNT_REMOUNTING_SIGKILL:
1607 mount_set_reload_result(m, MOUNT_FAILURE_TIMEOUT);
1609 log_unit_warning(UNIT(m), "Mount process still around after SIGKILL. Ignoring.");
1610 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS);
1611 break;
1613 case MOUNT_UNMOUNTING:
1614 log_unit_warning(UNIT(m), "Unmounting timed out. Terminating.");
1615 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGTERM, MOUNT_FAILURE_TIMEOUT);
1616 break;
1618 case MOUNT_UNMOUNTING_SIGTERM:
1619 if (m->kill_context.send_sigkill) {
1620 log_unit_warning(UNIT(m), "Mount process timed out. Killing.");
1621 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, MOUNT_FAILURE_TIMEOUT);
1622 } else {
1623 log_unit_warning(UNIT(m), "Mount process timed out. Skipping SIGKILL. Ignoring.");
1624 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_TIMEOUT);
1626 break;
1628 case MOUNT_UNMOUNTING_SIGKILL:
1629 log_unit_warning(UNIT(m), "Mount process still around after SIGKILL. Ignoring.");
1630 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_TIMEOUT);
1631 break;
1633 case MOUNT_CLEANING:
1634 log_unit_warning(UNIT(m), "Cleaning timed out. killing.");
1636 if (m->clean_result == MOUNT_SUCCESS)
1637 m->clean_result = MOUNT_FAILURE_TIMEOUT;
1639 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, 0);
1640 break;
1642 default:
1643 assert_not_reached();
1646 return 0;
1649 static int mount_setup_new_unit(
1650 Manager *m,
1651 const char *name,
1652 const char *what,
1653 const char *where,
1654 const char *options,
1655 const char *fstype,
1656 MountProcFlags *ret_flags,
1657 Unit **ret) {
1659 _cleanup_(unit_freep) Unit *u = NULL;
1660 int r;
1662 assert(m);
1663 assert(name);
1664 assert(ret_flags);
1665 assert(ret);
1667 r = unit_new_for_name(m, sizeof(Mount), name, &u);
1668 if (r < 0)
1669 return r;
1671 r = free_and_strdup(&u->source_path, "/proc/self/mountinfo");
1672 if (r < 0)
1673 return r;
1675 r = free_and_strdup(&MOUNT(u)->where, where);
1676 if (r < 0)
1677 return r;
1679 r = update_parameters_proc_self_mountinfo(MOUNT(u), what, options, fstype);
1680 if (r < 0)
1681 return r;
1683 /* This unit was generated because /proc/self/mountinfo reported it. Remember this, so that by the
1684 * time we load the unit file for it (and thus add in extra deps right after) we know what source to
1685 * attributes the deps to. */
1686 MOUNT(u)->from_proc_self_mountinfo = true;
1688 r = mount_add_non_exec_dependencies(MOUNT(u));
1689 if (r < 0)
1690 return r;
1692 /* We have only allocated the stub now, let's enqueue this unit for loading now, so that everything
1693 * else is loaded in now. */
1694 unit_add_to_load_queue(u);
1696 *ret_flags = MOUNT_PROC_IS_MOUNTED | MOUNT_PROC_JUST_MOUNTED | MOUNT_PROC_JUST_CHANGED;
1697 *ret = TAKE_PTR(u);
1698 return 0;
1701 static int mount_setup_existing_unit(
1702 Unit *u,
1703 const char *what,
1704 const char *where,
1705 const char *options,
1706 const char *fstype,
1707 MountProcFlags *ret_flags) {
1709 int r;
1711 assert(u);
1712 assert(ret_flags);
1714 if (!MOUNT(u)->where) {
1715 MOUNT(u)->where = strdup(where);
1716 if (!MOUNT(u)->where)
1717 return -ENOMEM;
1720 /* In case we have multiple mounts established on the same mount point, let's merge flags set already
1721 * for the current unit. Note that the flags field is reset on each iteration of reading
1722 * /proc/self/mountinfo, hence we know for sure anything already set here is from the current
1723 * iteration and thus worthy of taking into account. */
1724 MountProcFlags flags =
1725 MOUNT(u)->proc_flags | MOUNT_PROC_IS_MOUNTED;
1727 r = update_parameters_proc_self_mountinfo(MOUNT(u), what, options, fstype);
1728 if (r < 0)
1729 return r;
1730 if (r > 0)
1731 flags |= MOUNT_PROC_JUST_CHANGED;
1733 /* There are two conditions when we consider a mount point just mounted: when we haven't seen it in
1734 * /proc/self/mountinfo before or when MOUNT_MOUNTING is our current state. Why bother with the
1735 * latter? Shouldn't that be covered by the former? No, during reload it is not because we might then
1736 * encounter a new /proc/self/mountinfo in combination with an old mount unit state (since it stems
1737 * from the serialized state), and need to catch up. Since we know that the MOUNT_MOUNTING state is
1738 * reached when we wait for the mount to appear we hence can assume that if we are in it, we are
1739 * actually seeing it established for the first time. */
1740 if (!MOUNT(u)->from_proc_self_mountinfo || MOUNT(u)->state == MOUNT_MOUNTING)
1741 flags |= MOUNT_PROC_JUST_MOUNTED;
1743 MOUNT(u)->from_proc_self_mountinfo = true;
1745 if (IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_BAD_SETTING, UNIT_ERROR)) {
1746 /* The unit was previously not found or otherwise not loaded. Now that the unit shows up in
1747 * /proc/self/mountinfo we should reconsider it this, hence set it to UNIT_LOADED. */
1748 u->load_state = UNIT_LOADED;
1749 u->load_error = 0;
1751 flags |= MOUNT_PROC_JUST_CHANGED;
1754 if (FLAGS_SET(flags, MOUNT_PROC_JUST_CHANGED)) {
1755 /* If things changed, then make sure that all deps are regenerated. Let's
1756 * first remove all automatic deps, and then add in the new ones. */
1757 r = mount_add_non_exec_dependencies(MOUNT(u));
1758 if (r < 0)
1759 return r;
1762 *ret_flags = flags;
1763 return 0;
1766 static int mount_setup_unit(
1767 Manager *m,
1768 const char *what,
1769 const char *where,
1770 const char *options,
1771 const char *fstype,
1772 bool set_flags) {
1774 _cleanup_free_ char *e = NULL;
1775 MountProcFlags flags;
1776 Unit *u;
1777 int r;
1779 assert(m);
1780 assert(what);
1781 assert(where);
1782 assert(options);
1783 assert(fstype);
1785 /* Ignore API mount points. They should never be referenced in
1786 * dependencies ever. */
1787 if (mount_point_is_api(where) || mount_point_ignore(where))
1788 return 0;
1790 if (streq(fstype, "autofs"))
1791 return 0;
1793 /* probably some kind of swap, ignore */
1794 if (!is_path(where))
1795 return 0;
1797 r = unit_name_from_path(where, ".mount", &e);
1798 if (r < 0)
1799 return log_struct_errno(
1800 LOG_WARNING, r,
1801 "MESSAGE_ID=" SD_MESSAGE_MOUNT_POINT_PATH_NOT_SUITABLE_STR,
1802 "MOUNT_POINT=%s", where,
1803 LOG_MESSAGE("Failed to generate valid unit name from mount point path '%s', ignoring mount point: %m",
1804 where));
1806 u = manager_get_unit(m, e);
1807 if (u)
1808 r = mount_setup_existing_unit(u, what, where, options, fstype, &flags);
1809 else
1810 /* First time we see this mount point meaning that it's not been initiated by a mount unit
1811 * but rather by the sysadmin having called mount(8) directly. */
1812 r = mount_setup_new_unit(m, e, what, where, options, fstype, &flags, &u);
1813 if (r < 0)
1814 return log_warning_errno(r, "Failed to set up mount unit for '%s': %m", where);
1816 /* If the mount changed properties or state, let's notify our clients */
1817 if (flags & (MOUNT_PROC_JUST_CHANGED|MOUNT_PROC_JUST_MOUNTED))
1818 unit_add_to_dbus_queue(u);
1820 if (set_flags)
1821 MOUNT(u)->proc_flags = flags;
1823 return 0;
1826 static int mount_load_proc_self_mountinfo(Manager *m, bool set_flags) {
1827 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
1828 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
1829 int r;
1831 assert(m);
1833 r = libmount_parse(NULL, NULL, &table, &iter);
1834 if (r < 0)
1835 return log_error_errno(r, "Failed to parse /proc/self/mountinfo: %m");
1837 for (;;) {
1838 struct libmnt_fs *fs;
1839 const char *device, *path, *options, *fstype;
1841 r = mnt_table_next_fs(table, iter, &fs);
1842 if (r == 1)
1843 break;
1844 if (r < 0)
1845 return log_error_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
1847 device = mnt_fs_get_source(fs);
1848 path = mnt_fs_get_target(fs);
1849 options = mnt_fs_get_options(fs);
1850 fstype = mnt_fs_get_fstype(fs);
1852 if (!device || !path)
1853 continue;
1855 device_found_node(m, device, DEVICE_FOUND_MOUNT, DEVICE_FOUND_MOUNT);
1857 (void) mount_setup_unit(m, device, path, options, fstype, set_flags);
1860 return 0;
1863 static void mount_shutdown(Manager *m) {
1864 assert(m);
1866 m->mount_event_source = sd_event_source_disable_unref(m->mount_event_source);
1868 mnt_unref_monitor(m->mount_monitor);
1869 m->mount_monitor = NULL;
1872 static int mount_get_timeout(Unit *u, usec_t *timeout) {
1873 Mount *m = MOUNT(u);
1874 usec_t t;
1875 int r;
1877 assert(m);
1878 assert(u);
1880 if (!m->timer_event_source)
1881 return 0;
1883 r = sd_event_source_get_time(m->timer_event_source, &t);
1884 if (r < 0)
1885 return r;
1886 if (t == USEC_INFINITY)
1887 return 0;
1889 *timeout = t;
1890 return 1;
1893 static void mount_enumerate_perpetual(Manager *m) {
1894 Unit *u;
1895 int r;
1897 assert(m);
1899 /* Whatever happens, we know for sure that the root directory is around, and cannot go away. Let's
1900 * unconditionally synthesize it here and mark it as perpetual. */
1902 u = manager_get_unit(m, SPECIAL_ROOT_MOUNT);
1903 if (!u) {
1904 r = unit_new_for_name(m, sizeof(Mount), SPECIAL_ROOT_MOUNT, &u);
1905 if (r < 0) {
1906 log_error_errno(r, "Failed to allocate the special " SPECIAL_ROOT_MOUNT " unit: %m");
1907 return;
1911 u->perpetual = true;
1912 MOUNT(u)->deserialized_state = MOUNT_MOUNTED;
1914 unit_add_to_load_queue(u);
1915 unit_add_to_dbus_queue(u);
1918 static bool mount_is_mounted(Mount *m) {
1919 assert(m);
1921 return UNIT(m)->perpetual || FLAGS_SET(m->proc_flags, MOUNT_PROC_IS_MOUNTED);
1924 static int mount_on_ratelimit_expire(sd_event_source *s, void *userdata) {
1925 Manager *m = ASSERT_PTR(userdata);
1926 Job *j;
1928 /* Let's enqueue all start jobs that were previously skipped because of active ratelimit. */
1929 HASHMAP_FOREACH(j, m->jobs) {
1930 if (j->unit->type != UNIT_MOUNT)
1931 continue;
1933 job_add_to_run_queue(j);
1936 /* By entering ratelimited state we made all mount start jobs not runnable, now rate limit is over so
1937 * let's make sure we dispatch them in the next iteration. */
1938 manager_trigger_run_queue(m);
1940 return 0;
1943 static void mount_enumerate(Manager *m) {
1944 int r;
1946 assert(m);
1948 mnt_init_debug(0);
1950 if (!m->mount_monitor) {
1951 unsigned mount_rate_limit_burst = 5;
1952 int fd;
1954 m->mount_monitor = mnt_new_monitor();
1955 if (!m->mount_monitor) {
1956 log_oom();
1957 goto fail;
1960 r = mnt_monitor_enable_kernel(m->mount_monitor, 1);
1961 if (r < 0) {
1962 log_error_errno(r, "Failed to enable watching of kernel mount events: %m");
1963 goto fail;
1966 r = mnt_monitor_enable_userspace(m->mount_monitor, 1, NULL);
1967 if (r < 0) {
1968 log_error_errno(r, "Failed to enable watching of userspace mount events: %m");
1969 goto fail;
1972 /* mnt_unref_monitor() will close the fd */
1973 fd = r = mnt_monitor_get_fd(m->mount_monitor);
1974 if (r < 0) {
1975 log_error_errno(r, "Failed to acquire watch file descriptor: %m");
1976 goto fail;
1979 r = sd_event_add_io(m->event, &m->mount_event_source, fd, EPOLLIN, mount_dispatch_io, m);
1980 if (r < 0) {
1981 log_error_errno(r, "Failed to watch mount file descriptor: %m");
1982 goto fail;
1985 r = sd_event_source_set_priority(m->mount_event_source, SD_EVENT_PRIORITY_NORMAL-10);
1986 if (r < 0) {
1987 log_error_errno(r, "Failed to adjust mount watch priority: %m");
1988 goto fail;
1991 /* Let users override the default (5 in 1s), as it stalls the boot sequence on busy systems. */
1992 const char *e = secure_getenv("SYSTEMD_DEFAULT_MOUNT_RATE_LIMIT_BURST");
1993 if (e) {
1994 r = safe_atou(e, &mount_rate_limit_burst);
1995 if (r < 0)
1996 log_debug("Invalid value in $SYSTEMD_DEFAULT_MOUNT_RATE_LIMIT_BURST, ignoring: %s", e);
1999 r = sd_event_source_set_ratelimit(m->mount_event_source, 1 * USEC_PER_SEC, mount_rate_limit_burst);
2000 if (r < 0) {
2001 log_error_errno(r, "Failed to enable rate limit for mount events: %m");
2002 goto fail;
2005 r = sd_event_source_set_ratelimit_expire_callback(m->mount_event_source, mount_on_ratelimit_expire);
2006 if (r < 0) {
2007 log_error_errno(r, "Failed to enable rate limit for mount events: %m");
2008 goto fail;
2011 (void) sd_event_source_set_description(m->mount_event_source, "mount-monitor-dispatch");
2014 r = mount_load_proc_self_mountinfo(m, false);
2015 if (r < 0)
2016 goto fail;
2018 return;
2020 fail:
2021 mount_shutdown(m);
2024 static int drain_libmount(Manager *m) {
2025 bool rescan = false;
2026 int r;
2028 assert(m);
2030 /* Drain all events and verify that the event is valid.
2032 * Note that libmount also monitors /run/mount mkdir if the directory does not exist yet. The mkdir
2033 * may generate event which is irrelevant for us.
2035 * error: r < 0; valid: r == 0, false positive: r == 1 */
2036 do {
2037 r = mnt_monitor_next_change(m->mount_monitor, NULL, NULL);
2038 if (r < 0)
2039 return log_error_errno(r, "Failed to drain libmount events: %m");
2040 if (r == 0)
2041 rescan = true;
2042 } while (r == 0);
2044 return rescan;
2047 static int mount_process_proc_self_mountinfo(Manager *m) {
2048 _cleanup_set_free_ Set *around = NULL, *gone = NULL;
2049 const char *what;
2050 int r;
2052 assert(m);
2054 r = drain_libmount(m);
2055 if (r <= 0)
2056 return r;
2058 r = mount_load_proc_self_mountinfo(m, true);
2059 if (r < 0) {
2060 /* Reset flags, just in case, for later calls */
2061 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_MOUNT])
2062 MOUNT(u)->proc_flags = 0;
2064 return 0;
2067 manager_dispatch_load_queue(m);
2069 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_MOUNT]) {
2070 Mount *mount = MOUNT(u);
2072 if (!mount_is_mounted(mount)) {
2074 /* A mount point is not around right now. It might be gone, or might never have
2075 * existed. */
2077 if (mount->from_proc_self_mountinfo &&
2078 mount->parameters_proc_self_mountinfo.what)
2079 /* Remember that this device might just have disappeared */
2080 if (set_put_strdup_full(&gone, &path_hash_ops_free, mount->parameters_proc_self_mountinfo.what) < 0)
2081 log_oom(); /* we don't care too much about OOM here... */
2083 mount->from_proc_self_mountinfo = false;
2084 assert_se(update_parameters_proc_self_mountinfo(mount, NULL, NULL, NULL) >= 0);
2086 switch (mount->state) {
2088 case MOUNT_MOUNTED:
2089 /* This has just been unmounted by somebody else, follow the state change. */
2090 mount_enter_dead(mount, MOUNT_SUCCESS);
2091 break;
2093 case MOUNT_MOUNTING_DONE:
2094 /* The mount command may add the corresponding proc mountinfo entry and
2095 * then remove it because of an internal error. E.g., fuse.sshfs seems
2096 * to do that when the connection fails. See #17617. To handle such the
2097 * case, let's once set the state back to mounting. Then, the unit can
2098 * correctly enter the failed state later in mount_sigchld(). */
2099 mount_set_state(mount, MOUNT_MOUNTING);
2100 break;
2102 default:
2103 break;
2106 } else if (mount->proc_flags & (MOUNT_PROC_JUST_MOUNTED|MOUNT_PROC_JUST_CHANGED)) {
2108 /* A mount point was added or changed */
2110 switch (mount->state) {
2112 case MOUNT_DEAD:
2113 case MOUNT_FAILED:
2115 /* This has just been mounted by somebody else, follow the state change, but let's
2116 * generate a new invocation ID for this implicitly and automatically. */
2117 (void) unit_acquire_invocation_id(u);
2118 mount_cycle_clear(mount);
2119 mount_enter_mounted(mount, MOUNT_SUCCESS);
2120 break;
2122 case MOUNT_MOUNTING:
2123 mount_set_state(mount, MOUNT_MOUNTING_DONE);
2124 break;
2126 default:
2127 /* Nothing really changed, but let's issue an notification call nonetheless,
2128 * in case somebody is waiting for this. (e.g. file system ro/rw
2129 * remounts.) */
2130 mount_set_state(mount, mount->state);
2131 break;
2135 if (mount_is_mounted(mount) &&
2136 mount->from_proc_self_mountinfo &&
2137 mount->parameters_proc_self_mountinfo.what)
2138 /* Track devices currently used */
2139 if (set_put_strdup_full(&around, &path_hash_ops_free, mount->parameters_proc_self_mountinfo.what) < 0)
2140 log_oom();
2142 /* Reset the flags for later calls */
2143 mount->proc_flags = 0;
2146 SET_FOREACH(what, gone) {
2147 if (set_contains(around, what))
2148 continue;
2150 /* Let the device units know that the device is no longer mounted */
2151 device_found_node(m, what, DEVICE_NOT_FOUND, DEVICE_FOUND_MOUNT);
2154 return 0;
2157 static int mount_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2158 Manager *m = ASSERT_PTR(userdata);
2160 assert(revents & EPOLLIN);
2162 return mount_process_proc_self_mountinfo(m);
2165 static void mount_reset_failed(Unit *u) {
2166 Mount *m = MOUNT(u);
2168 assert(m);
2170 if (m->state == MOUNT_FAILED)
2171 mount_set_state(m, MOUNT_DEAD);
2173 m->result = MOUNT_SUCCESS;
2174 m->reload_result = MOUNT_SUCCESS;
2175 m->clean_result = MOUNT_SUCCESS;
2178 static int mount_kill(Unit *u, KillWho who, int signo, int code, int value, sd_bus_error *error) {
2179 Mount *m = MOUNT(u);
2181 assert(m);
2183 return unit_kill_common(u, who, signo, code, value, -1, m->control_pid, error);
2186 static int mount_control_pid(Unit *u) {
2187 Mount *m = MOUNT(u);
2189 assert(m);
2191 return m->control_pid;
2194 static int mount_clean(Unit *u, ExecCleanMask mask) {
2195 _cleanup_strv_free_ char **l = NULL;
2196 Mount *m = MOUNT(u);
2197 int r;
2199 assert(m);
2200 assert(mask != 0);
2202 if (m->state != MOUNT_DEAD)
2203 return -EBUSY;
2205 r = exec_context_get_clean_directories(&m->exec_context, u->manager->prefix, mask, &l);
2206 if (r < 0)
2207 return r;
2209 if (strv_isempty(l))
2210 return -EUNATCH;
2212 mount_unwatch_control_pid(m);
2213 m->clean_result = MOUNT_SUCCESS;
2214 m->control_command = NULL;
2215 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
2217 r = mount_arm_timer(m, usec_add(now(CLOCK_MONOTONIC), m->exec_context.timeout_clean_usec));
2218 if (r < 0)
2219 goto fail;
2221 r = unit_fork_and_watch_rm_rf(u, l, &m->control_pid);
2222 if (r < 0)
2223 goto fail;
2225 mount_set_state(m, MOUNT_CLEANING);
2227 return 0;
2229 fail:
2230 log_unit_warning_errno(u, r, "Failed to initiate cleaning: %m");
2231 m->clean_result = MOUNT_FAILURE_RESOURCES;
2232 m->timer_event_source = sd_event_source_disable_unref(m->timer_event_source);
2233 return r;
2236 static int mount_can_clean(Unit *u, ExecCleanMask *ret) {
2237 Mount *m = MOUNT(u);
2239 assert(m);
2241 return exec_context_get_clean_mask(&m->exec_context, ret);
2244 static int mount_can_start(Unit *u) {
2245 Mount *m = MOUNT(u);
2246 int r;
2248 assert(m);
2250 r = unit_test_start_limit(u);
2251 if (r < 0) {
2252 mount_enter_dead(m, MOUNT_FAILURE_START_LIMIT_HIT);
2253 return r;
2256 return 1;
2259 static int mount_subsystem_ratelimited(Manager *m) {
2260 assert(m);
2262 if (!m->mount_event_source)
2263 return false;
2265 return sd_event_source_is_ratelimited(m->mount_event_source);
2268 static const char* const mount_exec_command_table[_MOUNT_EXEC_COMMAND_MAX] = {
2269 [MOUNT_EXEC_MOUNT] = "ExecMount",
2270 [MOUNT_EXEC_UNMOUNT] = "ExecUnmount",
2271 [MOUNT_EXEC_REMOUNT] = "ExecRemount",
2274 DEFINE_STRING_TABLE_LOOKUP(mount_exec_command, MountExecCommand);
2276 static const char* const mount_result_table[_MOUNT_RESULT_MAX] = {
2277 [MOUNT_SUCCESS] = "success",
2278 [MOUNT_FAILURE_RESOURCES] = "resources",
2279 [MOUNT_FAILURE_TIMEOUT] = "timeout",
2280 [MOUNT_FAILURE_EXIT_CODE] = "exit-code",
2281 [MOUNT_FAILURE_SIGNAL] = "signal",
2282 [MOUNT_FAILURE_CORE_DUMP] = "core-dump",
2283 [MOUNT_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
2284 [MOUNT_FAILURE_PROTOCOL] = "protocol",
2287 DEFINE_STRING_TABLE_LOOKUP(mount_result, MountResult);
2289 const UnitVTable mount_vtable = {
2290 .object_size = sizeof(Mount),
2291 .exec_context_offset = offsetof(Mount, exec_context),
2292 .cgroup_context_offset = offsetof(Mount, cgroup_context),
2293 .kill_context_offset = offsetof(Mount, kill_context),
2294 .exec_runtime_offset = offsetof(Mount, exec_runtime),
2296 .sections =
2297 "Unit\0"
2298 "Mount\0"
2299 "Install\0",
2300 .private_section = "Mount",
2302 .can_transient = true,
2303 .can_fail = true,
2304 .exclude_from_switch_root_serialization = true,
2306 .init = mount_init,
2307 .load = mount_load,
2308 .done = mount_done,
2310 .coldplug = mount_coldplug,
2311 .catchup = mount_catchup,
2313 .dump = mount_dump,
2315 .start = mount_start,
2316 .stop = mount_stop,
2317 .reload = mount_reload,
2319 .kill = mount_kill,
2320 .clean = mount_clean,
2321 .can_clean = mount_can_clean,
2323 .serialize = mount_serialize,
2324 .deserialize_item = mount_deserialize_item,
2326 .active_state = mount_active_state,
2327 .sub_state_to_string = mount_sub_state_to_string,
2329 .will_restart = unit_will_restart_default,
2331 .may_gc = mount_may_gc,
2332 .is_extrinsic = mount_is_extrinsic,
2334 .sigchld_event = mount_sigchld_event,
2336 .reset_failed = mount_reset_failed,
2338 .control_pid = mount_control_pid,
2340 .bus_set_property = bus_mount_set_property,
2341 .bus_commit_properties = bus_mount_commit_properties,
2343 .get_timeout = mount_get_timeout,
2345 .enumerate_perpetual = mount_enumerate_perpetual,
2346 .enumerate = mount_enumerate,
2347 .shutdown = mount_shutdown,
2348 .subsystem_ratelimited = mount_subsystem_ratelimited,
2350 .status_message_formats = {
2351 .starting_stopping = {
2352 [0] = "Mounting %s...",
2353 [1] = "Unmounting %s...",
2355 .finished_start_job = {
2356 [JOB_DONE] = "Mounted %s.",
2357 [JOB_FAILED] = "Failed to mount %s.",
2358 [JOB_TIMEOUT] = "Timed out mounting %s.",
2360 .finished_stop_job = {
2361 [JOB_DONE] = "Unmounted %s.",
2362 [JOB_FAILED] = "Failed unmounting %s.",
2363 [JOB_TIMEOUT] = "Timed out unmounting %s.",
2367 .can_start = mount_can_start,
2369 .notify_plymouth = true,