1 /* Copyright 2013-2014 Google Corp.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * 	http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12  * implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <stdint.h>
17 #include "ec/config.h"
18 #include "ec/gpio.h"
19 
ec_gpio_setup(EcGpioPort port,uint8_t pin,int is_output,int pullup_enable)20 int ec_gpio_setup(EcGpioPort port, uint8_t pin,
21                   int is_output, int pullup_enable)
22 {
23     uint8_t ddr_reg;
24     if (pin > 7) {
25         return -1;
26     }
27 
28     /* Set data direction */
29     ec_outb(EC_GPIO_INDEX,
30             port * EC_GPIO_PORT_SKIP + EC_GPIO_DDR_OFFSET);
31     ddr_reg = ec_inb(EC_GPIO_DATA);
32     if (is_output) {
33         ddr_reg |= (1 << pin);
34     } else {
35         ddr_reg &= ~(1 << pin);
36     }
37     ec_outb(EC_GPIO_DATA, ddr_reg);
38 
39     /* Set pullup enable for output GPOs */
40     if (is_output)
41     {
42         uint8_t pup_reg;
43         ec_outb(EC_GPIO_INDEX,
44                 port * EC_GPIO_PORT_SKIP + EC_GPIO_PUP_OFFSET);
45         pup_reg = ec_inb(EC_GPIO_DATA);
46         if (pullup_enable) {
47             pup_reg |= (1 << pin);
48         } else {
49             pup_reg &= ~(1 << pin);
50         }
51         ec_outb(EC_GPIO_DATA, pup_reg);
52     }
53 
54     return 0;
55 }
56 
ec_gpio_read(EcGpioPort port,uint8_t pin)57 int ec_gpio_read(EcGpioPort port, uint8_t pin)
58 {
59     uint8_t pin_reg;
60     if (pin > 7) {
61         return -1;
62     }
63 
64     ec_outb(EC_GPIO_INDEX,
65             port * EC_GPIO_PORT_SKIP + EC_GPIO_PIN_OFFSET);
66     pin_reg = ec_inb(EC_GPIO_DATA);
67     return !!(pin_reg & (1 << pin));
68 }
69 
ec_gpio_set(EcGpioPort port,uint8_t pin,int val)70 int ec_gpio_set(EcGpioPort port, uint8_t pin, int val)
71 {
72     uint8_t data_reg;
73     if (pin > 7) {
74         return -1;
75     }
76 
77     ec_outb(EC_GPIO_INDEX,
78             port * EC_GPIO_PORT_SKIP + EC_GPIO_DATA_OFFSET);
79     data_reg = ec_inb(EC_GPIO_DATA);
80     if (val) {
81         data_reg |= (1 << pin);
82     } else {
83         data_reg &= ~(1 << pin);
84     }
85     ec_outb(EC_GPIO_DATA, data_reg);
86     return 0;
87 }
88