Add a generic framework for VMware communication port, by Herve Poussineau.
[qemu/dscho.git] / hw / i2c.c
blob3fc0733321e88da5cf51575126a38f34acd3ddc5
1 /*
2 * QEMU I2C bus interface.
4 * Copyright (c) 2007 CodeSourcery.
5 * Written by Paul Brook
7 * This code is licenced under the LGPL.
8 */
10 #include "vl.h"
12 struct i2c_bus
14 i2c_slave *current_dev;
15 i2c_slave *dev;
18 /* Create a new I2C bus. */
19 i2c_bus *i2c_init_bus(void)
21 i2c_bus *bus;
23 bus = (i2c_bus *)qemu_mallocz(sizeof(i2c_bus));
24 return bus;
27 /* Create a new slave device. */
28 i2c_slave *i2c_slave_init(i2c_bus *bus, int address, int size)
30 i2c_slave *dev;
32 if (size < sizeof(i2c_slave))
33 cpu_abort(cpu_single_env, "I2C struct too small");
35 dev = (i2c_slave *)qemu_mallocz(size);
36 dev->address = address;
37 dev->next = bus->dev;
38 bus->dev = dev;
40 return dev;
43 void i2c_set_slave_address(i2c_slave *dev, int address)
45 dev->address = address;
48 /* Return nonzero if bus is busy. */
49 int i2c_bus_busy(i2c_bus *bus)
51 return bus->current_dev != NULL;
54 /* Returns nonzero if the bus is already busy, or is the address is not
55 valid. */
56 /* TODO: Make this handle multiple masters. */
57 int i2c_start_transfer(i2c_bus *bus, int address, int recv)
59 i2c_slave *dev;
61 for (dev = bus->dev; dev; dev = dev->next) {
62 if (dev->address == address)
63 break;
66 if (!dev)
67 return 1;
69 /* If the bus is already busy, assume this is a repeated
70 start condition. */
71 bus->current_dev = dev;
72 dev->event(dev, recv ? I2C_START_RECV : I2C_START_SEND);
73 return 0;
76 void i2c_end_transfer(i2c_bus *bus)
78 i2c_slave *dev = bus->current_dev;
80 if (!dev)
81 return;
83 dev->event(dev, I2C_FINISH);
85 bus->current_dev = NULL;
88 int i2c_send(i2c_bus *bus, uint8_t data)
90 i2c_slave *dev = bus->current_dev;
92 if (!dev)
93 return -1;
95 return dev->send(dev, data);
98 int i2c_recv(i2c_bus *bus)
100 i2c_slave *dev = bus->current_dev;
102 if (!dev)
103 return -1;
105 return dev->recv(dev);
108 void i2c_nack(i2c_bus *bus)
110 i2c_slave *dev = bus->current_dev;
112 if (!dev)
113 return;
115 dev->event(dev, I2C_NACK);
118 void i2c_bus_save(QEMUFile *f, i2c_bus *bus)
120 qemu_put_byte(f, bus->current_dev ? bus->current_dev->address : 0x00);
123 void i2c_bus_load(QEMUFile *f, i2c_bus *bus)
125 i2c_slave *dev;
126 uint8_t address = qemu_get_byte(f);
128 if (address) {
129 for (dev = bus->dev; dev; dev = dev->next)
130 if (dev->address == address) {
131 bus->current_dev = dev;
132 return;
135 fprintf(stderr, "%s: I2C slave with address %02x disappeared\n",
136 __FUNCTION__, address);
140 void i2c_slave_save(QEMUFile *f, i2c_slave *dev)
142 qemu_put_byte(f, dev->address);
145 void i2c_slave_load(QEMUFile *f, i2c_slave *dev)
147 dev->address = qemu_get_byte(f);