func deleteContent(path string, rootDev uint64) error {
	var stat unix.Stat_t
	if err := unix.Lstat(path, &stat); err != nil {
		return err
	}
	if stat.Dev != rootDev {
		return nil
	}
	if fs.FileMode(stat.Mode).IsDir() {
		dirEntries, err := os.ReadDir(path)
		if err != nil {
			return err
		}
		for _, e := range dirEntries {
			if e.Name() == "." || e.Name() == ".." {
				continue
			}
			if err := deleteContent(filepath.Join(path, e.Name()), rootDev); err != nil {
				return err
			}
		}
	}
	if path != "/" {
		if err := os.Remove(path); err != nil {
			return fmt.Errorf("remove(%s): %v", path, err)
		}
	}
	return nil
}
deleteContent deletes content of the path recursively but without crossing mountpoints.
It checks that deleted files belong to the same device id (i.e. not a mountpoint).
package main
import (
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"
	"github.com/yookoala/realpath"
	"golang.org/x/sys/unix"
	"gopkg.in/yaml.v3"
)
const (
	newRoot    = "/booster.root"
	newInitBin = "/sbin/init"
)
var (
	cmdline = make(map[string]string)
	moduleParams = make(map[string][]string)
	rootMounting int32           
	rootMounted  sync.WaitGroup  
	cmdRoot   *deviceRef
	cmdResume *deviceRef
	luksMappings []luksMapping  
	rootAutodiscoveryMode       bool
	rootAutodiscoveryMountFlags uintptr  
	activeEfiEspGUID            UUID     
)
type set map[string]bool
func parseCmdline() error {
	b, err := os.ReadFile("/proc/cmdline")
	if err != nil {
		return err
	}
	parts := strings.Split(strings.TrimSpace(string(b)), " ")
	for _, part := range parts {
		if idx := strings.IndexByte(part, '='); idx > -1 {
			key, val := part[:idx], part[idx+1:]
			cmdline[key] = val
			if dot := strings.IndexByte(key, '.'); dot != -1 {
				mod, param := key[:dot], key[dot+1:]
				mod = normalizeModuleName(mod)
				moduleParams[mod] = append(moduleParams[mod], param+"="+val)
			}
		} else {
			cmdline[part] = ""
		}
	}
	if param, ok := cmdline["booster.log"]; ok {
		for _, p := range strings.Split(param, ",") {
			switch p {
			case "debug":
				verbosityLevel = levelDebug
			case "info":
				verbosityLevel = levelInfo
			case "warning":
				verbosityLevel = levelWarning
			case "error":
				verbosityLevel = levelError
			case "console":
				printToConsole = true
			default:
				warning("unknown booster.log key: %s", p)
			}
		}
	} else if _, ok := cmdline["booster.debug"]; ok {
		verbosityLevel = levelDebug
		printToConsole = true
	} else if _, ok := cmdline["quiet"]; ok {
		verbosityLevel = levelError
	}
	if verbosityLevel >= levelDebug {
		if err := disableKmsgThrottling(); err != nil {
			info("%v", err)
		}
	}
	if param, ok := cmdline["root"]; ok {
		cmdRoot, err = parseDeviceRef(param)
		if err != nil {
			return fmt.Errorf("root=%s: %v", param, err)
		}
	} else {
		rootUUIDType, ok := rootAutodiscoveryGptTypes[runtime.GOARCH]
		if !ok {
			return fmt.Errorf("root= boot option is not specified")
		}
		info("root= param is not specified. Use GPT partition autodiscovery with guid type %s", rootUUIDType)
		gptType, err := parseUUID(rootUUIDType)
		if err != nil {
			return err
		}
		activeEfiEspGUID, err = getActiveEfiEsp()
		if err != nil {
			return fmt.Errorf("unable to detect active ESP: %v", err)
		}
		rootAutodiscoveryMode = true
		cmdRoot = &deviceRef{refGptType, gptType}
	}
	if param, ok := cmdline["resume"]; ok {
		cmdResume, err = parseDeviceRef(param)
		if err != nil {
			return fmt.Errorf("resume=%s: %v", param, err)
		}
	}
	var luksOptions []string
	if param, ok := cmdline["rd.luks.options"]; ok {
		for _, o := range strings.Split(param, ",") {
			flag, ok := rdLuksOptions[o]
			if !ok {
				return fmt.Errorf("unknown value in rd.luks.options: %v", o)
			}
			luksOptions = append(luksOptions, flag)
		}
	}
	if param, ok := cmdline["rd.luks.name"]; ok {
		parts := strings.Split(param, "=")
		if len(parts) != 2 {
			return fmt.Errorf("invalid rd.luks.name kernel parameter %s, expected format rd.luks.name=<UUID>=<name>", cmdline["rd.luks.name"])
		}
		uuid, err := parseUUID(stripQuotes(parts[0]))
		if err != nil {
			return fmt.Errorf("invalid UUID %s %v", parts[0], err)
		}
		dev := luksMapping{
			ref:     &deviceRef{refFsUUID, uuid},
			name:    parts[1],
			options: luksOptions,
		}
		luksMappings = append(luksMappings, dev)
	} else if uuid, ok := cmdline["rd.luks.uuid"]; ok {
		stripped := stripQuotes(uuid)
		u, err := parseUUID(stripped)
		if err != nil {
			return fmt.Errorf("invalid UUID %s in rd.luks.uuid boot param: %v", uuid, err)
		}
		dev := luksMapping{
			ref:     &deviceRef{refFsUUID, u},
			name:    "luks-" + stripped,
			options: luksOptions,
		}
		luksMappings = append(luksMappings, dev)
	}
	return nil
}
func getActiveEfiEsp() (UUID, error) {
	_, data, err := readEfiVar("LoaderDevicePartUUID", "4a67b082-0a4c-41cf-b6c7-440b29bb8c4f")
	if err != nil {
		return nil, err
	}
	uuid := fromUnicode16(data, binary.LittleEndian)
	return parseUUID(uuid)
}
func readEfiVar(name, uuid string) (uint32, []byte, error) {
	data, err := os.ReadFile("/sys/firmware/efi/efivars/" + name + "-" + uuid)
	if err != nil {
		return 0, nil, err
	}
	attribute := binary.LittleEndian.Uint32(data[:4])
	data = data[4:]
	return attribute, data, nil
}
var (
	devicesMutex sync.Mutex
	seenDevices       = make(set)  
	processingDevices = make(map[string]*sync.WaitGroup)
	partitionTables   = make(map[string]string)  
)
func addTableNameForDevice(devPath string, tablePath string) {
	devicesMutex.Lock()
	partitionTables[devPath] = tablePath
	devicesMutex.Unlock()
}
func waitForTableToProcess(dev string) {
	devicesMutex.Lock()
	table, ok := partitionTables[dev]
	if !ok {
		devicesMutex.Unlock()
		return
	}
	wg, ok := processingDevices[table]
	if !ok {
		devicesMutex.Unlock()
		return
	}
	devicesMutex.Unlock()
	wg.Wait()
}
func markDeviceProcessed(dev string) {
	devicesMutex.Lock()
	defer devicesMutex.Unlock()
	wg := processingDevices[dev]
	wg.Done()
	delete(processingDevices, dev)
}
func addBlockDevice(devpath string, symlinks []string) error {
	devicesMutex.Lock()
	if _, alreadyAdded := seenDevices[devpath]; alreadyAdded {
		devicesMutex.Unlock()
		return nil
	}
	wg := &sync.WaitGroup{}
	wg.Add(1)
	processingDevices[devpath] = wg
	devicesMutex.Unlock()
	defer markDeviceProcessed(devpath)
	info("found a new device %s", devpath)
	blk, err := readBlkInfo(devpath)
	if err == errUnknownBlockType {
		blk = &blkInfo{
			path: devpath,
		}
		err = nil
	}
	if err != nil {
		return fmt.Errorf("%s: %v", devpath, err)
	}
	blk.symlinks = symlinks
	switch blk.format {
	case "luks":
		return handleLuksBlockDevice(blk)
	case "lvm":
		return handleLvmBlockDevice(blk)
	case "mdraid":
		return handleMdraidBlockDevice(blk)
	case "gpt":
		return handleGptBlockDevice(blk)
	}
	if cmdResume != nil {
		if cmdResume.dependsOnGpt() {
			waitForTableToProcess(devpath)
		}
		if cmdResume.matchesBlkInfo(blk) {
			if err := resume(devpath); err != nil {
				return err
			}
		}
	}
	if cmdRoot.dependsOnGpt() {
		waitForTableToProcess(devpath)
	}
	if cmdRoot.matchesBlkInfo(blk) {
		if blk.format == "" && cmdline["rootfstype"] != "" {
			blk.format = cmdline["rootfstype"]
			blk.isFs = true
		}
		if blk.format == "" {
			return fmt.Errorf("unable to detect filesystem type for device %s and no 'rootfstype' boot parameter specified", devpath)
		}
		if !blk.isFs {
			return fmt.Errorf("specified root %s has type %s and cannot be mounted as a filesystem", devpath, blk.format)
		}
		return mountRootFs(devpath, blk.format)
	}
	return nil
}
func handleGptBlockDevice(blk *blkInfo) error {
	gpt := blk.data.(gptData)
	if rootAutodiscoveryMode {
		if gpt.containsEsp() {
			info("%s table contains active ESP, use it to discover root", blk.path)
			cmdRoot.resolveGptRef(blk.path, gpt)
		}
	} else {
		cmdRoot.resolveGptRef(blk.path, gpt)
	}
	if cmdResume != nil {
		cmdResume.resolveGptRef(blk.path, gpt)
	}
	for _, m := range luksMappings {
		m.ref.resolveGptRef(blk.path, gpt)
	}
	return nil
}
var raidModules = map[uint32]string{
	levelMultipath: "multipath",
	levelLinear:    "linear",
	levelRaid0:     "raid0",
	levelRaid1:     "raid1",
	levelRaid4:     "raid456",
	levelRaid5:     "raid456",
	levelRaid6:     "raid456",
	levelRaid10:    "raid10",
}
func handleMdraidBlockDevice(blk *blkInfo) error {
	if !config.EnableMdraid {
		info("MdRaid support is disabled, ignoring mdraid device %s", blk.path)
		return nil
	}
	info("trying to assemble mdraid array %s", blk.uuid.toString())
	if mod, ok := raidModules[blk.data.(mdraidData).level]; ok {
		wg, err := loadModules(mod)
		if err != nil {
			return err
		}
		wg.Wait()
	} else {
		return fmt.Errorf("unknown raid level for device %s", blk.path)
	}
	out, err := exec.Command("mdadm", "--export", "--incremental", blk.path).CombinedOutput()
	if err != nil {
		return err
	}
	props := parseProperties(string(out))
	arrayName, hasArrayName := props["MD_DEVNAME"]
	if !hasArrayName {
		return fmt.Errorf("mdraid array at %s does not have a MD_DEVNAME property", blk.uuid.toString())
	}
	if started, ok := props["MD_STARTED"]; !ok || started != "yes" {
		info("mdraid array %s is not complete, ignore it", arrayName)
		return nil
	}
	return addBlockDevice("/dev/md/"+arrayName, nil)
}
func handleLvmBlockDevice(blk *blkInfo) error {
	if !config.EnableLVM {
		info("LVM support is disabled, ignoring lvm physical volume %s", blk.path)
		return nil
	}
	info("scanning lvm physical volume %s", blk.path)
	cmd := exec.Command("lvm", "pvscan", "--cache", "-aay", blk.path)
	if verbosityLevel >= levelDebug {
		cmd.Stderr = os.Stderr
		cmd.Stdout = os.Stdout
	}
	return cmd.Run()
}
func resume(devpath string) error {
	devNo, err := deviceNo(devpath)
	if err != nil {
		return err
	}
	major := unix.Major(devNo)
	minor := unix.Minor(devNo)
	info("resuming device %s, devno=(%d,%d)", devpath, major, minor)
	rd := fmt.Sprintf("%d:%d", major, minor)
	return os.WriteFile("/sys/power/resume", []byte(rd), 0644)
}
func fsck(dev string) error {
	if _, err := os.Stat("/usr/bin/fsck"); !os.IsNotExist(err) {
		cmd := exec.Command("/usr/bin/fsck", "-y", dev)
		if verbosityLevel >= levelDebug {
			cmd.Stderr = os.Stderr
			cmd.Stdout = os.Stdout
		}
		if err := cmd.Run(); err != nil {
			if err, ok := err.(*exec.ExitError); ok {
				code := err.ExitCode()
				code &^= 0x1  
				if code != 0 {
					return fmt.Errorf("fsck for %s failed with code 0x%x", dev, err.ExitCode())
				}
			}
			return fmt.Errorf("fsck for %s: unknown error %v", dev, err)
		}
	}
	return nil
}
func mountRootFs(dev, fstype string) error {
	if !atomic.CompareAndSwapInt32(&rootMounting, 0, 1) {
		return nil  
	}
	wg, err := loadModules(fstype)
	if err != nil {
		return err
	}
	wg.Wait()
	if err := fsck(dev); err != nil {
		return err
	}
	rootMountFlags, options := sunderMountFlags(cmdline["rootflags"], rootAutodiscoveryMountFlags)
	if _, ro := cmdline["ro"]; ro {
		rootMountFlags |= unix.MS_RDONLY
	}
	if _, rw := cmdline["rw"]; rw {
		rootMountFlags &^= unix.MS_RDONLY
	}
	info("mounting %s->%s, fs=%s, flags=0x%x, options=%s", dev, newRoot, fstype, rootMountFlags, options)
	if err := mount(dev, newRoot, fstype, rootMountFlags, options); err != nil {
		return err
	}
	rootMounted.Done()
	return nil
}
func sunderMountFlags(options string, flags uintptr) (uintptr, string) {
	var outOptions []string
	for _, o := range strings.Split(options, ",") {
		switch o {
		case "dirsync":
			flags |= unix.MS_DIRSYNC
		case "lazytime":
			flags |= unix.MS_LAZYTIME
		case "nolazytime":
			flags &^= unix.MS_LAZYTIME
		case "noatime":
			flags |= unix.MS_NOATIME
		case "atime":
			flags &^= unix.MS_NOATIME
		case "nodev":
			flags |= unix.MS_NODEV
		case "dev":
			flags &^= unix.MS_NODEV
		case "nodiratime":
			flags |= unix.MS_NODIRATIME
		case "diratime":
			flags &^= unix.MS_NODIRATIME
		case "noexec":
			flags |= unix.MS_NOEXEC
		case "exec":
			flags &^= unix.MS_NOEXEC
		case "nosuid":
			flags |= unix.MS_NOSUID
		case "suid":
			flags &^= unix.MS_NOSUID
		case "ro":
			flags |= unix.MS_RDONLY
		case "rw":
			flags &^= unix.MS_RDONLY
		case "relatime":
			flags |= unix.MS_RELATIME
		case "norelatime":
			flags &^= unix.MS_RELATIME
		case "silent":
			flags |= unix.MS_SILENT
		case "strictatime":
			flags |= unix.MS_STRICTATIME
		case "nostrictatime":
			flags &^= unix.MS_STRICTATIME
		case "sync":
			flags |= unix.MS_SYNC
		case "async":
			flags &^= unix.MS_SYNC
		case "nosymfollow":
			flags |= unix.MS_NOSYMFOLLOW
		default:
			outOptions = append(outOptions, o)
		}
	}
	return flags, strings.Join(outOptions, ",")
}
func isSystemd(path string) (bool, error) {
	myRealpath, err := realpath.Realpath(path)
	if err != nil {
		return false, err
	}
	return strings.HasSuffix(myRealpath, "/systemd"), nil
}
func moveMountpointsToHost() error {
	for _, m := range []string{"/run", "/dev", "/proc", "/sys"} {
		_, err := os.Stat(newRoot + m)
		if os.IsNotExist(err) {
			warning("%s does not exist at the newly mounted root filesystem", m)
			if err := unix.Unmount(m, unix.MNT_DETACH); err != nil {
				return fmt.Errorf("unmount(%s): %v", m, err)
			}
			continue
		}
		if err := unix.Mount(m, newRoot+m, "", unix.MS_MOVE, ""); err != nil {
			return fmt.Errorf("move %s to new root: %v", m, err)
		}
	}
	return nil
}