Debian Codegraph @

src/core/mount.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <signal.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <sys/socket.h>
7
8 #include "sd-messages.h"
9
10 #include "alloc-util.h"
11 #include "chase.h"
12 #include "dbus-mount.h"
13 #include "dbus-unit.h"
14 #include "device.h"
15 #include "errno-util.h"
16 #include "exec-credential.h"
17 #include "exit-status.h"
18 #include "fd-util.h"
19 #include "format-util.h"
20 #include "fstab-util.h"
21 #include "glyph-util.h"
22 #include "initrd-util.h"
23 #include "libmount-util.h"
24 #include "log.h"
25 #include "manager.h"
26 #include "mkdir.h"
27 #include "mount-util.h"
28 #include "mount.h"
29 #include "mount-setup.h"
30 #include "mountpoint-util.h"
31 #include "parse-util.h"
32 #include "path-util.h"
33 #include "process-util.h"
34 #include "serialize.h"
35 #include "set.h"
36 #include "special.h"
37 #include "stat-util.h"
38 #include "string-table.h"
39 #include "string-util.h"
40 #include "strv.h"
41 #include "unit.h"
42 #include "unit-name.h"
43 #include "utf8.h"
44
45 #define RETRY_UMOUNT_MAX 32
46
47 static const UnitActiveState state_translation_table[_MOUNT_STATE_MAX] = {
48 [MOUNT_DEAD] = UNIT_INACTIVE,
49 [MOUNT_MOUNTING] = UNIT_ACTIVATING,
50 [MOUNT_MOUNTING_DONE] = UNIT_ACTIVATING,
51 [MOUNT_MOUNTED] = UNIT_ACTIVE,
52 [MOUNT_REMOUNTING] = UNIT_RELOADING,
53 [MOUNT_REMOUNTING_SIGTERM] = UNIT_RELOADING,
54 [MOUNT_REMOUNTING_SIGKILL] = UNIT_RELOADING,
55 [MOUNT_UNMOUNTING] = UNIT_DEACTIVATING,
56 [MOUNT_UNMOUNTING_SIGTERM] = UNIT_DEACTIVATING,
57 [MOUNT_UNMOUNTING_SIGKILL] = UNIT_DEACTIVATING,
58 [MOUNT_FAILED] = UNIT_FAILED,
59 [MOUNT_CLEANING] = UNIT_MAINTENANCE,
60 };
61
62 static int mount_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
63 #if HAVE_LIBMOUNT
64 static int mount_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
65 #endif
66 static void mount_enter_dead(Mount *m, MountResult f, bool flush_result);
67 static void mount_enter_mounted(Mount *m, MountResult f);
68 static void mount_cycle_clear(Mount *m);
69 static int mount_process_proc_self_mountinfo(Manager *m);
70
71 static bool MOUNT_STATE_WITH_PROCESS(MountState state) {
72 return IN_SET(state,
73 MOUNT_MOUNTING,
74 MOUNT_MOUNTING_DONE,
75 MOUNT_REMOUNTING,
76 MOUNT_REMOUNTING_SIGTERM,
77 MOUNT_REMOUNTING_SIGKILL,
78 MOUNT_UNMOUNTING,
79 MOUNT_UNMOUNTING_SIGTERM,
80 MOUNT_UNMOUNTING_SIGKILL,
81 MOUNT_CLEANING);
82 }
83
84 static MountParameters* get_mount_parameters_fragment(Mount *m) {
85 assert(m);
86
87 if (m->from_fragment)
88 return &m->parameters_fragment;
89
90 return NULL;
91 }
92
93 static MountParameters* get_mount_parameters(Mount *m) {
94 assert(m);
95
96 if (m->from_proc_self_mountinfo)
97 return &m->parameters_proc_self_mountinfo;
98
99 return get_mount_parameters_fragment(m);
100 }
101
102 static bool mount_is_network(const MountParameters *p) {
103 assert(p);
104
105 if (fstab_test_option(p->options, "_netdev\0"))
106 return true;
107
108 if (p->fstype && fstype_is_network(p->fstype))
109 return true;
110
111 return false;
112 }
113
114 static bool mount_is_nofail(const Mount *m) {
115 assert(m);
116
117 if (!m->from_fragment)
118 return false;
119
120 return fstab_test_yes_no_option(m->parameters_fragment.options, "nofail\0" "fail\0");
121 }
122
123 static bool mount_is_loop(const MountParameters *p) {
124 assert(p);
125
126 if (fstab_test_option(p->options, "loop\0"))
127 return true;
128
129 return false;
130 }
131
132 static bool mount_is_bind(const MountParameters *p) {
133 assert(p);
134 return fstab_is_bind(p->options, p->fstype);
135 }
136
137 static int mount_is_bound_to_device(Mount *m) {
138 _cleanup_free_ char *value = NULL;
139 const MountParameters *p;
140 int r;
141
142 assert(m);
143
144 /* Determines whether to place a Requires= or BindsTo= dependency on the backing device unit. We do
145 * this by checking for the x-systemd.device-bound= mount option. If it is enabled we use BindsTo=,
146 * otherwise Requires=. But note that we might combine the latter with StopPropagatedFrom=, see
147 * below. */
148
149 p = get_mount_parameters(m);
150 if (!p)
151 return false;
152
153 r = fstab_filter_options(p->options, "x-systemd.device-bound\0", NULL, &value, NULL, NULL);
154 if (r < 0)
155 return r;
156 if (r == 0)
157 return -EIDRM; /* If unspecified at all, return recognizable error */
158
159 if (isempty(value))
160 return true;
161
162 return parse_boolean(value);
163 }
164
165 static bool mount_propagate_stop(Mount *m) {
166 int r;
167
168 assert(m);
169
170 r = mount_is_bound_to_device(m);
171 if (r >= 0)
172 /* If x-systemd.device-bound=no is explicitly requested by user, don't try to set StopPropagatedFrom=.
173 * Also don't bother if true, since with BindsTo= the stop propagation is implicit. */
174 return false;
175 if (r != -EIDRM)
176 log_debug_errno(r, "Failed to get x-systemd.device-bound= option, ignoring: %m");
177
178 return m->from_fragment; /* let's propagate stop whenever this is an explicitly configured unit,
179 * otherwise let's not bother. */
180 }
181
182 static void mount_init(Unit *u) {
183 Mount *m = ASSERT_PTR(MOUNT(u));
184
185 assert(u->load_state == UNIT_STUB);
186
187 m->timeout_usec = u->manager->defaults.timeout_start_usec;
188
189 m->exec_context.std_output = u->manager->defaults.std_output;
190 m->exec_context.std_error = u->manager->defaults.std_error;
191
192 m->directory_mode = 0755;
193
194 /* We need to make sure that /usr/bin/mount is always called
195 * in the same process group as us, so that the autofs kernel
196 * side doesn't send us another mount request while we are
197 * already trying to comply its last one. */
198 m->exec_context.same_pgrp = true;
199
200 m->control_pid = PIDREF_NULL;
201 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
202
203 u->ignore_on_isolate = true;
204 }
205
206 static int mount_arm_timer(Mount *m, bool relative, usec_t usec) {
207 assert(m);
208
209 return unit_arm_timer(UNIT(m), &m->timer_event_source, relative, usec, mount_dispatch_timer);
210 }
211
212 static void mount_unwatch_control_pid(Mount *m) {
213 assert(m);
214 unit_unwatch_pidref_done(UNIT(m), &m->control_pid);
215 }
216
217 static void mount_parameters_done(MountParameters *p) {
218 assert(p);
219
220 p->what = mfree(p->what);
221 p->options = mfree(p->options);
222 p->fstype = mfree(p->fstype);
223 }
224
225 static void mount_done(Unit *u) {
226 Mount *m = ASSERT_PTR(MOUNT(u));
227
228 m->where = mfree(m->where);
229
230 mount_parameters_done(&m->parameters_proc_self_mountinfo);
231 mount_parameters_done(&m->parameters_fragment);
232
233 m->exec_runtime = exec_runtime_free(m->exec_runtime);
234
235 exec_command_done_array(m->exec_command, _MOUNT_EXEC_COMMAND_MAX);
236 m->control_command = NULL;
237
238 mount_unwatch_control_pid(m);
239
240 m->timer_event_source = sd_event_source_disable_unref(m->timer_event_source);
241 }
242
243 static int mount_add_mount_dependencies(Mount *m) {
244 MountParameters *pm;
245 int r;
246
247 assert(m);
248
249 if (!path_equal(m->where, "/")) {
250 _cleanup_free_ char *parent = NULL;
251
252 /* Adds in links to other mount points that might lie further up in the hierarchy */
253
254 r = path_extract_directory(m->where, &parent);
255 if (r < 0)
256 return r;
257
258 r = unit_add_mounts_for(UNIT(m), parent, UNIT_DEPENDENCY_IMPLICIT, UNIT_MOUNT_REQUIRES);
259 if (r < 0)
260 return r;
261 }
262
263 /* Adds in dependencies to other mount points that might be needed for the source path (if this is a bind mount
264 * or a loop mount) to be available. */
265 pm = get_mount_parameters_fragment(m);
266 if (pm && pm->what &&
267 path_is_absolute(pm->what) &&
268 (mount_is_bind(pm) || mount_is_loop(pm) || !mount_is_network(pm))) {
269
270 r = unit_add_mounts_for(UNIT(m), pm->what, UNIT_DEPENDENCY_FILE, UNIT_MOUNT_REQUIRES);
271 if (r < 0)
272 return r;
273 }
274
275 /* Adds in dependencies to other units that use this path or paths further down in the hierarchy */
276 for (UnitMountDependencyType t = 0; t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX; ++t) {
277 Unit *other;
278 Set *s = manager_get_units_needing_mounts_for(UNIT(m)->manager, m->where, t);
279
280 SET_FOREACH(other, s) {
281 if (other->load_state != UNIT_LOADED)
282 continue;
283
284 if (other == UNIT(m))
285 continue;
286
287 r = unit_add_dependency(
288 other,
289 UNIT_AFTER,
290 UNIT(m),
291 /* add_reference= */ true,
292 UNIT_DEPENDENCY_PATH);
293 if (r < 0)
294 return r;
295
296 if (UNIT(m)->fragment_path) {
297 /* If we have fragment configuration, then make this dependency required/wanted */
298 r = unit_add_dependency(
299 other,
300 unit_mount_dependency_type_to_dependency_type(t),
301 UNIT(m),
302 /* add_reference= */ true,
303 UNIT_DEPENDENCY_PATH);
304 if (r < 0)
305 return r;
306 }
307 }
308 }
309
310 return 0;
311 }
312
313 static int mount_add_device_dependencies(Mount *m) {
314 UnitDependencyMask mask;
315 MountParameters *p;
316 UnitDependency dep;
317 int r;
318
319 assert(m);
320
321 log_unit_trace(UNIT(m), "Processing implicit device dependencies");
322
323 p = get_mount_parameters(m);
324 if (!p) {
325 log_unit_trace(UNIT(m), "Missing mount parameters, skipping implicit device dependencies");
326 return 0;
327 }
328
329 if (!p->what) {
330 log_unit_trace(UNIT(m), "Missing mount source, skipping implicit device dependencies");
331 return 0;
332 }
333
334 if (mount_is_bind(p)) {
335 log_unit_trace(UNIT(m), "Mount unit is a bind mount, skipping implicit device dependencies");
336 return 0;
337 }
338
339 if (!is_device_path(p->what)) {
340 log_unit_trace(UNIT(m), "Mount source is not a device path, skipping implicit device dependencies");
341 return 0;
342 }
343
344 /* /dev/root is a really weird thing, it's not a real device, but just a path the kernel exports for
345 * the root file system specified on the kernel command line. Ignore it here. */
346 if (PATH_IN_SET(p->what, "/dev/root", "/dev/nfs")) {
347 log_unit_trace(UNIT(m), "Mount source is in /dev/root or /dev/nfs, skipping implicit device dependencies");
348 return 0;
349 }
350
351 if (path_equal(m->where, "/")) {
352 log_unit_trace(UNIT(m), "Mount destination is '/', skipping implicit device dependencies");
353 return 0;
354 }
355
356 /* Mount units from /proc/self/mountinfo are not bound to devices by default since they're subject to
357 * races when mounts are established by other tools with different backing devices than what we
358 * maintain. The user can still force this to be a BindsTo= dependency with an appropriate option (or
359 * udev property) so the mount units are automatically stopped when the device disappears
360 * suddenly. */
361 dep = mount_is_bound_to_device(m) > 0 ? UNIT_BINDS_TO : UNIT_REQUIRES;
362
363 /* We always use 'what' from /proc/self/mountinfo if mounted */
364 mask = m->from_proc_self_mountinfo ? UNIT_DEPENDENCY_MOUNTINFO : UNIT_DEPENDENCY_MOUNT_FILE;
365
366 r = unit_add_node_dependency(UNIT(m), p->what, dep, mask);
367 if (r < 0)
368 return r;
369 if (r > 0)
370 log_unit_trace(UNIT(m), "Added %s dependency on %s", unit_dependency_to_string(dep), p->what);
371
372 if (mount_propagate_stop(m)) {
373 r = unit_add_node_dependency(UNIT(m), p->what, UNIT_STOP_PROPAGATED_FROM, mask);
374 if (r < 0)
375 return r;
376 if (r > 0)
377 log_unit_trace(UNIT(m), "Added %s dependency on %s",
378 unit_dependency_to_string(UNIT_STOP_PROPAGATED_FROM), p->what);
379 }
380
381 r = unit_add_blockdev_dependency(UNIT(m), p->what, mask);
382 if (r > 0)
383 log_unit_trace(UNIT(m), "Added %s dependency on %s", unit_dependency_to_string(UNIT_AFTER), p->what);
384
385 return 0;
386 }
387
388 static bool mount_is_extrinsic(Unit *u) {
389 Mount *m = ASSERT_PTR(MOUNT(u));
390 MountParameters *p;
391
392 /* Returns true for all units that are "magic" and should be excluded from the usual
393 * start-up and shutdown dependencies. We call them "extrinsic" here, as they are generally
394 * mounted outside of the systemd dependency logic. We shouldn't attempt to manage them
395 * ourselves but it's fine if the user operates on them with us. */
396
397 /* We only automatically manage mounts if we are in system mode */
398 if (MANAGER_IS_USER(u->manager))
399 return true;
400
401 p = get_mount_parameters(m);
402 if (p && fstab_is_extrinsic(m->where, p->options))
403 return true;
404
405 return false;
406 }
407
408 static int mount_add_default_ordering_dependencies(Mount *m, MountParameters *p, UnitDependencyMask mask) {
409 const char *after, *before, *e;
410 int r;
411
412 assert(m);
413
414 e = path_startswith(m->where, "/sysroot");
415 if (e && in_initrd()) {
416 /* All mounts under /sysroot need to happen later, at initrd-fs.target time. IOW,
417 * it's not technically part of the basic initrd filesystem itself, and so
418 * shouldn't inherit the default Before=local-fs.target dependency. However,
419 * these mounts still need to start after local-fs-pre.target, as a sync point
420 * for things like systemd-hibernate-resume.service that should start before
421 * any mounts. */
422
423 after = SPECIAL_LOCAL_FS_PRE_TARGET;
424 before = isempty(e) ? SPECIAL_INITRD_ROOT_FS_TARGET : SPECIAL_INITRD_FS_TARGET;
425
426 } else if (in_initrd() && path_startswith(m->where, "/sysusr/usr")) {
427 after = SPECIAL_LOCAL_FS_PRE_TARGET;
428 before = SPECIAL_INITRD_USR_FS_TARGET;
429
430 } else if (mount_is_network(p)) {
431 after = SPECIAL_REMOTE_FS_PRE_TARGET;
432 before = SPECIAL_REMOTE_FS_TARGET;
433
434 } else {
435 after = SPECIAL_LOCAL_FS_PRE_TARGET;
436 before = SPECIAL_LOCAL_FS_TARGET;
437 }
438
439 if (before && !mount_is_nofail(m)) {
440 r = unit_add_dependency_by_name(UNIT(m), UNIT_BEFORE, before, /* add_reference= */ true, mask);
441 if (r < 0)
442 return r;
443 }
444
445 if (after) {
446 r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, after, /* add_reference= */ true, mask);
447 if (r < 0)
448 return r;
449 }
450
451 r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET,
452 /* add_reference= */ true, mask);
453 if (r < 0)
454 return r;
455
456 /* If this is a tmpfs mount then we have to unmount it before we try to deactivate swaps */
457 if (streq_ptr(p->fstype, "tmpfs")) {
458 r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, SPECIAL_SWAP_TARGET,
459 /* add_reference= */ true, mask);
460 if (r < 0)
461 return r;
462 }
463
464 return 0;
465 }
466
467 static int mount_add_default_network_dependencies(Mount *m, MountParameters *p, UnitDependencyMask mask) {
468 int r;
469
470 assert(m);
471
472 if (!mount_is_network(p))
473 return 0;
474
475 /* We order ourselves after network.target. This is primarily useful at shutdown: services that take
476 * down the network should order themselves before network.target, so that they are shut down only
477 * after this mount unit is stopped. */
478
479 r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, SPECIAL_NETWORK_TARGET,
480 /* add_reference= */ true, mask);
481 if (r < 0)
482 return r;
483
484 /* We pull in network-online.target, and order ourselves after it. This is useful at start-up to
485 * actively pull in tools that want to be started before we start mounting network file systems, and
486 * whose purpose it is to delay this until the network is "up". */
487
488 return unit_add_two_dependencies_by_name(UNIT(m), UNIT_WANTS, UNIT_AFTER, SPECIAL_NETWORK_ONLINE_TARGET,
489 /* add_reference= */ true, mask);
490 }
491
492 static int mount_add_default_dependencies(Mount *m) {
493 UnitDependencyMask mask;
494 MountParameters *p;
495 int r;
496
497 assert(m);
498
499 if (!UNIT(m)->default_dependencies)
500 return 0;
501
502 /* We do not add any default dependencies to /, /usr or /run/initramfs/, since they are
503 * guaranteed to stay mounted the whole time, since our system is on it. Also, don't
504 * bother with anything mounted below virtual file systems, it's also going to be virtual,
505 * and hence not worth the effort. */
506 if (mount_is_extrinsic(UNIT(m)))
507 return 0;
508
509 p = get_mount_parameters(m);
510 if (!p)
511 return 0;
512
513 mask = m->from_proc_self_mountinfo ? UNIT_DEPENDENCY_MOUNTINFO : UNIT_DEPENDENCY_MOUNT_FILE;
514
515 r = mount_add_default_ordering_dependencies(m, p, mask);
516 if (r < 0)
517 return r;
518
519 r = mount_add_default_network_dependencies(m, p, mask);
520 if (r < 0)
521 return r;
522
523 return 0;
524 }
525
526 static int mount_verify(Mount *m) {
527 _cleanup_free_ char *e = NULL;
528 MountParameters *p;
529 int r;
530
531 assert(m);
532 assert(UNIT(m)->load_state == UNIT_LOADED);
533
534 if (!m->from_fragment && !m->from_proc_self_mountinfo && !UNIT(m)->perpetual)
535 return -ENOENT;
536
537 r = unit_name_from_path(m->where, ".mount", &e);
538 if (r < 0)
539 return log_unit_error_errno(UNIT(m), r, "Failed to generate unit name from mount path: %m");
540
541 if (!unit_has_name(UNIT(m), e))
542 return log_unit_error_errno(UNIT(m), SYNTHETIC_ERRNO(ENOEXEC), "Where= setting doesn't match unit name. Refusing.");
543
544 if (mount_point_is_api(m->where) || mount_point_ignore(m->where))
545 return log_unit_error_errno(UNIT(m), SYNTHETIC_ERRNO(ENOEXEC),
546 "Cannot create mount unit for API file system '%s'. Refusing.", m->where);
547
548 if (mount_point_is_credentials(UNIT(m)->manager->prefix[EXEC_DIRECTORY_RUNTIME], m->where))
549 return log_unit_error_errno(UNIT(m), SYNTHETIC_ERRNO(ENOEXEC),
550 "Cannot create mount unit for credential mount '%s'. Refusing.", m->where);
551
552 p = get_mount_parameters_fragment(m);
553 if (p && !p->what && !UNIT(m)->perpetual)
554 return log_unit_error_errno(UNIT(m), SYNTHETIC_ERRNO(ENOEXEC), "What= setting is missing. Refusing.");
555
556 return 0;
557 }
558
559 static int mount_add_non_exec_dependencies(Mount *m) {
560 int r;
561
562 assert(m);
563
564 /* We may be called due to this mount appearing in /proc/self/mountinfo, hence we clear all existing
565 * dependencies that were initialized from the unit file but whose final value really depends on the
566 * content of /proc/self/mountinfo. Some (such as m->where) might have become stale now. */
567 unit_remove_dependencies(UNIT(m), UNIT_DEPENDENCY_MOUNTINFO | UNIT_DEPENDENCY_MOUNT_FILE);
568
569 if (!m->where)
570 return 0;
571
572 /* Adds in all dependencies directly responsible for ordering the mount, as opposed to dependencies
573 * resulting from the ExecContext and such. */
574
575 r = mount_add_device_dependencies(m);
576 if (r < 0)
577 return r;
578
579 r = mount_add_mount_dependencies(m);
580 if (r < 0)
581 return r;
582
583 r = mount_add_default_dependencies(m);
584 if (r < 0)
585 return r;
586
587 return 0;
588 }
589
590 static int mount_add_extras(Mount *m) {
591 Unit *u = UNIT(ASSERT_PTR(m));
592 int r;
593
594 /* Note: this call might be called after we already have been loaded once (and even when it has already been
595 * activated), in case data from /proc/self/mountinfo has changed. This means all code here needs to be ready
596 * to run with an already set up unit. */
597
598 if (u->fragment_path)
599 m->from_fragment = true;
600
601 if (!m->where) {
602 r = unit_name_to_path(u->id, &m->where);
603 if (r == -ENAMETOOLONG)
604 log_unit_error_errno(u, r, "Failed to derive mount point path from unit name, because unit name is hashed. "
605 "Set \"Where=\" in the unit file explicitly.");
606 if (r < 0)
607 return r;
608 }
609
610 path_simplify(m->where);
611
612 if (!u->description) {
613 _cleanup_free_ char *w = mount_get_where_escaped(m);
614 if (!w)
615 return log_oom();
616
617 r = unit_set_description(u, w);
618 if (r < 0)
619 return r;
620 }
621
622 r = unit_patch_contexts(u);
623 if (r < 0)
624 return r;
625
626 r = unit_add_exec_dependencies(u, &m->exec_context);
627 if (r < 0)
628 return r;
629
630 r = unit_set_default_slice(u);
631 if (r < 0)
632 return r;
633
634 r = mount_add_non_exec_dependencies(m);
635 if (r < 0)
636 return r;
637
638 return 0;
639 }
640
641 static void mount_load_root_mount(Unit *u) {
642 Mount *m = ASSERT_PTR(MOUNT(u));
643
644 if (!unit_has_name(u, SPECIAL_ROOT_MOUNT))
645 return;
646
647 u->perpetual = true;
648 u->default_dependencies = false;
649
650 /* The stdio/kmsg bridge socket is on /, in order to avoid a dep loop, don't use kmsg logging for -.mount */
651 m->exec_context.std_output = EXEC_OUTPUT_NULL;
652 m->exec_context.std_input = EXEC_INPUT_NULL;
653
654 if (!u->description)
655 u->description = strdup("Root Mount");
656 }
657
658 static int mount_load(Unit *u) {
659 Mount *m = ASSERT_PTR(MOUNT(u));
660 int r;
661
662 assert(u->load_state == UNIT_STUB);
663
664 mount_load_root_mount(u);
665
666 bool from_kernel = m->from_proc_self_mountinfo || u->perpetual;
667
668 r = unit_load_fragment_and_dropin(u, /* fragment_required= */ !from_kernel);
669
670 /* Add in some extras. Note we do this in all cases (even if we failed to load the unit) when announced by the
671 * kernel, because we need some things to be set up no matter what when the kernel establishes a mount and thus
672 * we need to update the state in our unit to track it. After all, consider that we don't allow changing the
673 * 'slice' field for a unit once it is active. */
674 if (u->load_state == UNIT_LOADED || from_kernel)
675 RET_GATHER(r, mount_add_extras(m));
676
677 if (r < 0)
678 return r;
679
680 if (u->load_state != UNIT_LOADED)
681 return 0;
682
683 return mount_verify(m);
684 }
685
686 static void mount_set_state(Mount *m, MountState state) {
687 MountState old_state;
688
689 assert(m);
690
691 if (m->state != state)
692 bus_unit_send_pending_change_signal(UNIT(m), false);
693
694 old_state = m->state;
695 m->state = state;
696
697 if (!MOUNT_STATE_WITH_PROCESS(state)) {
698 m->timer_event_source = sd_event_source_disable_unref(m->timer_event_source);
699 mount_unwatch_control_pid(m);
700 m->control_command = NULL;
701 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
702 }
703
704 if (state != old_state)
705 log_unit_debug(UNIT(m), "Changed %s -> %s", mount_state_to_string(old_state), mount_state_to_string(state));
706
707 unit_notify(UNIT(m), state_translation_table[old_state], state_translation_table[state], m->reload_result == MOUNT_SUCCESS);
708 }
709
710 static int mount_coldplug(Unit *u) {
711 Mount *m = ASSERT_PTR(MOUNT(u));
712 int r;
713
714 assert(m->state == MOUNT_DEAD);
715
716 if (m->deserialized_state == m->state)
717 return 0;
718
719 if (pidref_is_set(&m->control_pid) &&
720 pidref_is_unwaited(&m->control_pid) > 0 &&
721 MOUNT_STATE_WITH_PROCESS(m->deserialized_state)) {
722
723 r = unit_watch_pidref(UNIT(m), &m->control_pid, /* exclusive= */ false);
724 if (r < 0)
725 return r;
726
727 r = mount_arm_timer(m, /* relative= */ false, usec_add(u->state_change_timestamp.monotonic, m->timeout_usec));
728 if (r < 0)
729 return r;
730 }
731
732 if (!IN_SET(m->deserialized_state, MOUNT_DEAD, MOUNT_FAILED))
733 (void) unit_setup_exec_runtime(u);
734
735 mount_set_state(m, m->deserialized_state);
736 return 0;
737 }
738
739 static void mount_catchup(Unit *u) {
740 Mount *m = ASSERT_PTR(MOUNT(u));
741
742 /* Adjust the deserialized state. See comments in mount_process_proc_self_mountinfo(). */
743 if (m->from_proc_self_mountinfo)
744 switch (m->state) {
745 case MOUNT_DEAD:
746 case MOUNT_FAILED:
747 assert(!pidref_is_set(&m->control_pid));
748 (void) unit_acquire_invocation_id(u);
749 mount_cycle_clear(m);
750 mount_enter_mounted(m, MOUNT_SUCCESS);
751 break;
752 case MOUNT_MOUNTING:
753 assert(pidref_is_set(&m->control_pid));
754 mount_set_state(m, MOUNT_MOUNTING_DONE);
755 break;
756 default:
757 ;
758 }
759 else
760 switch (m->state) {
761 case MOUNT_MOUNTING_DONE:
762 assert(pidref_is_set(&m->control_pid));
763 mount_set_state(m, MOUNT_MOUNTING);
764 break;
765 case MOUNT_MOUNTED:
766 assert(!pidref_is_set(&m->control_pid));
767 mount_enter_dead(m, MOUNT_SUCCESS, /* flush_result= */ false);
768 break;
769 default:
770 ;
771 }
772 }
773
774 static void mount_dump(Unit *u, FILE *f, const char *prefix) {
775 Mount *m = ASSERT_PTR(MOUNT(u));
776 MountParameters *p;
777 const char *prefix2;
778
779 assert(f);
780
781 prefix = strempty(prefix);
782 prefix2 = strjoina(prefix, "\t");
783
784 p = get_mount_parameters(m);
785
786 fprintf(f,
787 "%sMount State: %s\n"
788 "%sResult: %s\n"
789 "%sClean Result: %s\n"
790 "%sWhere: %s\n"
791 "%sWhat: %s\n"
792 "%sFile System Type: %s\n"
793 "%sOptions: %s\n"
794 "%sFrom /proc/self/mountinfo: %s\n"
795 "%sFrom fragment: %s\n"
796 "%sExtrinsic: %s\n"
797 "%sDirectoryMode: %04o\n"
798 "%sSloppyOptions: %s\n"
799 "%sLazyUnmount: %s\n"
800 "%sForceUnmount: %s\n"
801 "%sReadWriteOnly: %s\n"
802 "%sTimeoutSec: %s\n",
803 prefix, mount_state_to_string(m->state),
804 prefix, mount_result_to_string(m->result),
805 prefix, mount_result_to_string(m->clean_result),
806 prefix, m->where,
807 prefix, p ? strna(p->what) : "n/a",
808 prefix, p ? strna(p->fstype) : "n/a",
809 prefix, p ? strna(p->options) : "n/a",
810 prefix, yes_no(m->from_proc_self_mountinfo),
811 prefix, yes_no(m->from_fragment),
812 prefix, yes_no(mount_is_extrinsic(u)),
813 prefix, m->directory_mode,
814 prefix, yes_no(m->sloppy_options),
815 prefix, yes_no(m->lazy_unmount),
816 prefix, yes_no(m->force_unmount),
817 prefix, yes_no(m->read_write_only),
818 prefix, FORMAT_TIMESPAN(m->timeout_usec, USEC_PER_SEC));
819
820 if (pidref_is_set(&m->control_pid))
821 fprintf(f,
822 "%sControl PID: "PID_FMT"\n",
823 prefix, m->control_pid.pid);
824
825 exec_context_dump(&m->exec_context, f, prefix);
826 kill_context_dump(&m->kill_context, f, prefix);
827 cgroup_context_dump(UNIT(m), f, prefix);
828
829 for (MountExecCommand c = 0; c < _MOUNT_EXEC_COMMAND_MAX; c++) {
830 if (!m->exec_command[c].argv)
831 continue;
832
833 fprintf(f, "%s%s %s:\n",
834 prefix, glyph(GLYPH_ARROW_RIGHT), mount_exec_command_to_string(c));
835
836 exec_command_dump(m->exec_command + c, f, prefix2);
837 }
838 }
839
840 static ExecFlags mount_exec_flags(MountState state) {
841 ExecFlags flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN;
842
843 assert(IN_SET(state, MOUNT_MOUNTING, MOUNT_REMOUNTING, MOUNT_UNMOUNTING));
844
845 if (IN_SET(state, MOUNT_MOUNTING, MOUNT_REMOUNTING))
846 flags |= EXEC_SETUP_CREDENTIALS;
847
848 return flags;
849 }
850
851 static int mount_spawn(Mount *m, ExecCommand *c, ExecFlags flags, PidRef *ret_pid) {
852 _cleanup_(exec_params_shallow_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(flags);
853 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
854 int r;
855
856 assert(m);
857 assert(c);
858 assert(ret_pid);
859
860 r = unit_prepare_exec(UNIT(m));
861 if (r < 0)
862 return r;
863
864 r = mount_arm_timer(m, /* relative= */ true, m->timeout_usec);
865 if (r < 0)
866 return r;
867
868 r = unit_set_exec_params(UNIT(m), &exec_params);
869 if (r < 0)
870 return r;
871
872 /* Assume the label inherited from systemd as the fallback */
873 exec_params.fallback_smack_process_label = NULL;
874
875 r = exec_spawn(UNIT(m),
876 c,
877 &m->exec_context,
878 &exec_params,
879 m->exec_runtime,
880 &m->cgroup_context,
881 &pidref);
882 if (r < 0)
883 return r;
884
885 r = unit_watch_pidref(UNIT(m), &pidref, /* exclusive= */ true);
886 if (r < 0)
887 return r;
888
889 *ret_pid = TAKE_PIDREF(pidref);
890 return 0;
891 }
892
893 static void mount_enter_dead(Mount *m, MountResult f, bool flush_result) {
894 assert(m);
895
896 if (m->result == MOUNT_SUCCESS || f == MOUNT_FAILURE_START_LIMIT_HIT || flush_result)
897 m->result = f;
898
899 unit_log_result(UNIT(m), m->result == MOUNT_SUCCESS, mount_result_to_string(m->result));
900 unit_warn_leftover_processes(UNIT(m), /* start= */ false);
901
902 mount_set_state(m, m->result != MOUNT_SUCCESS ? MOUNT_FAILED : MOUNT_DEAD);
903
904 m->exec_runtime = exec_runtime_destroy(m->exec_runtime);
905
906 unit_destroy_runtime_data(UNIT(m), &m->exec_context, /* destroy_runtime_dir= */ true);
907
908 unit_unref_uid_gid(UNIT(m), true);
909
910 /* Any dependencies based on /proc/self/mountinfo are now stale. Let's re-generate dependencies from
911 * .mount unit. */
912 (void) mount_add_non_exec_dependencies(m);
913 }
914
915 static void mount_enter_mounted(Mount *m, MountResult f) {
916 assert(m);
917
918 if (m->result == MOUNT_SUCCESS)
919 m->result = f;
920
921 /* Refer to service_set_state() handling of SERVICE_EXITED state for rationale. In particular
922 * for mount units let's not leave cred mounts around, otherwise the actual number of mounts would be
923 * somewhat doubled.
924 *
925 * Note that this effectively means fresh creds are used during remount, but that's mostly what
926 * users would expect anyways. */
927 unit_destroy_runtime_data(UNIT(m), &m->exec_context, /* destroy_runtime_dir= */ false);
928
929 mount_set_state(m, MOUNT_MOUNTED);
930 }
931
932 static void mount_enter_dead_or_mounted(Mount *m, MountResult f, bool flush_result) {
933 assert(m);
934
935 /* Enter DEAD or MOUNTED state, depending on what the kernel currently says about the mount point.
936 * We use this whenever we executed an operation, so that our internal state reflects what
937 * the kernel says again, after all ultimately we just mirror the kernel's internal state on this.
938 *
939 * Note that flush_result only applies to mount_enter_dead(), since that's when the result gets
940 * turned into unit end state. */
941
942 if (m->from_proc_self_mountinfo)
943 mount_enter_mounted(m, f);
944 else
945 mount_enter_dead(m, f, flush_result);
946 }
947
948 static int state_to_kill_operation(MountState state) {
949 switch (state) {
950
951 case MOUNT_REMOUNTING_SIGTERM:
952 return KILL_RESTART;
953
954 case MOUNT_UNMOUNTING_SIGTERM:
955 return KILL_TERMINATE;
956
957 case MOUNT_REMOUNTING_SIGKILL:
958 case MOUNT_UNMOUNTING_SIGKILL:
959 return KILL_KILL;
960
961 default:
962 return _KILL_OPERATION_INVALID;
963 }
964 }
965
966 static void mount_enter_signal(Mount *m, MountState state, MountResult f) {
967 int r;
968
969 assert(m);
970
971 if (m->result == MOUNT_SUCCESS)
972 m->result = f;
973
974 r = unit_kill_context(UNIT(m), state_to_kill_operation(state));
975 if (r < 0) {
976 log_unit_warning_errno(UNIT(m), r, "Failed to kill processes: %m");
977 goto fail;
978 }
979
980 if (r > 0) {
981 r = mount_arm_timer(m, /* relative= */ true, m->timeout_usec);
982 if (r < 0) {
983 log_unit_warning_errno(UNIT(m), r, "Failed to install timer: %m");
984 goto fail;
985 }
986
987 mount_set_state(m, state);
988 } else if (state == MOUNT_REMOUNTING_SIGTERM && m->kill_context.send_sigkill)
989 mount_enter_signal(m, MOUNT_REMOUNTING_SIGKILL, MOUNT_SUCCESS);
990 else if (IN_SET(state, MOUNT_REMOUNTING_SIGTERM, MOUNT_REMOUNTING_SIGKILL))
991 mount_enter_mounted(m, MOUNT_SUCCESS);
992 else if (state == MOUNT_UNMOUNTING_SIGTERM && m->kill_context.send_sigkill)
993 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, MOUNT_SUCCESS);
994 else
995 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS, /* flush_result= */ false);
996
997 return;
998
999 fail:
1000 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_RESOURCES, /* flush_result= */ false);
1001 }
1002
1003 static int mount_set_umount_command(Mount *m, ExecCommand *c) {
1004 int r;
1005
1006 assert(m);
1007 assert(c);
1008
1009 r = exec_command_set(c, UMOUNT_PATH, m->where, "-c", NULL);
1010 if (r < 0)
1011 return r;
1012
1013 if (m->lazy_unmount) {
1014 r = exec_command_append(c, "-l", NULL);
1015 if (r < 0)
1016 return r;
1017 }
1018
1019 if (m->force_unmount) {
1020 r = exec_command_append(c, "-f", NULL);
1021 if (r < 0)
1022 return r;
1023 }
1024
1025 return 0;
1026 }
1027
1028 static void mount_enter_unmounting(Mount *m) {
1029 int r;
1030
1031 assert(m);
1032
1033 /* Start counting our attempts */
1034 if (!IN_SET(m->state,
1035 MOUNT_UNMOUNTING,
1036 MOUNT_UNMOUNTING_SIGTERM,
1037 MOUNT_UNMOUNTING_SIGKILL))
1038 m->n_retry_umount = 0;
1039
1040 mount_unwatch_control_pid(m);
1041
1042 m->control_command_id = MOUNT_EXEC_UNMOUNT;
1043 m->control_command = m->exec_command + MOUNT_EXEC_UNMOUNT;
1044
1045 r = mount_set_umount_command(m, m->control_command);
1046 if (r < 0) {
1047 log_unit_warning_errno(UNIT(m), r, "Failed to prepare umount command line: %m");
1048 goto fail;
1049 }
1050
1051 r = mount_spawn(m, m->control_command, mount_exec_flags(MOUNT_UNMOUNTING), &m->control_pid);
1052 if (r < 0) {
1053 log_unit_warning_errno(UNIT(m), r, "Failed to spawn 'umount' task: %m");
1054 goto fail;
1055 }
1056
1057 mount_set_state(m, MOUNT_UNMOUNTING);
1058 return;
1059
1060 fail:
1061 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_RESOURCES, /* flush_result= */ false);
1062 }
1063
1064 static int mount_apply_graceful_options(Mount *m, const MountParameters *p, char **opts) {
1065 _cleanup_strv_free_ char **graceful = NULL;
1066 _cleanup_free_ char *filtered = NULL;
1067 int r;
1068
1069 assert(m);
1070 assert(p);
1071 assert(opts);
1072
1073 r = fstab_filter_options(*opts, "x-systemd.graceful-option\0", NULL, NULL, &graceful, &filtered);
1074 if (r <= 0)
1075 return r;
1076
1077 if (!p->fstype) {
1078 log_unit_warning(UNIT(m), "x-systemd.graceful-option= used but file system type not known, suppressing all graceful options.");
1079 return 0;
1080 }
1081
1082 STRV_FOREACH(o, graceful) {
1083 _cleanup_free_ char *k = NULL, *v = NULL;
1084
1085 r = split_pair(*o, "=", &k, &v);
1086 if (r < 0 && r != -EINVAL) /* EINVAL → not a key/value pair */
1087 return r;
1088
1089 r = mount_option_supported(p->fstype, k ?: *o, v);
1090 if (r == -EAGAIN) {
1091 log_unit_warning_errno(UNIT(m), r,
1092 "x-systemd.graceful-option= used but not supported by file system %s, suppressing all.",
1093 p->fstype);
1094 break;
1095 }
1096 if (r < 0)
1097 log_unit_warning_errno(UNIT(m), r,
1098 "x-systemd.graceful-option=%s specified, but cannot determine availability, suppressing: %m", *o);
1099 else if (r == 0)
1100 log_unit_info(UNIT(m), "x-systemd.graceful-option=%s specified, but option is not available, suppressing.", *o);
1101 else {
1102 log_unit_debug(UNIT(m), "x-systemd.graceful-option=%s specified and supported, appending to mount option string.", *o);
1103
1104 if (!strextend_with_separator(&filtered, ",", *o))
1105 return -ENOMEM;
1106 }
1107 }
1108
1109 return free_and_replace(*opts, filtered);
1110 }
1111
1112 static int mount_set_mount_command(Mount *m, ExecCommand *c, const MountParameters *p, bool remount) {
1113 int r;
1114
1115 assert(m);
1116 assert(c);
1117 assert(p);
1118
1119 r = exec_command_set(c, MOUNT_PATH, p->what, m->where, NULL);
1120 if (r < 0)
1121 return r;
1122
1123 if (m->sloppy_options) {
1124 r = exec_command_append(c, "-s", NULL);
1125 if (r < 0)
1126 return r;
1127 }
1128
1129 if (m->read_write_only) {
1130 r = exec_command_append(c, "-w", NULL);
1131 if (r < 0)
1132 return r;
1133 }
1134
1135 if (p->fstype) {
1136 r = exec_command_append(c, "-t", p->fstype, NULL);
1137 if (r < 0)
1138 return r;
1139 }
1140
1141 _cleanup_free_ char *opts = NULL;
1142 r = fstab_filter_options(p->options, "nofail\0" "fail\0" "noauto\0" "auto\0", NULL, NULL, NULL, &opts);
1143 if (r < 0)
1144 return r;
1145
1146 r = mount_apply_graceful_options(m, p, &opts);
1147 if (r < 0)
1148 return r;
1149
1150 if (remount)
1151 if (!strprepend_with_separator(&opts, ",", "remount"))
1152 return -ENOMEM;
1153
1154 if (!isempty(opts)) {
1155 r = exec_command_append(c, "-o", opts, NULL);
1156 if (r < 0)
1157 return r;
1158 }
1159
1160 return 0;
1161 }
1162
1163 static void mount_enter_mounting(Mount *m) {
1164 _cleanup_close_ int fd = -EBADF;
1165 _cleanup_free_ char *fn = NULL;
1166 int r;
1167
1168 assert(m);
1169
1170 /* Validate that the path we are overmounting does not contain any symlinks, because if it does, we
1171 * couldn't support that reasonably: the mounts in /proc/self/mountinfo would not be recognizable to
1172 * us anymore. */
1173 fd = chase_and_open_parent(m->where, /* root= */ NULL, CHASE_PROHIBIT_SYMLINKS|CHASE_MKDIR_0755|CHASE_TRIGGER_AUTOFS, &fn);
1174 if (fd == -ELOOP) {
1175 r = unit_log_noncanonical_mount_path(UNIT(m), m->where);
1176 goto fail;
1177 }
1178 if (fd < 0) {
1179 log_unit_error_errno(UNIT(m), fd, "Failed to resolve parent of mount point '%s': %m", m->where);
1180 goto fail;
1181 }
1182
1183 MountParameters *p = get_mount_parameters_fragment(m);
1184 if (!p) {
1185 r = log_unit_warning_errno(UNIT(m), SYNTHETIC_ERRNO(ENOENT), "No mount parameters to operate on.");
1186 goto fail;
1187 }
1188
1189 bool source_is_dir = true;
1190 if (mount_is_bind(p)) {
1191 r = is_dir(p->what, /* follow= */ true);
1192 if (r < 0 && r != -ENOENT)
1193 log_unit_info_errno(UNIT(m), r, "Failed to determine type of bind mount source '%s', ignoring: %m", p->what);
1194 else if (r == 0)
1195 source_is_dir = false;
1196 }
1197
1198 r = make_mount_point_inode_from_mode(
1199 fd,
1200 fn,
1201 source_is_dir ? S_IFDIR : S_IFREG,
1202 m->directory_mode);
1203 if (r < 0 && r != -EEXIST)
1204 log_unit_warning_errno(UNIT(m), r, "Failed to create mount point '%s', ignoring: %m", m->where);
1205
1206 /* If we are asked to create an OverlayFS, create the upper/work directories if they are missing */
1207 if (streq_ptr(p->fstype, "overlay")) {
1208 _cleanup_strv_free_ char **dirs = NULL;
1209
1210 r = fstab_filter_options(
1211 p->options,
1212 "upperdir\0workdir\0",
1213 /* ret_namefound= */ NULL,
1214 /* ret_value= */ NULL,
1215 &dirs,
1216 /* ret_filtered= */ NULL);
1217 if (r < 0)
1218 log_unit_warning_errno(
1219 UNIT(m),
1220 r,
1221 "Failed to determine upper directory for OverlayFS, ignoring: %m");
1222 else
1223 STRV_FOREACH(d, dirs) {
1224 r = mkdir_p_label(*d, m->directory_mode);
1225 if (r < 0 && r != -EEXIST)
1226 log_unit_warning_errno(
1227 UNIT(m),
1228 r,
1229 "Failed to create overlay directory '%s', ignoring: %m",
1230 *d);
1231 }
1232 }
1233
1234 if (source_is_dir)
1235 unit_warn_if_dir_nonempty(UNIT(m), m->where);
1236
1237 /* Create the source directory for bind-mounts if needed */
1238 if (mount_is_bind(p)) {
1239 r = mkdir_p_label(p->what, m->directory_mode);
1240 /* mkdir_p_label() can return -EEXIST if the target path exists and is not a directory - which is
1241 * totally OK, in case the user wants us to overmount a non-directory inode. Also -EROFS can be
1242 * returned on read-only filesystem. Moreover, -EACCES (and also maybe -EPERM?) may be returned
1243 * when the path is on NFS. See issue #24120. All such errors will be logged in the debug level. */
1244 if (r < 0 && r != -EEXIST)
1245 log_unit_full_errno(UNIT(m),
1246 ERRNO_IS_NEG_FS_WRITE_REFUSED(r) ? LOG_DEBUG : LOG_WARNING,
1247 r, "Failed to make bind mount source '%s', ignoring: %m", p->what);
1248 }
1249
1250 mount_unwatch_control_pid(m);
1251 unit_warn_leftover_processes(UNIT(m), /* start= */ true);
1252
1253 m->control_command_id = MOUNT_EXEC_MOUNT;
1254 m->control_command = m->exec_command + MOUNT_EXEC_MOUNT;
1255
1256 r = mount_set_mount_command(m, m->control_command, p, /* remount= */ false);
1257 if (r < 0) {
1258 log_unit_error_errno(UNIT(m), r, "Failed to prepare mount command line: %m");
1259 goto fail;
1260 }
1261
1262 r = mount_spawn(m, m->control_command, mount_exec_flags(MOUNT_MOUNTING), &m->control_pid);
1263 if (r < 0) {
1264 log_unit_warning_errno(UNIT(m), r, "Failed to spawn 'mount' task: %m");
1265 goto fail;
1266 }
1267
1268 mount_set_state(m, MOUNT_MOUNTING);
1269 return;
1270
1271 fail:
1272 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_RESOURCES, /* flush_result= */ false);
1273 }
1274
1275 static void mount_set_reload_result(Mount *m, MountResult result) {
1276 assert(m);
1277
1278 /* Only store the first error we encounter */
1279 if (m->reload_result != MOUNT_SUCCESS)
1280 return;
1281
1282 m->reload_result = result;
1283 }
1284
1285 static void mount_enter_remounting(Mount *m) {
1286 MountParameters *p;
1287 int r;
1288
1289 assert(m);
1290
1291 p = get_mount_parameters_fragment(m);
1292 if (!p) {
1293 r = log_unit_warning_errno(UNIT(m), SYNTHETIC_ERRNO(ENOENT), "No mount parameters to operate on.");
1294 goto fail;
1295 }
1296
1297 mount_unwatch_control_pid(m);
1298 m->reload_result = MOUNT_SUCCESS;
1299
1300 m->control_command_id = MOUNT_EXEC_REMOUNT;
1301 m->control_command = m->exec_command + MOUNT_EXEC_REMOUNT;
1302
1303 r = mount_set_mount_command(m, m->control_command, p, /* remount= */ true);
1304 if (r < 0) {
1305 log_unit_error_errno(UNIT(m), r, "Failed to prepare remount command line: %m");
1306 goto fail;
1307 }
1308
1309 r = mount_spawn(m, m->control_command, mount_exec_flags(MOUNT_REMOUNTING), &m->control_pid);
1310 if (r < 0) {
1311 log_unit_warning_errno(UNIT(m), r, "Failed to spawn 'remount' task: %m");
1312 goto fail;
1313 }
1314
1315 mount_set_state(m, MOUNT_REMOUNTING);
1316 return;
1317
1318 fail:
1319 mount_set_reload_result(m, MOUNT_FAILURE_RESOURCES);
1320 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS, /* flush_result= */ false);
1321 }
1322
1323 static void mount_cycle_clear(Mount *m) {
1324 assert(m);
1325
1326 /* Clear all state we shall forget for this new cycle */
1327
1328 m->result = MOUNT_SUCCESS;
1329 m->reload_result = MOUNT_SUCCESS;
1330 exec_command_reset_status_array(m->exec_command, _MOUNT_EXEC_COMMAND_MAX);
1331
1332 if (m->cgroup_runtime)
1333 m->cgroup_runtime->reset_accounting = true;
1334 }
1335
1336 static int mount_start(Unit *u) {
1337 Mount *m = ASSERT_PTR(MOUNT(u));
1338 int r;
1339
1340 assert(IN_SET(m->state, MOUNT_DEAD, MOUNT_FAILED));
1341
1342 r = unit_acquire_invocation_id(u);
1343 if (r < 0)
1344 return r;
1345
1346 mount_cycle_clear(m);
1347 mount_enter_mounting(m);
1348
1349 return 1;
1350 }
1351
1352 static int mount_stop(Unit *u) {
1353 Mount *m = ASSERT_PTR(MOUNT(u));
1354 int r;
1355
1356 switch (m->state) {
1357
1358 case MOUNT_UNMOUNTING:
1359 case MOUNT_UNMOUNTING_SIGKILL:
1360 case MOUNT_UNMOUNTING_SIGTERM:
1361 /* Already on it */
1362 return 0;
1363
1364 case MOUNT_MOUNTING:
1365 case MOUNT_MOUNTING_DONE:
1366 /* If we are still waiting for /bin/mount, we go directly into kill mode. */
1367 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGTERM, MOUNT_SUCCESS);
1368 return 0;
1369
1370 case MOUNT_REMOUNTING:
1371 case MOUNT_REMOUNTING_SIGTERM:
1372 assert(pidref_is_set(&m->control_pid));
1373
1374 r = pidref_kill_and_sigcont(&m->control_pid, SIGKILL);
1375 if (r < 0)
1376 log_unit_debug_errno(u, r,
1377 "Failed to kill remount process " PID_FMT ", ignoring: %m",
1378 m->control_pid.pid);
1379
1380 _fallthrough_;
1381 case MOUNT_REMOUNTING_SIGKILL:
1382 case MOUNT_MOUNTED:
1383 mount_enter_unmounting(m);
1384 return 1;
1385
1386 case MOUNT_CLEANING:
1387 /* If we are currently cleaning, then abort it, brutally. */
1388 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, MOUNT_SUCCESS);
1389 return 0;
1390
1391 default:
1392 assert_not_reached();
1393 }
1394 }
1395
1396 static int mount_reload(Unit *u) {
1397 Mount *m = ASSERT_PTR(MOUNT(u));
1398
1399 assert(m->state == MOUNT_MOUNTED);
1400
1401 mount_enter_remounting(m);
1402
1403 return 1;
1404 }
1405
1406 static bool mount_can_reload(Unit *u) {
1407 Mount *m = ASSERT_PTR(MOUNT(u));
1408
1409 return get_mount_parameters_fragment(m);
1410 }
1411
1412 static int mount_serialize(Unit *u, FILE *f, FDSet *fds) {
1413 Mount *m = ASSERT_PTR(MOUNT(u));
1414
1415 assert(f);
1416 assert(fds);
1417
1418 (void) serialize_item(f, "state", mount_state_to_string(m->state));
1419 (void) serialize_item(f, "result", mount_result_to_string(m->result));
1420 (void) serialize_item(f, "reload-result", mount_result_to_string(m->reload_result));
1421 (void) serialize_item_format(f, "n-retry-umount", "%u", m->n_retry_umount);
1422 (void) serialize_pidref(f, fds, "control-pid", &m->control_pid);
1423
1424 if (m->control_command_id >= 0)
1425 (void) serialize_item(f, "control-command", mount_exec_command_to_string(m->control_command_id));
1426
1427 return 0;
1428 }
1429
1430 static int mount_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1431 Mount *m = ASSERT_PTR(MOUNT(u));
1432 int r;
1433
1434 assert(key);
1435 assert(value);
1436 assert(fds);
1437
1438 if (streq(key, "state")) {
1439 MountState state;
1440
1441 state = mount_state_from_string(value);
1442 if (state < 0)
1443 log_unit_debug_errno(u, state, "Failed to parse state value: %s", value);
1444 else
1445 m->deserialized_state = state;
1446
1447 } else if (streq(key, "result")) {
1448 MountResult f;
1449
1450 f = mount_result_from_string(value);
1451 if (f < 0)
1452 log_unit_debug_errno(u, f, "Failed to parse result value: %s", value);
1453 else if (f != MOUNT_SUCCESS)
1454 m->result = f;
1455
1456 } else if (streq(key, "reload-result")) {
1457 MountResult f;
1458
1459 f = mount_result_from_string(value);
1460 if (f < 0)
1461 log_unit_debug_errno(u, f, "Failed to parse reload result value: %s", value);
1462 else if (f != MOUNT_SUCCESS)
1463 m->reload_result = f;
1464
1465 } else if (streq(key, "n-retry-umount")) {
1466
1467 r = safe_atou(value, &m->n_retry_umount);
1468 if (r < 0)
1469 log_unit_debug_errno(u, r, "Failed to parse n-retry-umount value: %s", value);
1470
1471 } else if (streq(key, "control-pid")) {
1472
1473 if (!pidref_is_set(&m->control_pid))
1474 (void) deserialize_pidref(fds, value, &m->control_pid);
1475
1476 } else if (streq(key, "control-command")) {
1477 MountExecCommand id;
1478
1479 id = mount_exec_command_from_string(value);
1480 if (id < 0)
1481 log_unit_debug_errno(u, id, "Failed to parse exec-command value: %s", value);
1482 else {
1483 m->control_command_id = id;
1484 m->control_command = m->exec_command + id;
1485 }
1486 } else
1487 log_unit_debug(u, "Unknown serialization key: %s", key);
1488
1489 return 0;
1490 }
1491
1492 static UnitActiveState mount_active_state(Unit *u) {
1493 Mount *m = ASSERT_PTR(MOUNT(u));
1494
1495 return state_translation_table[m->state];
1496 }
1497
1498 static const char *mount_sub_state_to_string(Unit *u) {
1499 Mount *m = ASSERT_PTR(MOUNT(u));
1500
1501 return mount_state_to_string(m->state);
1502 }
1503
1504 static bool mount_may_gc(Unit *u) {
1505 Mount *m = ASSERT_PTR(MOUNT(u));
1506
1507 if (m->from_proc_self_mountinfo)
1508 return false;
1509
1510 return true;
1511 }
1512
1513 static void mount_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1514 Mount *m = ASSERT_PTR(MOUNT(u));
1515 MountResult f;
1516
1517 assert(pid >= 0);
1518
1519 if (pid != m->control_pid.pid)
1520 return;
1521
1522 /* So here's the thing, we really want to know before /usr/bin/mount or /usr/bin/umount exit whether
1523 * they established/remove a mount. This is important when mounting, but even more so when unmounting
1524 * since we need to deal with nested mounts and otherwise cannot safely determine whether to repeat
1525 * the unmounts. In theory, the kernel fires /proc/self/mountinfo changes off before returning from
1526 * the mount() or umount() syscalls, and thus we should see the changes to the proc file before we
1527 * process the waitid() for the /usr/bin/(u)mount processes. However, this is unfortunately racy: we
1528 * have to waitid() for processes using P_ALL (since we need to reap unexpected children that got
1529 * reparented to PID 1), but when using P_ALL we might end up reaping processes that terminated just
1530 * instants ago, i.e. already after our last event loop iteration (i.e. after the last point we might
1531 * have noticed /proc/self/mountinfo events via epoll). This means event loop priorities for
1532 * processing SIGCHLD vs. /proc/self/mountinfo IO events are not as relevant as we want. To fix that
1533 * race, let's explicitly scan /proc/self/mountinfo before we start processing /usr/bin/(u)mount
1534 * dying. It's ugly, but it makes our ordering systematic again, and makes sure we always see
1535 * /proc/self/mountinfo changes before our mount/umount exits. */
1536 (void) mount_process_proc_self_mountinfo(u->manager);
1537
1538 pidref_done(&m->control_pid);
1539
1540 if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL))
1541 f = MOUNT_SUCCESS;
1542 else if (code == CLD_EXITED)
1543 f = MOUNT_FAILURE_EXIT_CODE;
1544 else if (code == CLD_KILLED)
1545 f = MOUNT_FAILURE_SIGNAL;
1546 else if (code == CLD_DUMPED)
1547 f = MOUNT_FAILURE_CORE_DUMP;
1548 else
1549 assert_not_reached();
1550
1551 if (IN_SET(m->state, MOUNT_REMOUNTING, MOUNT_REMOUNTING_SIGKILL, MOUNT_REMOUNTING_SIGTERM))
1552 mount_set_reload_result(m, f);
1553 else if (m->result == MOUNT_SUCCESS && !IN_SET(m->state, MOUNT_MOUNTING, MOUNT_UNMOUNTING))
1554 /* MOUNT_MOUNTING and MOUNT_UNMOUNTING states need to be patched, see below. */
1555 m->result = f;
1556
1557 if (m->control_command) {
1558 exec_status_exit(&m->control_command->exec_status, &m->exec_context, pid, code, status);
1559
1560 m->control_command = NULL;
1561 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
1562 }
1563
1564 unit_log_process_exit(
1565 u,
1566 "Mount process",
1567 mount_exec_command_to_string(m->control_command_id),
1568 f == MOUNT_SUCCESS,
1569 code, status);
1570
1571 /* Note that due to the io event priority logic, we can be sure the new mountinfo is loaded
1572 * before we process the SIGCHLD for the mount command. */
1573
1574 switch (m->state) {
1575
1576 case MOUNT_MOUNTING:
1577 /* Our mount point has not appeared in mountinfo. Something went wrong. */
1578
1579 if (f == MOUNT_SUCCESS) {
1580 /* Either /bin/mount has an unexpected definition of success, or someone raced us
1581 * and we lost. */
1582 log_unit_warning(UNIT(m), "Mount process finished, but there is no mount.");
1583 f = MOUNT_FAILURE_PROTOCOL;
1584 }
1585 mount_enter_dead(m, f, /* flush_result= */ false);
1586 break;
1587
1588 case MOUNT_MOUNTING_DONE:
1589 mount_enter_mounted(m, f);
1590 break;
1591
1592 case MOUNT_REMOUNTING:
1593 case MOUNT_REMOUNTING_SIGTERM:
1594 case MOUNT_REMOUNTING_SIGKILL:
1595 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS, /* flush_result= */ false);
1596 break;
1597
1598 case MOUNT_UNMOUNTING:
1599 if (f == MOUNT_SUCCESS && m->from_proc_self_mountinfo) {
1600 /* Still a mount point? If so, let's try again. Most likely there were multiple mount points
1601 * stacked on top of each other. We might exceed the timeout specified by the user overall,
1602 * but we will stop as soon as any one umount times out. */
1603
1604 if (m->n_retry_umount < RETRY_UMOUNT_MAX) {
1605 log_unit_debug(u, "Mount still present, trying again.");
1606 m->n_retry_umount++;
1607 mount_enter_unmounting(m);
1608 } else {
1609 log_unit_warning(u, "Mount still present after %u attempts to unmount, giving up.", m->n_retry_umount);
1610 mount_enter_mounted(m, MOUNT_FAILURE_PROTOCOL);
1611 }
1612 } else if (f == MOUNT_FAILURE_EXIT_CODE && !m->from_proc_self_mountinfo) {
1613 /* Hmm, umount process spawned by us failed, but the mount disappeared anyway?
1614 * Maybe someone else is trying to unmount at the same time. */
1615 log_unit_notice(u, "Mount disappeared even though umount process failed, continuing.");
1616 mount_enter_dead(m, MOUNT_SUCCESS, /* flush_result= */ true);
1617 } else
1618 /* At this point, either the unmount succeeded or unexpected error occurred. We usually
1619 * remember the first error in 'result', but here let's update that forcibly, since
1620 * there could previous failed attempts yet we only care about the most recent
1621 * attempt. IOW, if we eventually managed to unmount the stuff, don't enter failed
1622 * end state. */
1623 mount_enter_dead_or_mounted(m, f, /* flush_result= */ true);
1624
1625 break;
1626
1627 case MOUNT_UNMOUNTING_SIGTERM:
1628 case MOUNT_UNMOUNTING_SIGKILL:
1629 mount_enter_dead_or_mounted(m, f, /* flush_result= */ false);
1630 break;
1631
1632 case MOUNT_CLEANING:
1633 if (m->clean_result == MOUNT_SUCCESS)
1634 m->clean_result = f;
1635
1636 mount_enter_dead(m, MOUNT_SUCCESS, /* flush_result= */ false);
1637 break;
1638
1639 default:
1640 assert_not_reached();
1641 }
1642
1643 /* Notify clients about changed exit status */
1644 unit_add_to_dbus_queue(u);
1645 }
1646
1647 static int mount_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
1648 Mount *m = ASSERT_PTR(MOUNT(userdata));
1649
1650 assert(m->timer_event_source == source);
1651
1652 switch (m->state) {
1653
1654 case MOUNT_MOUNTING:
1655 case MOUNT_MOUNTING_DONE:
1656 log_unit_warning(UNIT(m), "Mounting timed out. Terminating.");
1657 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGTERM, MOUNT_FAILURE_TIMEOUT);
1658 break;
1659
1660 case MOUNT_REMOUNTING:
1661 log_unit_warning(UNIT(m), "Remounting timed out. Terminating remount process.");
1662 mount_set_reload_result(m, MOUNT_FAILURE_TIMEOUT);
1663 mount_enter_signal(m, MOUNT_REMOUNTING_SIGTERM, MOUNT_SUCCESS);
1664 break;
1665
1666 case MOUNT_REMOUNTING_SIGTERM:
1667 mount_set_reload_result(m, MOUNT_FAILURE_TIMEOUT);
1668
1669 if (m->kill_context.send_sigkill) {
1670 log_unit_warning(UNIT(m), "Remounting timed out. Killing.");
1671 mount_enter_signal(m, MOUNT_REMOUNTING_SIGKILL, MOUNT_SUCCESS);
1672 } else {
1673 log_unit_warning(UNIT(m), "Remounting timed out. Skipping SIGKILL. Ignoring.");
1674 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS, /* flush_result= */ false);
1675 }
1676 break;
1677
1678 case MOUNT_REMOUNTING_SIGKILL:
1679 mount_set_reload_result(m, MOUNT_FAILURE_TIMEOUT);
1680
1681 log_unit_warning(UNIT(m), "Mount process still around after SIGKILL. Ignoring.");
1682 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS, /* flush_result= */ false);
1683 break;
1684
1685 case MOUNT_UNMOUNTING:
1686 log_unit_warning(UNIT(m), "Unmounting timed out. Terminating.");
1687 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGTERM, MOUNT_FAILURE_TIMEOUT);
1688 break;
1689
1690 case MOUNT_UNMOUNTING_SIGTERM:
1691 if (m->kill_context.send_sigkill) {
1692 log_unit_warning(UNIT(m), "Mount process timed out. Killing.");
1693 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, MOUNT_FAILURE_TIMEOUT);
1694 } else {
1695 log_unit_warning(UNIT(m), "Mount process timed out. Skipping SIGKILL. Ignoring.");
1696 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_TIMEOUT, /* flush_result= */ false);
1697 }
1698 break;
1699
1700 case MOUNT_UNMOUNTING_SIGKILL:
1701 log_unit_warning(UNIT(m), "Mount process still around after SIGKILL. Ignoring.");
1702 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_TIMEOUT, /* flush_result= */ false);
1703 break;
1704
1705 case MOUNT_CLEANING:
1706 log_unit_warning(UNIT(m), "Cleaning timed out. killing.");
1707
1708 if (m->clean_result == MOUNT_SUCCESS)
1709 m->clean_result = MOUNT_FAILURE_TIMEOUT;
1710
1711 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, 0);
1712 break;
1713
1714 default:
1715 assert_not_reached();
1716 }
1717
1718 return 0;
1719 }
1720
1721 #if HAVE_LIBMOUNT
1722 static int update_parameters_proc_self_mountinfo(
1723 Mount *m,
1724 const char *what,
1725 const char *options,
1726 const char *fstype) {
1727
1728 MountParameters *p;
1729 int r, q, w;
1730
1731 assert(m);
1732
1733 p = &m->parameters_proc_self_mountinfo;
1734
1735 r = free_and_strdup(&p->what, what);
1736 if (r < 0)
1737 return r;
1738
1739 q = free_and_strdup(&p->options, options);
1740 if (q < 0)
1741 return q;
1742
1743 w = free_and_strdup(&p->fstype, fstype);
1744 if (w < 0)
1745 return w;
1746
1747 return r > 0 || q > 0 || w > 0;
1748 }
1749
1750 static int mount_setup_new_unit(
1751 Manager *m,
1752 const char *name,
1753 const char *what,
1754 const char *where,
1755 const char *options,
1756 const char *fstype,
1757 MountProcFlags *ret_flags,
1758 Unit **ret) {
1759
1760 _cleanup_(unit_freep) Unit *u = NULL;
1761 Mount *mnt;
1762 int r;
1763
1764 assert(m);
1765 assert(name);
1766 assert(ret_flags);
1767 assert(ret);
1768
1769 r = unit_new_for_name(m, sizeof(Mount), name, &u);
1770 if (r < 0)
1771 return r;
1772
1773 mnt = ASSERT_PTR(MOUNT(u));
1774
1775 r = free_and_strdup(&u->source_path, "/proc/self/mountinfo");
1776 if (r < 0)
1777 return r;
1778
1779 r = free_and_strdup(&mnt->where, where);
1780 if (r < 0)
1781 return r;
1782
1783 r = update_parameters_proc_self_mountinfo(mnt, what, options, fstype);
1784 if (r < 0)
1785 return r;
1786
1787 /* This unit was generated because /proc/self/mountinfo reported it. Remember this, so that by the
1788 * time we load the unit file for it (and thus add in extra deps right after) we know what source to
1789 * attributes the deps to. */
1790 mnt->from_proc_self_mountinfo = true;
1791
1792 /* We have only allocated the stub now, let's enqueue this unit for loading now, so that everything
1793 * else is loaded in now. */
1794 unit_add_to_load_queue(u);
1795
1796 *ret_flags = MOUNT_PROC_IS_MOUNTED | MOUNT_PROC_JUST_MOUNTED | MOUNT_PROC_JUST_CHANGED;
1797 *ret = TAKE_PTR(u);
1798 return 0;
1799 }
1800
1801 static int mount_setup_existing_unit(
1802 Unit *u,
1803 const char *what,
1804 const char *where,
1805 const char *options,
1806 const char *fstype,
1807 MountProcFlags *ret_flags) {
1808
1809 Mount *m = ASSERT_PTR(MOUNT(u));
1810 int r;
1811
1812 assert(u);
1813 assert(where);
1814 assert(ret_flags);
1815
1816 if (!m->where) {
1817 m->where = strdup(where);
1818 if (!m->where)
1819 return -ENOMEM;
1820 }
1821
1822 /* In case we have multiple mounts established on the same mount point, let's merge flags set already
1823 * for the current unit. Note that the flags field is reset on each iteration of reading
1824 * /proc/self/mountinfo, hence we know for sure anything already set here is from the current
1825 * iteration and thus worthy of taking into account. */
1826 MountProcFlags flags = m->proc_flags | MOUNT_PROC_IS_MOUNTED;
1827
1828 r = update_parameters_proc_self_mountinfo(m, what, options, fstype);
1829 if (r < 0)
1830 return r;
1831 if (r > 0)
1832 flags |= MOUNT_PROC_JUST_CHANGED;
1833
1834 /* There are two conditions when we consider a mount point just mounted: when we haven't seen it in
1835 * /proc/self/mountinfo before or when MOUNT_MOUNTING is our current state. Why bother with the
1836 * latter? Shouldn't that be covered by the former? No, during reload it is not because we might then
1837 * encounter a new /proc/self/mountinfo in combination with an old mount unit state (since it stems
1838 * from the serialized state), and need to catch up. Since we know that the MOUNT_MOUNTING state is
1839 * reached when we wait for the mount to appear we hence can assume that if we are in it, we are
1840 * actually seeing it established for the first time. */
1841 if (!m->from_proc_self_mountinfo || m->state == MOUNT_MOUNTING)
1842 flags |= MOUNT_PROC_JUST_MOUNTED;
1843
1844 m->from_proc_self_mountinfo = true;
1845
1846 if (UNIT_IS_LOAD_ERROR(u->load_state)) {
1847 /* The unit was previously not found or otherwise not loaded. Now that the unit shows up in
1848 * /proc/self/mountinfo we should reconsider that. Hence, let's reset the load state and load
1849 * error, and add the unit to load queue. */
1850 u->load_state = UNIT_STUB;
1851 u->load_error = 0;
1852 unit_add_to_load_queue(u);
1853
1854 flags |= MOUNT_PROC_JUST_CHANGED;
1855 }
1856
1857 if (FLAGS_SET(flags, MOUNT_PROC_JUST_CHANGED) && u->load_state == UNIT_LOADED) {
1858 /* If things changed, and we have successfully loaded the unit, then make sure that all deps
1859 * are regenerated. Let's first remove all automatic deps, and then add in the new ones. */
1860 r = mount_add_non_exec_dependencies(m);
1861 if (r < 0)
1862 return r;
1863 }
1864
1865 *ret_flags = flags;
1866 return 0;
1867 }
1868
1869 static int mount_setup_unit(
1870 Manager *m,
1871 const char *what,
1872 const char *where,
1873 const char *options,
1874 const char *fstype,
1875 bool set_flags) {
1876
1877 _cleanup_free_ char *e = NULL;
1878 MountProcFlags flags;
1879 Unit *u;
1880 int r;
1881
1882 assert(m);
1883 assert(what);
1884 assert(where);
1885 assert(options);
1886 assert(fstype);
1887
1888 /* Ignore API and credential mount points. They should never be referenced in dependencies ever.
1889 * Furthermore, the lifetime of credential mounts is strictly bound to the owning services,
1890 * so mount units make little sense for them. */
1891 if (mount_point_is_api(where) || mount_point_ignore(where) ||
1892 mount_point_is_credentials(m->prefix[EXEC_DIRECTORY_RUNTIME], where))
1893 return 0;
1894
1895 if (streq(fstype, "autofs"))
1896 return 0;
1897
1898 /* probably some kind of swap, ignore */
1899 if (!is_path(where))
1900 return 0;
1901
1902 r = unit_name_from_path(where, ".mount", &e);
1903 if (r < 0)
1904 return log_struct_errno(
1905 LOG_WARNING, r,
1906 LOG_MESSAGE_ID(SD_MESSAGE_MOUNT_POINT_PATH_NOT_SUITABLE_STR),
1907 LOG_ITEM("MOUNT_POINT=%s", where),
1908 LOG_MESSAGE("Failed to generate valid unit name from mount point path '%s', ignoring mount point: %m",
1909 where));
1910
1911 u = manager_get_unit(m, e);
1912 if (u)
1913 r = mount_setup_existing_unit(u, what, where, options, fstype, &flags);
1914 else
1915 /* First time we see this mount point meaning that it's not been initiated by a mount unit
1916 * but rather by the sysadmin having called mount(8) directly. */
1917 r = mount_setup_new_unit(m, e, what, where, options, fstype, &flags, &u);
1918 if (r < 0)
1919 return log_warning_errno(r, "Failed to set up mount unit for '%s': %m", where);
1920
1921 /* If the mount changed properties or state, let's notify our clients */
1922 if (flags & (MOUNT_PROC_JUST_CHANGED|MOUNT_PROC_JUST_MOUNTED))
1923 unit_add_to_dbus_queue(u);
1924
1925 if (set_flags)
1926 MOUNT(u)->proc_flags = flags;
1927
1928 return 0;
1929 }
1930
1931 static int mount_load_proc_self_mountinfo(Manager *m, bool set_flags) {
1932 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
1933 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
1934 _cleanup_set_free_ Set *devices = NULL;
1935 int r;
1936
1937 assert(m);
1938
1939 r = libmount_parse_with_utab(&table, &iter);
1940 if (r < 0)
1941 return log_error_errno(r, "Failed to parse /proc/self/mountinfo: %m");
1942
1943 for (;;) {
1944 struct libmnt_fs *fs;
1945 const char *device, *path, *options, *fstype;
1946
1947 r = sym_mnt_table_next_fs(table, iter, &fs);
1948 if (r == 1)
1949 break;
1950 if (r < 0)
1951 return log_error_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
1952
1953 device = sym_mnt_fs_get_source(fs);
1954 path = sym_mnt_fs_get_target(fs);
1955 options = sym_mnt_fs_get_options(fs);
1956 fstype = sym_mnt_fs_get_fstype(fs);
1957
1958 if (!device || !path)
1959 continue;
1960
1961 /* Just to achieve device name uniqueness. Note that the suppression of the duplicate
1962 * processing is merely an optimization, hence in case of OOM (unlikely) we'll just process
1963 * it twice. */
1964 if (set_put_strdup_full(&devices, &path_hash_ops_free, device) != 0)
1965 device_found_node(m, device, DEVICE_FOUND_MOUNT, DEVICE_FOUND_MOUNT);
1966
1967 (void) mount_setup_unit(m, device, path, options, fstype, set_flags);
1968 }
1969
1970 return 0;
1971 }
1972 #endif
1973
1974 static void mount_shutdown(Manager *m) {
1975 assert(m);
1976
1977 m->mount_event_source = sd_event_source_disable_unref(m->mount_event_source);
1978
1979 if (m->mount_monitor) {
1980 sym_mnt_unref_monitor(m->mount_monitor);
1981 m->mount_monitor = NULL;
1982 }
1983 }
1984
1985 static void mount_handoff_timestamp(
1986 Unit *u,
1987 const struct ucred *ucred,
1988 const dual_timestamp *ts) {
1989
1990 Mount *m = ASSERT_PTR(MOUNT(u));
1991
1992 assert(ucred);
1993 assert(ts);
1994
1995 if (m->control_pid.pid == ucred->pid && m->control_command) {
1996 exec_status_handoff(&m->control_command->exec_status, ucred, ts);
1997 unit_add_to_dbus_queue(u);
1998 }
1999 }
2000
2001 static int mount_get_timeout(Unit *u, usec_t *timeout) {
2002 Mount *m = ASSERT_PTR(MOUNT(u));
2003 usec_t t;
2004 int r;
2005
2006 assert(timeout);
2007
2008 if (!m->timer_event_source)
2009 return 0;
2010
2011 r = sd_event_source_get_time(m->timer_event_source, &t);
2012 if (r < 0)
2013 return r;
2014 if (t == USEC_INFINITY)
2015 return 0;
2016
2017 *timeout = t;
2018 return 1;
2019 }
2020
2021 static void mount_enumerate_perpetual(Manager *m) {
2022 Unit *u;
2023 int r;
2024
2025 assert(m);
2026 assert(unit_type_supported(UNIT_MOUNT));
2027
2028 /* Whatever happens, we know for sure that the root directory is around, and cannot go away. Let's
2029 * unconditionally synthesize it here and mark it as perpetual. */
2030
2031 u = manager_get_unit(m, SPECIAL_ROOT_MOUNT);
2032 if (!u) {
2033 r = unit_new_for_name(m, sizeof(Mount), SPECIAL_ROOT_MOUNT, &u);
2034 if (r < 0)
2035 return (void) log_error_errno(r, "Failed to allocate the special %s unit: %m",
2036 SPECIAL_ROOT_MOUNT);
2037 }
2038
2039 u->perpetual = true;
2040 MOUNT(u)->deserialized_state = MOUNT_MOUNTED;
2041
2042 unit_add_to_load_queue(u);
2043 unit_add_to_dbus_queue(u);
2044 }
2045
2046 #if HAVE_LIBMOUNT
2047 static bool mount_is_mounted(Mount *m) {
2048 assert(m);
2049
2050 return UNIT(m)->perpetual || FLAGS_SET(m->proc_flags, MOUNT_PROC_IS_MOUNTED);
2051 }
2052
2053 static int mount_on_ratelimit_expire(sd_event_source *s, void *userdata) {
2054 Manager *m = ASSERT_PTR(userdata);
2055 Job *j;
2056
2057 /* Let's enqueue all start jobs that were previously skipped because of active ratelimit. */
2058 HASHMAP_FOREACH(j, m->jobs) {
2059 if (j->unit->type != UNIT_MOUNT)
2060 continue;
2061
2062 job_add_to_run_queue(j);
2063 }
2064
2065 /* By entering ratelimited state we made all mount start jobs not runnable, now rate limit is over so
2066 * let's make sure we dispatch them in the next iteration. */
2067 manager_trigger_run_queue(m);
2068
2069 return 0;
2070 }
2071 #endif
2072
2073 static void mount_enumerate(Manager *m) {
2074 assert(m);
2075 assert(unit_type_supported(UNIT_MOUNT));
2076
2077 #if HAVE_LIBMOUNT
2078 int r;
2079
2080 sym_mnt_init_debug(0);
2081
2082 if (!m->mount_monitor) {
2083 usec_t mount_rate_limit_interval = 1 * USEC_PER_SEC;
2084 unsigned mount_rate_limit_burst = 5;
2085 int fd;
2086
2087 m->mount_monitor = sym_mnt_new_monitor();
2088 if (!m->mount_monitor) {
2089 log_oom();
2090 goto fail;
2091 }
2092
2093 r = sym_mnt_monitor_enable_kernel(m->mount_monitor, 1);
2094 if (r < 0) {
2095 log_error_errno(r, "Failed to enable watching of kernel mount events: %m");
2096 goto fail;
2097 }
2098
2099 r = sym_mnt_monitor_enable_userspace(m->mount_monitor, 1, NULL);
2100 if (r < 0) {
2101 log_error_errno(r, "Failed to enable watching of userspace mount events: %m");
2102 goto fail;
2103 }
2104
2105 /* mnt_unref_monitor() will close the fd */
2106 fd = r = sym_mnt_monitor_get_fd(m->mount_monitor);
2107 if (r < 0) {
2108 log_error_errno(r, "Failed to acquire watch file descriptor: %m");
2109 goto fail;
2110 }
2111
2112 r = sd_event_add_io(m->event, &m->mount_event_source, fd, EPOLLIN, mount_dispatch_io, m);
2113 if (r < 0) {
2114 log_error_errno(r, "Failed to watch mount file descriptor: %m");
2115 goto fail;
2116 }
2117
2118 r = sd_event_source_set_priority(m->mount_event_source, EVENT_PRIORITY_MOUNT_TABLE);
2119 if (r < 0) {
2120 log_error_errno(r, "Failed to adjust mount watch priority: %m");
2121 goto fail;
2122 }
2123
2124 /* Let users override the default (5 in 1s), as it stalls the boot sequence on busy systems. */
2125 const char *e = secure_getenv("SYSTEMD_DEFAULT_MOUNT_RATE_LIMIT_INTERVAL_SEC");
2126 if (e) {
2127 r = parse_sec(e, &mount_rate_limit_interval);
2128 if (r < 0)
2129 log_debug_errno(r, "Invalid value in $SYSTEMD_DEFAULT_MOUNT_RATE_LIMIT_INTERVAL_SEC, ignoring: %s", e);
2130 }
2131
2132 e = secure_getenv("SYSTEMD_DEFAULT_MOUNT_RATE_LIMIT_BURST");
2133 if (e) {
2134 r = safe_atou(e, &mount_rate_limit_burst);
2135 if (r < 0)
2136 log_debug_errno(r, "Invalid value in $SYSTEMD_DEFAULT_MOUNT_RATE_LIMIT_BURST, ignoring: %s", e);
2137 }
2138
2139 r = sd_event_source_set_ratelimit(m->mount_event_source, mount_rate_limit_interval, mount_rate_limit_burst);
2140 if (r < 0) {
2141 log_error_errno(r, "Failed to enable rate limit for mount events: %m");
2142 goto fail;
2143 }
2144
2145 r = sd_event_source_set_ratelimit_expire_callback(m->mount_event_source, mount_on_ratelimit_expire);
2146 if (r < 0) {
2147 log_error_errno(r, "Failed to enable rate limit for mount events: %m");
2148 goto fail;
2149 }
2150
2151 (void) sd_event_source_set_description(m->mount_event_source, "mount-monitor-dispatch");
2152 }
2153
2154 r = mount_load_proc_self_mountinfo(m, false);
2155 if (r < 0)
2156 goto fail;
2157
2158 return;
2159
2160 fail:
2161 #endif
2162 mount_shutdown(m);
2163 }
2164
2165 static int drain_libmount(Manager *m) {
2166 assert(m);
2167
2168 if (!m->mount_monitor)
2169 return false;
2170
2171 #if HAVE_LIBMOUNT
2172 bool rescan = false;
2173 int r;
2174
2175 /* Drain all events and verify that the event is valid.
2176 *
2177 * Note that libmount also monitors /run/mount mkdir if the directory does not exist yet. The mkdir
2178 * may generate event which is irrelevant for us.
2179 *
2180 * error: r < 0; valid: r == 0, false positive: r == 1 */
2181 do {
2182 r = sym_mnt_monitor_next_change(m->mount_monitor, NULL, NULL);
2183 if (r < 0)
2184 return log_error_errno(r, "Failed to drain libmount events: %m");
2185 if (r == 0)
2186 rescan = true;
2187 } while (r == 0);
2188
2189 return rescan;
2190
2191 #else
2192 assert_not_reached();
2193 #endif
2194 }
2195
2196 static int mount_process_proc_self_mountinfo(Manager *m) {
2197 int r;
2198
2199 assert(m);
2200
2201 r = drain_libmount(m);
2202 if (r <= 0)
2203 return r;
2204
2205 #if HAVE_LIBMOUNT
2206 r = mount_load_proc_self_mountinfo(m, true);
2207 if (r < 0) {
2208 /* Reset flags, just in case, for later calls */
2209 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_MOUNT])
2210 MOUNT(u)->proc_flags = 0;
2211
2212 return 0;
2213 }
2214
2215 manager_dispatch_load_queue(m);
2216
2217 _cleanup_set_free_ Set *around = NULL, *gone = NULL;
2218
2219 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_MOUNT]) {
2220 Mount *mount = MOUNT(u);
2221
2222 if (!mount_is_mounted(mount)) {
2223
2224 /* A mount point is not around right now. It might be gone, or might never have
2225 * existed. */
2226
2227 if (mount->from_proc_self_mountinfo &&
2228 mount->parameters_proc_self_mountinfo.what)
2229 /* Remember that this device might just have disappeared */
2230 if (set_put_strdup_full(&gone, &path_hash_ops_free, mount->parameters_proc_self_mountinfo.what) < 0)
2231 log_oom(); /* we don't care too much about OOM here... */
2232
2233 mount->from_proc_self_mountinfo = false;
2234 assert_se(update_parameters_proc_self_mountinfo(mount, NULL, NULL, NULL) >= 0);
2235
2236 switch (mount->state) {
2237
2238 case MOUNT_MOUNTED:
2239 /* This has just been unmounted by somebody else, follow the state change.
2240 * Also explicitly override the result (see the comment in mount_sigchld_event()),
2241 * but more aggressively here since the state change is extrinsic. */
2242 mount_cycle_clear(mount);
2243 mount_enter_dead(mount, MOUNT_SUCCESS, /* flush_result= */ true);
2244 break;
2245
2246 case MOUNT_MOUNTING_DONE:
2247 /* The mount command may add the corresponding proc mountinfo entry and
2248 * then remove it because of an internal error. E.g., fuse.sshfs seems
2249 * to do that when the connection fails. See #17617. To handle such the
2250 * case, let's once set the state back to mounting. Then, the unit can
2251 * correctly enter the failed state later in mount_sigchld_event(). */
2252 mount_set_state(mount, MOUNT_MOUNTING);
2253 break;
2254
2255 default:
2256 ;
2257 }
2258
2259 } else if (mount->proc_flags & (MOUNT_PROC_JUST_MOUNTED|MOUNT_PROC_JUST_CHANGED)) {
2260
2261 /* A mount point was added or changed */
2262
2263 switch (mount->state) {
2264
2265 case MOUNT_DEAD:
2266 case MOUNT_FAILED:
2267
2268 /* This has just been mounted by somebody else, follow the state change, but let's
2269 * generate a new invocation ID for this implicitly and automatically. */
2270 (void) unit_acquire_invocation_id(u);
2271 mount_cycle_clear(mount);
2272 mount_enter_mounted(mount, MOUNT_SUCCESS);
2273 break;
2274
2275 case MOUNT_MOUNTING:
2276 mount_set_state(mount, MOUNT_MOUNTING_DONE);
2277 break;
2278
2279 default:
2280 /* Nothing really changed, but let's issue an notification call nonetheless,
2281 * in case somebody is waiting for this. (e.g. file system ro/rw
2282 * remounts.) */
2283 mount_set_state(mount, mount->state);
2284 }
2285 }
2286
2287 if (mount_is_mounted(mount) &&
2288 mount->from_proc_self_mountinfo &&
2289 mount->parameters_proc_self_mountinfo.what)
2290 /* Track devices currently used */
2291 if (set_put_strdup_full(&around, &path_hash_ops_free, mount->parameters_proc_self_mountinfo.what) < 0)
2292 log_oom();
2293
2294 /* Reset the flags for later calls */
2295 mount->proc_flags = 0;
2296 }
2297
2298 const char *what;
2299 SET_FOREACH(what, gone) {
2300 if (set_contains(around, what))
2301 continue;
2302
2303 /* Let the device units know that the device is no longer mounted */
2304 device_found_node(m, what, DEVICE_NOT_FOUND, DEVICE_FOUND_MOUNT);
2305 }
2306
2307 return 0;
2308 #else
2309 assert_not_reached();
2310 #endif
2311 }
2312
2313 #if HAVE_LIBMOUNT
2314 static int mount_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2315 Manager *m = ASSERT_PTR(userdata);
2316
2317 assert(revents & EPOLLIN);
2318
2319 return mount_process_proc_self_mountinfo(m);
2320 }
2321 #endif
2322
2323 static void mount_reset_failed(Unit *u) {
2324 Mount *m = MOUNT(u);
2325
2326 assert(m);
2327
2328 if (m->state == MOUNT_FAILED)
2329 mount_set_state(m, MOUNT_DEAD);
2330
2331 m->result = MOUNT_SUCCESS;
2332 m->reload_result = MOUNT_SUCCESS;
2333 m->clean_result = MOUNT_SUCCESS;
2334 }
2335
2336 static PidRef* mount_control_pid(Unit *u) {
2337 return &ASSERT_PTR(MOUNT(u))->control_pid;
2338 }
2339
2340 static int mount_clean(Unit *u, ExecCleanMask mask) {
2341 _cleanup_strv_free_ char **l = NULL;
2342 Mount *m = MOUNT(u);
2343 int r;
2344
2345 assert(m);
2346 assert(mask != 0);
2347
2348 if (m->state != MOUNT_DEAD)
2349 return -EBUSY;
2350
2351 r = exec_context_get_clean_directories(&m->exec_context, u->manager->prefix, mask, &l);
2352 if (r < 0)
2353 return r;
2354
2355 if (strv_isempty(l))
2356 return -EUNATCH;
2357
2358 mount_unwatch_control_pid(m);
2359 m->clean_result = MOUNT_SUCCESS;
2360 m->control_command = NULL;
2361 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
2362
2363 r = mount_arm_timer(m, /* relative= */ true, m->exec_context.timeout_clean_usec);
2364 if (r < 0) {
2365 log_unit_warning_errno(u, r, "Failed to install timer: %m");
2366 goto fail;
2367 }
2368
2369 r = unit_fork_and_watch_rm_rf(u, l, &m->control_pid);
2370 if (r < 0) {
2371 log_unit_warning_errno(u, r, "Failed to spawn cleaning task: %m");
2372 goto fail;
2373 }
2374
2375 mount_set_state(m, MOUNT_CLEANING);
2376 return 0;
2377
2378 fail:
2379 m->clean_result = MOUNT_FAILURE_RESOURCES;
2380 m->timer_event_source = sd_event_source_disable_unref(m->timer_event_source);
2381 return r;
2382 }
2383
2384 static int mount_can_clean(Unit *u, ExecCleanMask *ret) {
2385 Mount *m = ASSERT_PTR(MOUNT(u));
2386
2387 return exec_context_get_clean_mask(&m->exec_context, ret);
2388 }
2389
2390 static int mount_test_startable(Unit *u) {
2391 Mount *m = ASSERT_PTR(MOUNT(u));
2392 int r;
2393
2394 /* It is already being started. */
2395 if (IN_SET(m->state, MOUNT_MOUNTING, MOUNT_MOUNTING_DONE))
2396 return false;
2397
2398 r = unit_test_start_limit(u);
2399 if (r < 0) {
2400 mount_enter_dead(m, MOUNT_FAILURE_START_LIMIT_HIT, /* flush_result= */ false);
2401 return r;
2402 }
2403
2404 if (!get_mount_parameters_fragment(m))
2405 return -ENOENT;
2406
2407 return true;
2408 }
2409
2410 static bool mount_supported(void) {
2411 return DLOPEN_LIBMOUNT(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED) >= 0;
2412 }
2413
2414 static int mount_subsystem_ratelimited(Manager *m) {
2415 assert(m);
2416
2417 if (!m->mount_event_source)
2418 return false;
2419
2420 return sd_event_source_is_ratelimited(m->mount_event_source);
2421 }
2422
2423 char* mount_get_where_escaped(const Mount *m) {
2424 assert(m);
2425
2426 if (!m->where)
2427 return strdup("");
2428
2429 return utf8_escape_invalid(m->where);
2430 }
2431
2432 char* mount_get_what_escaped(const Mount *m) {
2433 const char *s = NULL;
2434
2435 assert(m);
2436
2437 if (m->from_proc_self_mountinfo && m->parameters_proc_self_mountinfo.what)
2438 s = m->parameters_proc_self_mountinfo.what;
2439 else if (m->from_fragment && m->parameters_fragment.what)
2440 s = m->parameters_fragment.what;
2441 if (!s)
2442 return strdup("");
2443
2444 return utf8_escape_invalid(s);
2445 }
2446
2447 char* mount_get_options_escaped(const Mount *m) {
2448 const char *s = NULL;
2449
2450 assert(m);
2451
2452 if (m->from_proc_self_mountinfo && m->parameters_proc_self_mountinfo.options)
2453 s = m->parameters_proc_self_mountinfo.options;
2454 else if (m->from_fragment && m->parameters_fragment.options)
2455 s = m->parameters_fragment.options;
2456 if (!s)
2457 return strdup("");
2458
2459 return utf8_escape_invalid(s);
2460 }
2461
2462 const char* mount_get_fstype(const Mount *m) {
2463 assert(m);
2464
2465 if (m->from_proc_self_mountinfo && m->parameters_proc_self_mountinfo.fstype)
2466 return m->parameters_proc_self_mountinfo.fstype;
2467
2468 if (m->from_fragment && m->parameters_fragment.fstype)
2469 return m->parameters_fragment.fstype;
2470
2471 return NULL;
2472 }
2473
2474 static const char* const mount_exec_command_table[_MOUNT_EXEC_COMMAND_MAX] = {
2475 [MOUNT_EXEC_MOUNT] = "ExecMount",
2476 [MOUNT_EXEC_UNMOUNT] = "ExecUnmount",
2477 [MOUNT_EXEC_REMOUNT] = "ExecRemount",
2478 };
2479
2480 DEFINE_STRING_TABLE_LOOKUP(mount_exec_command, MountExecCommand);
2481
2482 static const char* const mount_result_table[_MOUNT_RESULT_MAX] = {
2483 [MOUNT_SUCCESS] = "success",
2484 [MOUNT_FAILURE_RESOURCES] = "resources",
2485 [MOUNT_FAILURE_TIMEOUT] = "timeout",
2486 [MOUNT_FAILURE_EXIT_CODE] = "exit-code",
2487 [MOUNT_FAILURE_SIGNAL] = "signal",
2488 [MOUNT_FAILURE_CORE_DUMP] = "core-dump",
2489 [MOUNT_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
2490 [MOUNT_FAILURE_PROTOCOL] = "protocol",
2491 };
2492
2493 DEFINE_STRING_TABLE_LOOKUP(mount_result, MountResult);
2494
2495 const UnitVTable mount_vtable = {
2496 .object_size = sizeof(Mount),
2497 .exec_context_offset = offsetof(Mount, exec_context),
2498 .cgroup_context_offset = offsetof(Mount, cgroup_context),
2499 .kill_context_offset = offsetof(Mount, kill_context),
2500 .exec_runtime_offset = offsetof(Mount, exec_runtime),
2501 .cgroup_runtime_offset = offsetof(Mount, cgroup_runtime),
2502
2503 .sections =
2504 "Unit\0"
2505 "Mount\0"
2506 "Install\0",
2507 .private_section = "Mount",
2508
2509 .can_transient = true,
2510 .can_fail = true,
2511 .exclude_from_switch_root_serialization = true,
2512 .notify_plymouth = true,
2513 .track_orphaned = true,
2514
2515 .init = mount_init,
2516 .load = mount_load,
2517 .done = mount_done,
2518
2519 .coldplug = mount_coldplug,
2520 .catchup = mount_catchup,
2521
2522 .dump = mount_dump,
2523
2524 .start = mount_start,
2525 .stop = mount_stop,
2526
2527 .reload = mount_reload,
2528 .can_reload = mount_can_reload,
2529
2530 .clean = mount_clean,
2531 .can_clean = mount_can_clean,
2532
2533 .serialize = mount_serialize,
2534 .deserialize_item = mount_deserialize_item,
2535
2536 .active_state = mount_active_state,
2537 .sub_state_to_string = mount_sub_state_to_string,
2538
2539 .will_restart = unit_will_restart_default,
2540
2541 .may_gc = mount_may_gc,
2542 .is_extrinsic = mount_is_extrinsic,
2543
2544 .sigchld_event = mount_sigchld_event,
2545
2546 .reset_failed = mount_reset_failed,
2547
2548 .notify_handoff_timestamp = mount_handoff_timestamp,
2549
2550 .control_pid = mount_control_pid,
2551
2552 .bus_set_property = bus_mount_set_property,
2553 .bus_commit_properties = bus_mount_commit_properties,
2554
2555 .get_timeout = mount_get_timeout,
2556
2557 .enumerate_perpetual = mount_enumerate_perpetual,
2558 .enumerate = mount_enumerate,
2559 .shutdown = mount_shutdown,
2560 .supported = mount_supported,
2561 .subsystem_ratelimited = mount_subsystem_ratelimited,
2562
2563 .status_message_formats = {
2564 .starting_stopping = {
2565 [0] = "Mounting %s...",
2566 [1] = "Unmounting %s...",
2567 },
2568 .finished_start_job = {
2569 [JOB_DONE] = "Mounted %s.",
2570 [JOB_FAILED] = "Failed to mount %s.",
2571 [JOB_TIMEOUT] = "Timed out mounting %s.",
2572 },
2573 .finished_stop_job = {
2574 [JOB_DONE] = "Unmounted %s.",
2575 [JOB_FAILED] = "Failed unmounting %s.",
2576 [JOB_TIMEOUT] = "Timed out unmounting %s.",
2577 },
2578 },
2579
2580 .test_startable = mount_test_startable,
2581 };