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