blob: c32b407c16fe386e568953f53e8cd17736ab9fd4 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
Mateusz Zalega43e21072021-10-08 18:05:29 +02002// SPDX-License-Identifier: Apache-2.0
Mateusz Zalega43e21072021-10-08 18:05:29 +02003
4// Implementation included in this file was written with the aim of easing
5// integration with the interface exposed at /sys/class/block. It assumes sysfs
6// is already mounted at /sys.
7package sysfs
8
9import (
Lorenz Brun57d06a72022-01-13 14:12:27 +010010 "errors"
Mateusz Zalega43e21072021-10-08 18:05:29 +020011 "fmt"
12 "os"
13 "path/filepath"
14 "strconv"
15 "strings"
Lorenz Brunca9cfcf2023-05-02 19:29:14 +020016
17 "github.com/google/uuid"
Mateusz Zalega43e21072021-10-08 18:05:29 +020018)
19
20// PartUUIDMap returns a mapping between partition UUIDs and block device
21// names based on information exposed by uevent. UUID keys of the returned
22// map are represented as lowercase strings.
23func PartUUIDMap() (map[string]string, error) {
24 m := make(map[string]string)
25 // Get a list of block device symlinks from sysfs.
26 const blkDirPath = "/sys/class/block"
27 blkDevs, err := os.ReadDir(blkDirPath)
28 if err != nil {
29 return m, fmt.Errorf("couldn't read %q: %w", blkDirPath, err)
30 }
31 // Iterate over block device symlinks present in blkDevs, creating a mapping
32 // in m for each device with both PARTUUID and DEVNAME keys present in their
33 // respective uevent files.
34 for _, devInfo := range blkDevs {
35 // Read the uevent file and transform it into a string->string map.
36 kv, err := ReadUevents(filepath.Join(blkDirPath, devInfo.Name(), "uevent"))
37 if err != nil {
38 return m, fmt.Errorf("while reading uevents: %w", err)
39 }
40 // Check that the required keys are present in the map.
41 if uuid, name := kv["PARTUUID"], kv["DEVNAME"]; uuid != "" && name != "" {
42 m[uuid] = name
43 }
44 }
45 return m, nil
46}
47
Lorenz Brun57d06a72022-01-13 14:12:27 +010048var ErrDevNotFound = errors.New("device not found")
49
Mateusz Zalega43e21072021-10-08 18:05:29 +020050// DeviceByPartUUID returns a block device name, given its corresponding
51// partition UUID.
Lorenz Brunca9cfcf2023-05-02 19:29:14 +020052func DeviceByPartUUID(id uuid.UUID) (string, error) {
Mateusz Zalega43e21072021-10-08 18:05:29 +020053 pm, err := PartUUIDMap()
54 if err != nil {
55 return "", err
56 }
Lorenz Brunca9cfcf2023-05-02 19:29:14 +020057 if bdev, ok := pm[id.String()]; ok {
Mateusz Zalega43e21072021-10-08 18:05:29 +020058 return bdev, nil
59 }
Lorenz Brun57d06a72022-01-13 14:12:27 +010060 return "", ErrDevNotFound
Mateusz Zalega43e21072021-10-08 18:05:29 +020061}
62
63// ParentBlockDevice transforms the block device name of a partition, eg
64// "sda1", to the name of the block device hosting it, eg "sda".
65func ParentBlockDevice(dev string) (string, error) {
66 // Build a path pointing to a sysfs block device symlink.
67 partLink := filepath.Join("/sys/class/block", dev)
68 // Read the symlink at partLink. This should leave us with a path of the form
69 // (...)/sda/sdaN.
70 linkTgt, err := os.Readlink(partLink)
71 if err != nil {
72 return "", fmt.Errorf("couldn't read the block device symlink at %q: %w", partLink, err)
73 }
74 // Remove the last element from the path, leaving us with a path pointing to
75 // the block device containting the installer partition, of the form
76 // (...)/sda.
77 devPath := filepath.Dir(linkTgt)
78 // Get the last element of the path, leaving us with just the block device
79 // name, eg sda
80 devName := filepath.Base(devPath)
81 return devName, nil
82}
83
84// PartitionBlockDevice returns the name of a block device associated with the
85// partition at index in the containing block device dev, eg "nvme0n1pN" for
86// "nvme0n1" or "sdaN" for "sda".
87func PartitionBlockDevice(dev string, index int) (string, error) {
88 dp := filepath.Join("/sys/class/block", dev)
89 dir, err := os.ReadDir(dp)
90 if err != nil {
91 return "", err
92 }
93 for _, info := range dir {
94 // Skip non-directories
95 if !info.IsDir() {
96 continue
97 }
98 // Check whether the directory contains a file named 'partition'. If that's
99 // the case, read the partition index from it and compare it with the one
100 // supplied as a function parameter. If they're equal, return the directory
101 // name.
102 istr, err := os.ReadFile(filepath.Join(dp, info.Name(), "partition"))
103 if os.IsNotExist(err) {
104 continue
105 }
106 if err != nil {
107 return "", err
108 }
109 // istr holds a newline-terminated ASCII-encoded decimal number.
110 pi, err := strconv.Atoi(strings.TrimSuffix(string(istr), "\n"))
111 if err != nil {
112 return "", fmt.Errorf("failed to parse partition index: %w", err)
113 }
114 if pi == index {
115 return info.Name(), nil
116 }
117 }
118 return "", fmt.Errorf("couldn't find partition %d of %q", index, dev)
119}