+static int setup_volatile_state(const char *directory) {
+ const char *p;
+ int r;
+
+ assert(directory);
+
+ if (arg_volatile != VOLATILE_STATE)
+ return 0;
+
+ /* --volatile=state means we simply overmount /var
+ with a tmpfs, and the rest read-only. */
+
+ r = bind_remount_recursive(directory, true);
+ if (r < 0) {
+ log_error("Failed to remount %s read-only: %s", directory, strerror(-r));
+ return r;
+ }
+
+ p = strappenda(directory, "/var");
+ mkdir(p, 0755);
+
+ if (mount("tmpfs", p, "tmpfs", MS_STRICTATIME, "mode=755") < 0) {
+ log_error("Failed to mount tmpfs to /var: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int setup_volatile(const char *directory) {
+ bool tmpfs_mounted = false, bind_mounted = false;
+ char template[] = "/tmp/nspawn-volatile-XXXXXX";
+ const char *f, *t;
+ int r;
+
+ assert(directory);
+
+ if (arg_volatile != VOLATILE_YES)
+ return 0;
+
+ /* --volatile=yes means we mount a tmpfs to the root dir, and
+ the original /usr to use inside it, and that read-only. */
+
+ if (!mkdtemp(template)) {
+ log_error("Failed to create temporary directory: %m");
+ return -errno;
+ }
+
+ if (mount("tmpfs", template, "tmpfs", MS_STRICTATIME, "mode=755") < 0) {
+ log_error("Failed to mount tmpfs for root directory: %m");
+ r = -errno;
+ goto fail;
+ }
+
+ tmpfs_mounted = true;
+
+ f = strappenda(directory, "/usr");
+ t = strappenda(template, "/usr");
+
+ mkdir(t, 0755);
+ if (mount(f, t, "bind", MS_BIND|MS_REC, NULL) < 0) {
+ log_error("Failed to create /usr bind mount: %m");
+ r = -errno;
+ goto fail;
+ }
+
+ bind_mounted = true;
+
+ r = bind_remount_recursive(t, true);
+ if (r < 0) {
+ log_error("Failed to remount %s read-only: %s", t, strerror(-r));
+ goto fail;
+ }
+
+ if (mount(template, directory, NULL, MS_MOVE, NULL) < 0) {
+ log_error("Failed to move root mount: %m");
+ r = -errno;
+ goto fail;
+ }
+
+ rmdir(template);
+
+ return 0;
+
+fail:
+ if (bind_mounted)
+ umount(t);
+ if (tmpfs_mounted)
+ umount(template);
+ rmdir(template);
+ return r;
+}
+