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