pass-hal: tm2: Add implementation of HAL for CPU
[platform/adaptation/tm2/pass-hal-tm2.git] / src / shared / sysfs.c
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <unistd.h>
7
8 #include "sysfs.h"
9
10 static int sysfs_read_buf(char *path, char *buf, int len)
11 {
12         int r, fd;
13
14         if ((!path) || (!buf) || (len < 0))
15                 return -EINVAL;
16
17         fd = open(path, O_RDONLY);
18         if (fd == -1)
19                 return -ENOENT;
20
21         r = read(fd, buf, len + 1);
22         close(fd);
23
24         if ((r < 0) || (r > len))
25                 return -EIO;
26
27         buf[r] = '\0';
28
29         return 0;
30 }
31
32 static int sysfs_write_buf(char *path, char *buf)
33 {
34         int w, fd;
35
36         if ((!path) || (!buf))
37                 return -EINVAL;
38
39         fd = open(path, O_WRONLY);
40         if (fd == -1)
41                 return -ENOENT;
42
43         w = write(fd, buf, strlen(buf));
44         close(fd);
45
46         if (w < 0)
47                 return -EIO;
48
49         return 0;
50 }
51
52 int sysfs_read_int(char *path, int *val)
53 {
54         char buf[MAX_BUF_SIZE];
55         int r;
56
57         if ((!path) || (!val))
58                 return -EINVAL;
59
60         r = sysfs_read_buf(path, buf, MAX_BUF_SIZE);
61         if (r < 0)
62                 return r;
63
64         *val = atoi(buf);
65         return 0;
66 }
67
68 int sysfs_read_str(char *path, char *str, int len)
69 {
70         int r;
71
72         if ((!path) || (!str) || (len <= 0))
73                 return -EINVAL;
74
75         r = sysfs_read_buf(path, str, len);
76         if (r < 0)
77                 return r;
78
79         return 0;
80 }
81
82 int sysfs_write_int(char *path, int val)
83 {
84         char buf[MAX_BUF_SIZE];
85         int w;
86
87         if (!path)
88                 return -EINVAL;
89
90         snprintf(buf, MAX_BUF_SIZE, "%d", val);
91         w = sysfs_write_buf(path, buf);
92         if (w < 0)
93                 return w;
94
95         return 0;
96 }
97
98 int sysfs_write_str(char *path, char *str)
99 {
100         int w;
101
102         if ((!path) || (!str))
103                 return -EINVAL;
104
105         w = sysfs_write_buf(path, str);
106         if (w < 0)
107                 return w;
108
109         return 0;
110 }