summaryrefslogtreecommitdiff
path: root/device.c
blob: bec5a1a42ae2531aec4de38aaab3e7a2ca18cd6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
 * Copyright (C) 2010 Tobias Klauser <tklauser@distanz.ch>
 * Copyright (C) 2010 chysun2000@gmail.com
 *
 * This file is part of nios2sim-ng.
 *
 * This file is subject to the terms and conditions of the GNU General Public
 * License. See the file "COPYING" in the main directory of this archive
 * for more details.
 */

#include <stdio.h>

#include "nios2sim-ng.h"
#include "device.h"
#include "uart.h"
#include "jtag_uart.h"

static struct device *devices[] = {
	&uart_core,
	&jtag_uart_core,
};
#define DEVICES_COUNT	ARRAY_SIZE(devices)

bool device_generic_is_dev_addr(struct device *dev, uint32_t addr)
{
	if (addr >= dev->base && addr < dev->base + dev->size)
		return true;

	return false;
}

int device_init_all(void)
{
	unsigned int i;
	int ret = 0;

	for (i = 0; i < DEVICES_COUNT; i++) {
		struct device *dev = devices[i];

		if (unlikely(dev->init == NULL))
			continue;

		ret = dev->init(dev);
		if (ret) {
			err("Failed to initialize device '%s'\n", dev->name);
			break;
		}

		if (dev->is_dev_addr == NULL)
			dev->is_dev_addr = device_generic_is_dev_addr;

		vinfo("%s at 0x%08x - 0x%08x\n", dev->name, dev->base,
				(uint32_t)(dev->base + dev->size));
	}

	return ret;
}

/**
 * Get device mapped at a specific address.
 *
 * @param addr  address to get the mapped device for
 * @return      pointer to the device mapped at addr, NULL if no device is
 *              mapped there
 */
struct device *device_get_by_addr(uint32_t addr)
{
	unsigned int i;
	struct device *dev = NULL;

	for (i = 0; i < DEVICES_COUNT; i++) {
		dev = devices[i];
		if (unlikely(dev->is_dev_addr == NULL))
			continue;
		if (dev->is_dev_addr(dev, addr))
			return dev;
	}

	return NULL;
}

void device_simulate_all(void)
{
	unsigned int i;
	struct device *dev;

	for (i = 0; i < DEVICES_COUNT; i++) {
		dev = devices[i];
		if (likely(dev->simulate != NULL))
			dev->simulate(dev);
	}
}

void io_register_init(struct io_register *reg, uint32_t addr,
		      uint32_t valid, uint32_t readonly, uint32_t value)
{
	reg->addr = addr;
	reg->valid_mask = valid;
	reg->readonly_mask = readonly;
	reg->value = value;
}

uint32_t io_register_read(struct io_register *reg)
{
	return reg->value & reg->valid_mask;
}

void io_register_write(struct io_register *reg, uint32_t value)
{
	reg->value = value & ~(reg->readonly_mask);
}