blob: 49c31df93103b8583cb8f82e3b8eb7f38e316025 [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001/*
2 * Copyright (c) 2016 Adam Barth
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files
6 * (the "Software"), to deal in the Software without restriction,
7 * including without limitation the rights to use, copy, modify, merge,
8 * publish, distribute, sublicense, and/or sell copies of the Software,
9 * and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23#include <dev/gpio.h>
24#include <errno.h>
25#include <platform/bcm28xx.h>
26#include <reg.h>
27
28#define NUM_PINS 54
29#define BITS_PER_REG 32
30#define BITS_PER_PIN 3
31#define PINS_PER_REG (BITS_PER_REG / BITS_PER_PIN)
32#define GPIOREG(base, nr) (REG32(base) + (nr / BITS_PER_REG))
33
34int gpio_config(unsigned nr, unsigned flags)
35{
36 unsigned mask = 0x7;
37 if (nr >= NUM_PINS || flags & ~mask)
38 return -EINVAL;
39 unsigned register_number = nr / PINS_PER_REG;
40 unsigned offset = (nr % PINS_PER_REG) * BITS_PER_PIN;
41 unsigned shifted_mask = mask << offset;
42 volatile uint32_t *reg = REG32(GPIO_GPFSEL0) + register_number;
43 *reg = (*reg & ~shifted_mask) | (flags << offset);
44 return 0;
45}
46
47void gpio_set(unsigned nr, unsigned on)
48{
49 unsigned offset = nr % BITS_PER_REG;
50 *GPIOREG(on ? GPIO_GPSET0 : GPIO_GPCLR0, nr) = 1 << offset;
51}
52
53int gpio_get(unsigned nr)
54{
55 unsigned offset = nr % BITS_PER_REG;
56 return (*GPIOREG(GPIO_GPLEV0, nr) & (1 << offset)) >> offset;
57}