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