2 * QEMU I2C bus interface.
4 * Copyright (c) 2007 CodeSourcery.
5 * Written by Paul Brook
7 * This code is licenced under the LGPL.
15 i2c_slave
*current_dev
;
20 static void i2c_bus_save(QEMUFile
*f
, void *opaque
)
22 i2c_bus
*bus
= (i2c_bus
*)opaque
;
24 qemu_put_byte(f
, bus
->current_dev
? bus
->current_dev
->address
: -1);
27 static int i2c_bus_load(QEMUFile
*f
, void *opaque
, int version_id
)
29 i2c_bus
*bus
= (i2c_bus
*)opaque
;
34 /* The bus is loaded before attached devices, so load and save the
35 current device id. Devices will check themselves as loaded. */
36 bus
->saved_address
= (int8_t) qemu_get_byte(f
);
37 bus
->current_dev
= NULL
;
42 /* Create a new I2C bus. */
43 i2c_bus
*i2c_init_bus(void)
47 bus
= (i2c_bus
*)qemu_mallocz(sizeof(i2c_bus
));
48 register_savevm("i2c_bus", -1, 1, i2c_bus_save
, i2c_bus_load
, bus
);
52 /* Create a new slave device. */
53 i2c_slave
*i2c_slave_init(i2c_bus
*bus
, int address
, int size
)
57 if (size
< sizeof(i2c_slave
))
58 hw_error("I2C struct too small");
60 dev
= (i2c_slave
*)qemu_mallocz(size
);
61 dev
->address
= address
;
69 void i2c_set_slave_address(i2c_slave
*dev
, int address
)
71 dev
->address
= address
;
74 /* Return nonzero if bus is busy. */
75 int i2c_bus_busy(i2c_bus
*bus
)
77 return bus
->current_dev
!= NULL
;
80 /* Returns non-zero if the address is not valid. */
81 /* TODO: Make this handle multiple masters. */
82 int i2c_start_transfer(i2c_bus
*bus
, int address
, int recv
)
86 for (dev
= bus
->dev
; dev
; dev
= dev
->next
) {
87 if (dev
->address
== address
)
94 /* If the bus is already busy, assume this is a repeated
96 bus
->current_dev
= dev
;
97 dev
->event(dev
, recv
? I2C_START_RECV
: I2C_START_SEND
);
101 void i2c_end_transfer(i2c_bus
*bus
)
103 i2c_slave
*dev
= bus
->current_dev
;
108 dev
->event(dev
, I2C_FINISH
);
110 bus
->current_dev
= NULL
;
113 int i2c_send(i2c_bus
*bus
, uint8_t data
)
115 i2c_slave
*dev
= bus
->current_dev
;
120 return dev
->send(dev
, data
);
123 int i2c_recv(i2c_bus
*bus
)
125 i2c_slave
*dev
= bus
->current_dev
;
130 return dev
->recv(dev
);
133 void i2c_nack(i2c_bus
*bus
)
135 i2c_slave
*dev
= bus
->current_dev
;
140 dev
->event(dev
, I2C_NACK
);
143 void i2c_slave_save(QEMUFile
*f
, i2c_slave
*dev
)
145 qemu_put_byte(f
, dev
->address
);
148 void i2c_slave_load(QEMUFile
*f
, i2c_slave
*dev
)
150 dev
->address
= qemu_get_byte(f
);
151 if (dev
->bus
->saved_address
== dev
->address
)
152 dev
->bus
->current_dev
= dev
;