blob: d5c2ce43c8a472128cca2e0c8a4b0339f2e5b599 [file] [log] [blame]
Matt Spinler36df1972017-05-25 10:23:05 -05001/**
2 * Copyright © 2017 IBM Corporation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include <fcntl.h>
17#include <phosphor-logging/log.hpp>
18#include <sys/ioctl.h>
19#include "gpio.hpp"
20
21namespace phosphor
22{
23namespace gpio
24{
25
26using namespace phosphor::logging;
27
28void GPIO::set(Value value)
29{
30 assert(direction == Direction::output);
31
32 requestLine(value);
33
34 gpiohandle_data data{};
35 data.values[0] = static_cast<gpioValue_t>(value);
36
37 auto rc = ioctl(lineFD(), GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
38 if (rc == -1)
39 {
40 auto e = errno;
41 log<level::ERR>("Failed SET_LINE_VALUES ioctl",
42 entry("ERRNO=%d", e));
43 throw std::runtime_error("Failed SET_LINE_VALUES ioctl");
44 }
45}
46
47
48void GPIO::requestLine(Value defaultValue)
49{
50 //Only need to do this once
51 if (lineFD)
52 {
53 return;
54 }
55
56 FileDescriptor fd{open(device.c_str(), 0)};
57 if (fd() == -1)
58 {
59 auto e = errno;
60 log<level::ERR>("Failed opening GPIO device",
61 entry("DEVICE=%s", device),
62 entry("ERRNO=%d", e));
63 throw std::runtime_error("Failed opening GPIO device");
64 }
65
66 //Make an ioctl call to request the GPIO line, which will
67 //return the descriptor to use to access it.
68 gpiohandle_request request{};
69 strncpy(request.consumer_label,
70 "phosphor-gpio-util",
71 sizeof(request.consumer_label));
72
73 request.flags = (direction == Direction::output) ?
74 GPIOHANDLE_REQUEST_OUTPUT : GPIOHANDLE_REQUEST_INPUT;
75
76 request.lineoffsets[0] = gpio;
77 request.lines = 1;
78
79 if (direction == Direction::output)
80 {
81 request.default_values[0] = static_cast<gpioValue_t>(defaultValue);
82 }
83
84 auto rc = ioctl(fd(), GPIO_GET_LINEHANDLE_IOCTL, &request);
85 if (rc == -1)
86 {
87 auto e = errno;
88 log<level::ERR>("Failed GET_LINEHANDLE ioctl",
89 entry("GPIO=%d", gpio),
90 entry("ERRNO=%d", e));
91 throw std::runtime_error("Failed GET_LINEHANDLE ioctl");
92 }
93
94 lineFD.set(request.fd);
95}
96
97}
98}