1
2
3
4
5
6
7
8
9
10#include "qemu/osdep.h"
11#include "qemu/log.h"
12#include "qemu/timer.h"
13#include "qemu/bcd.h"
14#include "hw/i2c/i2c.h"
15
16#define TYPE_M41T80 "m41t80"
17#define M41T80(obj) OBJECT_CHECK(M41t80State, (obj), TYPE_M41T80)
18
19typedef struct M41t80State {
20 I2CSlave parent_obj;
21 int8_t addr;
22} M41t80State;
23
24static void m41t80_realize(DeviceState *dev, Error **errp)
25{
26 M41t80State *s = M41T80(dev);
27
28 s->addr = -1;
29}
30
31static int m41t80_send(I2CSlave *i2c, uint8_t data)
32{
33 M41t80State *s = M41T80(i2c);
34
35 if (s->addr < 0) {
36 s->addr = data;
37 } else {
38 s->addr++;
39 }
40 return 0;
41}
42
43static int m41t80_recv(I2CSlave *i2c)
44{
45 M41t80State *s = M41T80(i2c);
46 struct tm now;
47 qemu_timeval tv;
48
49 if (s->addr < 0) {
50 s->addr = 0;
51 }
52 if (s->addr >= 1 && s->addr <= 7) {
53 qemu_get_timedate(&now, -1);
54 }
55 switch (s->addr++) {
56 case 0:
57 qemu_gettimeofday(&tv);
58 return to_bcd(tv.tv_usec / 10000);
59 case 1:
60 return to_bcd(now.tm_sec);
61 case 2:
62 return to_bcd(now.tm_min);
63 case 3:
64 return to_bcd(now.tm_hour);
65 case 4:
66 return to_bcd(now.tm_wday);
67 case 5:
68 return to_bcd(now.tm_mday);
69 case 6:
70 return to_bcd(now.tm_mon + 1);
71 case 7:
72 return to_bcd(now.tm_year % 100);
73 case 8 ... 19:
74 qemu_log_mask(LOG_UNIMP, "%s: unimplemented register: %d\n",
75 __func__, s->addr - 1);
76 return 0;
77 default:
78 qemu_log_mask(LOG_GUEST_ERROR, "%s: invalid register: %d\n",
79 __func__, s->addr - 1);
80 return 0;
81 }
82}
83
84static int m41t80_event(I2CSlave *i2c, enum i2c_event event)
85{
86 M41t80State *s = M41T80(i2c);
87
88 if (event == I2C_START_SEND) {
89 s->addr = -1;
90 }
91 return 0;
92}
93
94static void m41t80_class_init(ObjectClass *klass, void *data)
95{
96 DeviceClass *dc = DEVICE_CLASS(klass);
97 I2CSlaveClass *sc = I2C_SLAVE_CLASS(klass);
98
99 dc->realize = m41t80_realize;
100 sc->send = m41t80_send;
101 sc->recv = m41t80_recv;
102 sc->event = m41t80_event;
103}
104
105static const TypeInfo m41t80_info = {
106 .name = TYPE_M41T80,
107 .parent = TYPE_I2C_SLAVE,
108 .instance_size = sizeof(M41t80State),
109 .class_init = m41t80_class_init,
110};
111
112static void m41t80_register_types(void)
113{
114 type_register_static(&m41t80_info);
115}
116
117type_init(m41t80_register_types)
118