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