lib/efi: Cleanup read/write routines
[petitboot] / discover / dt.c
1 #include <asm/byteorder.h>
2 #include <dirent.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <sys/types.h>
6
7 #include <talloc/talloc.h>
8 #include <file/file.h>
9
10 #include "dt.h"
11
12 static int filter_sensors(const struct dirent *ent)
13 {
14         /* Check for prefix "sensor@" */
15         return strncmp(ent->d_name, "sensor@", strlen("sensor@")) == 0;
16 }
17
18 int get_ipmi_sensor(void *t, enum ipmi_sensor_ids sensor_id)
19 {
20         int rc, len, n;
21         struct dirent **namelist;
22         char *buf, *filename;
23         const char sensor_dir[] = "/proc/device-tree/bmc/sensors/";
24
25         n = scandir(sensor_dir, &namelist, filter_sensors, alphasort);
26         if (n <= 0)
27                 return -1;
28
29         while (n--) {
30                 filename = talloc_asprintf(t, "%s%s/ipmi-sensor-type",
31                                            sensor_dir, namelist[n]->d_name);
32                 rc = read_file(t, filename, &buf, &len);
33                 if (rc == 0 && len == 4 &&
34                     __be32_to_cpu(*(uint32_t *)buf) == sensor_id)
35                                 break;
36                 free(namelist[n]);
37         }
38         if (n < 0) {
39                 rc = -1;
40                 goto out;
41         }
42
43         filename = talloc_asprintf(t, "%s%s/reg", sensor_dir,
44                                    namelist[n]->d_name);
45         /* Free the rest of the scandir strings, if there are any */
46         do {
47                 free(namelist[n]);
48         } while (n-- > 0);
49
50         rc = read_file(t, filename, &buf, &len);
51         if (rc != 0 || len != 4) {
52                 rc = -1;
53                 goto out;
54         }
55
56         rc = __be32_to_cpu(*(uint32_t *)buf);
57
58 out:
59         talloc_free(buf);
60         free(namelist);
61         return rc;
62 }