xref: /openbmc/qemu/hw/sensor/lsm303dlhc_mag.c (revision 63dd7bcb)
1 /*
2  * LSM303DLHC I2C magnetometer.
3  *
4  * Copyright (C) 2021 Linaro Ltd.
5  * Written by Kevin Townsend <kevin.townsend@linaro.org>
6  *
7  * Based on: https://www.st.com/resource/en/datasheet/lsm303dlhc.pdf
8  *
9  * SPDX-License-Identifier: GPL-2.0-or-later
10  */
11 
12 /*
13  * The I2C address associated with this device is set on the command-line when
14  * initialising the machine, but the following address is standard: 0x1E.
15  *
16  * Get and set functions for 'mag-x', 'mag-y' and 'mag-z' assume that
17  * 1 = 0.001 uT. (NOTE the 1 gauss = 100 uT, so setting a value of 100,000
18  * would be equal to 1 gauss or 100 uT.)
19  *
20  * Get and set functions for 'temperature' assume that 1 = 0.001 C, so 23.6 C
21  * would be equal to 23600.
22  */
23 
24 #include "qemu/osdep.h"
25 #include "hw/i2c/i2c.h"
26 #include "migration/vmstate.h"
27 #include "qapi/error.h"
28 #include "qapi/visitor.h"
29 #include "qemu/module.h"
30 #include "qemu/log.h"
31 #include "qemu/bswap.h"
32 
33 enum LSM303DLHCMagReg {
34     LSM303DLHC_MAG_REG_CRA          = 0x00,
35     LSM303DLHC_MAG_REG_CRB          = 0x01,
36     LSM303DLHC_MAG_REG_MR           = 0x02,
37     LSM303DLHC_MAG_REG_OUT_X_H      = 0x03,
38     LSM303DLHC_MAG_REG_OUT_X_L      = 0x04,
39     LSM303DLHC_MAG_REG_OUT_Z_H      = 0x05,
40     LSM303DLHC_MAG_REG_OUT_Z_L      = 0x06,
41     LSM303DLHC_MAG_REG_OUT_Y_H      = 0x07,
42     LSM303DLHC_MAG_REG_OUT_Y_L      = 0x08,
43     LSM303DLHC_MAG_REG_SR           = 0x09,
44     LSM303DLHC_MAG_REG_IRA          = 0x0A,
45     LSM303DLHC_MAG_REG_IRB          = 0x0B,
46     LSM303DLHC_MAG_REG_IRC          = 0x0C,
47     LSM303DLHC_MAG_REG_TEMP_OUT_H   = 0x31,
48     LSM303DLHC_MAG_REG_TEMP_OUT_L   = 0x32
49 };
50 
51 typedef struct LSM303DLHCMagState {
52     I2CSlave parent_obj;
53     uint8_t cra;
54     uint8_t crb;
55     uint8_t mr;
56     int16_t x;
57     int16_t z;
58     int16_t y;
59     int16_t x_lock;
60     int16_t z_lock;
61     int16_t y_lock;
62     uint8_t sr;
63     uint8_t ira;
64     uint8_t irb;
65     uint8_t irc;
66     int16_t temperature;
67     int16_t temperature_lock;
68     uint8_t len;
69     uint8_t buf;
70     uint8_t pointer;
71 } LSM303DLHCMagState;
72 
73 #define TYPE_LSM303DLHC_MAG "lsm303dlhc_mag"
74 OBJECT_DECLARE_SIMPLE_TYPE(LSM303DLHCMagState, LSM303DLHC_MAG)
75 
76 /*
77  * Conversion factor from Gauss to sensor values for each GN gain setting,
78  * in units "lsb per Gauss" (see data sheet table 3). There is no documented
79  * behaviour if the GN setting in CRB is incorrectly set to 0b000;
80  * we arbitrarily make it the same as 0b001.
81  */
82 uint32_t xy_gain[] = { 1100, 1100, 855, 670, 450, 400, 330, 230 };
83 uint32_t z_gain[] = { 980, 980, 760, 600, 400, 355, 295, 205 };
84 
85 static void lsm303dlhc_mag_get_x(Object *obj, Visitor *v, const char *name,
86                                  void *opaque, Error **errp)
87 {
88     LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
89     int gm = extract32(s->crb, 5, 3);
90 
91     /* Convert to uT where 1000 = 1 uT. Conversion factor depends on gain. */
92     int64_t value = muldiv64(s->x, 100000, xy_gain[gm]);
93     visit_type_int(v, name, &value, errp);
94 }
95 
96 static void lsm303dlhc_mag_get_y(Object *obj, Visitor *v, const char *name,
97                                  void *opaque, Error **errp)
98 {
99     LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
100     int gm = extract32(s->crb, 5, 3);
101 
102     /* Convert to uT where 1000 = 1 uT. Conversion factor depends on gain. */
103     int64_t value = muldiv64(s->y, 100000, xy_gain[gm]);
104     visit_type_int(v, name, &value, errp);
105 }
106 
107 static void lsm303dlhc_mag_get_z(Object *obj, Visitor *v, const char *name,
108                                  void *opaque, Error **errp)
109 {
110     LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
111     int gm = extract32(s->crb, 5, 3);
112 
113     /* Convert to uT where 1000 = 1 uT. Conversion factor depends on gain. */
114     int64_t value = muldiv64(s->z, 100000, z_gain[gm]);
115     visit_type_int(v, name, &value, errp);
116 }
117 
118 static void lsm303dlhc_mag_set_x(Object *obj, Visitor *v, const char *name,
119                                  void *opaque, Error **errp)
120 {
121     LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
122     int64_t value;
123     int64_t reg;
124     int gm = extract32(s->crb, 5, 3);
125 
126     if (!visit_type_int(v, name, &value, errp)) {
127         return;
128     }
129 
130     reg = muldiv64(value, xy_gain[gm], 100000);
131 
132     /* Make sure we are within a 12-bit limit. */
133     if (reg > 2047 || reg < -2048) {
134         error_setg(errp, "value %" PRId64 " out of register's range", value);
135         return;
136     }
137 
138     s->x = (int16_t)reg;
139 }
140 
141 static void lsm303dlhc_mag_set_y(Object *obj, Visitor *v, const char *name,
142                                  void *opaque, Error **errp)
143 {
144     LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
145     int64_t value;
146     int64_t reg;
147     int gm = extract32(s->crb, 5, 3);
148 
149     if (!visit_type_int(v, name, &value, errp)) {
150         return;
151     }
152 
153     reg = muldiv64(value, xy_gain[gm], 100000);
154 
155     /* Make sure we are within a 12-bit limit. */
156     if (reg > 2047 || reg < -2048) {
157         error_setg(errp, "value %" PRId64 " out of register's range", value);
158         return;
159     }
160 
161     s->y = (int16_t)reg;
162 }
163 
164 static void lsm303dlhc_mag_set_z(Object *obj, Visitor *v, const char *name,
165                                  void *opaque, Error **errp)
166 {
167     LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
168     int64_t value;
169     int64_t reg;
170     int gm = extract32(s->crb, 5, 3);
171 
172     if (!visit_type_int(v, name, &value, errp)) {
173         return;
174     }
175 
176     reg = muldiv64(value, z_gain[gm], 100000);
177 
178     /* Make sure we are within a 12-bit limit. */
179     if (reg > 2047 || reg < -2048) {
180         error_setg(errp, "value %" PRId64 " out of register's range", value);
181         return;
182     }
183 
184     s->z = (int16_t)reg;
185 }
186 
187 /*
188  * Get handler for the temperature property.
189  */
190 static void lsm303dlhc_mag_get_temperature(Object *obj, Visitor *v,
191                                            const char *name, void *opaque,
192                                            Error **errp)
193 {
194     LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
195     int64_t value;
196 
197     /* Convert to 1 lsb = 0.125 C to 1 = 0.001 C for 'temperature' property. */
198     value = s->temperature * 125;
199 
200     visit_type_int(v, name, &value, errp);
201 }
202 
203 /*
204  * Set handler for the temperature property.
205  */
206 static void lsm303dlhc_mag_set_temperature(Object *obj, Visitor *v,
207                                            const char *name, void *opaque,
208                                            Error **errp)
209 {
210     LSM303DLHCMagState *s = LSM303DLHC_MAG(obj);
211     int64_t value;
212 
213     if (!visit_type_int(v, name, &value, errp)) {
214         return;
215     }
216 
217     /* Input temperature is in 0.001 C units. Convert to 1 lsb = 0.125 C. */
218     value /= 125;
219 
220     if (value > 2047 || value < -2048) {
221         error_setg(errp, "value %" PRId64 " lsb is out of range", value);
222         return;
223     }
224 
225     s->temperature = (int16_t)value;
226 }
227 
228 /*
229  * Callback handler whenever a 'I2C_START_RECV' (read) event is received.
230  */
231 static void lsm303dlhc_mag_read(LSM303DLHCMagState *s)
232 {
233     /*
234      * Set the LOCK bit whenever a new read attempt is made. This will be
235      * cleared in I2C_FINISH. Note that DRDY is always set to 1 in this driver.
236      */
237     s->sr = 0x3;
238 
239     /*
240      * Copy the current X/Y/Z and temp. values into the locked registers so
241      * that 'mag-x', 'mag-y', 'mag-z' and 'temperature' can continue to be
242      * updated via QOM, etc., without corrupting the current read event.
243      */
244     s->x_lock = s->x;
245     s->z_lock = s->z;
246     s->y_lock = s->y;
247     s->temperature_lock = s->temperature;
248 }
249 
250 /*
251  * Callback handler whenever a 'I2C_FINISH' event is received.
252  */
253 static void lsm303dlhc_mag_finish(LSM303DLHCMagState *s)
254 {
255     /*
256      * Clear the LOCK bit when the read attempt terminates.
257      * This bit is initially set in the I2C_START_RECV handler.
258      */
259     s->sr = 0x1;
260 }
261 
262 /*
263  * Callback handler when a device attempts to write to a register.
264  */
265 static void lsm303dlhc_mag_write(LSM303DLHCMagState *s)
266 {
267     switch (s->pointer) {
268     case LSM303DLHC_MAG_REG_CRA:
269         s->cra = s->buf;
270         break;
271     case LSM303DLHC_MAG_REG_CRB:
272         /* Make sure gain is at least 1, falling back to 1 on an error. */
273         if (s->buf >> 5 == 0) {
274             s->buf = 1 << 5;
275         }
276         s->crb = s->buf;
277         break;
278     case LSM303DLHC_MAG_REG_MR:
279         s->mr = s->buf;
280         break;
281     case LSM303DLHC_MAG_REG_SR:
282         s->sr = s->buf;
283         break;
284     case LSM303DLHC_MAG_REG_IRA:
285         s->ira = s->buf;
286         break;
287     case LSM303DLHC_MAG_REG_IRB:
288         s->irb = s->buf;
289         break;
290     case LSM303DLHC_MAG_REG_IRC:
291         s->irc = s->buf;
292         break;
293     default:
294         qemu_log_mask(LOG_GUEST_ERROR, "reg is read-only: 0x%02X", s->buf);
295         break;
296     }
297 }
298 
299 /*
300  * Low-level master-to-slave transaction handler.
301  */
302 static int lsm303dlhc_mag_send(I2CSlave *i2c, uint8_t data)
303 {
304     LSM303DLHCMagState *s = LSM303DLHC_MAG(i2c);
305 
306     if (s->len == 0) {
307         /* First byte is the reg pointer */
308         s->pointer = data;
309         s->len++;
310     } else if (s->len == 1) {
311         /* Second byte is the new register value. */
312         s->buf = data;
313         lsm303dlhc_mag_write(s);
314     } else {
315         g_assert_not_reached();
316     }
317 
318     return 0;
319 }
320 
321 /*
322  * Low-level slave-to-master transaction handler (read attempts).
323  */
324 static uint8_t lsm303dlhc_mag_recv(I2CSlave *i2c)
325 {
326     LSM303DLHCMagState *s = LSM303DLHC_MAG(i2c);
327     uint8_t resp;
328 
329     switch (s->pointer) {
330     case LSM303DLHC_MAG_REG_CRA:
331         resp = s->cra;
332         break;
333     case LSM303DLHC_MAG_REG_CRB:
334         resp = s->crb;
335         break;
336     case LSM303DLHC_MAG_REG_MR:
337         resp = s->mr;
338         break;
339     case LSM303DLHC_MAG_REG_OUT_X_H:
340         resp = (uint8_t)(s->x_lock >> 8);
341         break;
342     case LSM303DLHC_MAG_REG_OUT_X_L:
343         resp = (uint8_t)(s->x_lock);
344         break;
345     case LSM303DLHC_MAG_REG_OUT_Z_H:
346         resp = (uint8_t)(s->z_lock >> 8);
347         break;
348     case LSM303DLHC_MAG_REG_OUT_Z_L:
349         resp = (uint8_t)(s->z_lock);
350         break;
351     case LSM303DLHC_MAG_REG_OUT_Y_H:
352         resp = (uint8_t)(s->y_lock >> 8);
353         break;
354     case LSM303DLHC_MAG_REG_OUT_Y_L:
355         resp = (uint8_t)(s->y_lock);
356         break;
357     case LSM303DLHC_MAG_REG_SR:
358         resp = s->sr;
359         break;
360     case LSM303DLHC_MAG_REG_IRA:
361         resp = s->ira;
362         break;
363     case LSM303DLHC_MAG_REG_IRB:
364         resp = s->irb;
365         break;
366     case LSM303DLHC_MAG_REG_IRC:
367         resp = s->irc;
368         break;
369     case LSM303DLHC_MAG_REG_TEMP_OUT_H:
370         /* Check if the temperature sensor is enabled or not (CRA & 0x80). */
371         if (s->cra & 0x80) {
372             resp = (uint8_t)(s->temperature_lock >> 8);
373         } else {
374             resp = 0;
375         }
376         break;
377     case LSM303DLHC_MAG_REG_TEMP_OUT_L:
378         if (s->cra & 0x80) {
379             resp = (uint8_t)(s->temperature_lock & 0xff);
380         } else {
381             resp = 0;
382         }
383         break;
384     default:
385         resp = 0;
386         break;
387     }
388 
389     /*
390      * The address pointer on the LSM303DLHC auto-increments whenever a byte
391      * is read, without the master device having to request the next address.
392      *
393      * The auto-increment process has the following logic:
394      *
395      *   - if (s->pointer == 8) then s->pointer = 3
396      *   - else: if (s->pointer == 12) then s->pointer = 0
397      *   - else: s->pointer += 1
398      *
399      * Reading an invalid address return 0.
400      */
401     if (s->pointer == LSM303DLHC_MAG_REG_OUT_Y_L) {
402         s->pointer = LSM303DLHC_MAG_REG_OUT_X_H;
403     } else if (s->pointer == LSM303DLHC_MAG_REG_IRC) {
404         s->pointer = LSM303DLHC_MAG_REG_CRA;
405     } else {
406         s->pointer++;
407     }
408 
409     return resp;
410 }
411 
412 /*
413  * Bus state change handler.
414  */
415 static int lsm303dlhc_mag_event(I2CSlave *i2c, enum i2c_event event)
416 {
417     LSM303DLHCMagState *s = LSM303DLHC_MAG(i2c);
418 
419     switch (event) {
420     case I2C_START_SEND:
421         break;
422     case I2C_START_RECV:
423         lsm303dlhc_mag_read(s);
424         break;
425     case I2C_FINISH:
426         lsm303dlhc_mag_finish(s);
427         break;
428     case I2C_NACK:
429         break;
430     default:
431         return -1;
432     }
433 
434     s->len = 0;
435     return 0;
436 }
437 
438 /*
439  * Device data description using VMSTATE macros.
440  */
441 static const VMStateDescription vmstate_lsm303dlhc_mag = {
442     .name = "LSM303DLHC_MAG",
443     .version_id = 0,
444     .minimum_version_id = 0,
445     .fields = (VMStateField[]) {
446 
447         VMSTATE_I2C_SLAVE(parent_obj, LSM303DLHCMagState),
448         VMSTATE_UINT8(len, LSM303DLHCMagState),
449         VMSTATE_UINT8(buf, LSM303DLHCMagState),
450         VMSTATE_UINT8(pointer, LSM303DLHCMagState),
451         VMSTATE_UINT8(cra, LSM303DLHCMagState),
452         VMSTATE_UINT8(crb, LSM303DLHCMagState),
453         VMSTATE_UINT8(mr, LSM303DLHCMagState),
454         VMSTATE_INT16(x, LSM303DLHCMagState),
455         VMSTATE_INT16(z, LSM303DLHCMagState),
456         VMSTATE_INT16(y, LSM303DLHCMagState),
457         VMSTATE_INT16(x_lock, LSM303DLHCMagState),
458         VMSTATE_INT16(z_lock, LSM303DLHCMagState),
459         VMSTATE_INT16(y_lock, LSM303DLHCMagState),
460         VMSTATE_UINT8(sr, LSM303DLHCMagState),
461         VMSTATE_UINT8(ira, LSM303DLHCMagState),
462         VMSTATE_UINT8(irb, LSM303DLHCMagState),
463         VMSTATE_UINT8(irc, LSM303DLHCMagState),
464         VMSTATE_INT16(temperature, LSM303DLHCMagState),
465         VMSTATE_INT16(temperature_lock, LSM303DLHCMagState),
466         VMSTATE_END_OF_LIST()
467     }
468 };
469 
470 /*
471  * Put the device into post-reset default state.
472  */
473 static void lsm303dlhc_mag_default_cfg(LSM303DLHCMagState *s)
474 {
475     /* Set the device into is default reset state. */
476     s->len = 0;
477     s->pointer = 0;         /* Current register. */
478     s->buf = 0;             /* Shared buffer. */
479     s->cra = 0x10;          /* Temp Enabled = 0, Data Rate = 15.0 Hz. */
480     s->crb = 0x20;          /* Gain = +/- 1.3 Gauss. */
481     s->mr = 0x3;            /* Operating Mode = Sleep. */
482     s->x = 0;
483     s->z = 0;
484     s->y = 0;
485     s->x_lock = 0;
486     s->z_lock = 0;
487     s->y_lock = 0;
488     s->sr = 0x1;            /* DRDY = 1. */
489     s->ira = 0x48;
490     s->irb = 0x34;
491     s->irc = 0x33;
492     s->temperature = 0;     /* Default to 0 degrees C (0/8 lsb = 0 C). */
493     s->temperature_lock = 0;
494 }
495 
496 /*
497  * Callback handler when DeviceState 'reset' is set to true.
498  */
499 static void lsm303dlhc_mag_reset(DeviceState *dev)
500 {
501     I2CSlave *i2c = I2C_SLAVE(dev);
502     LSM303DLHCMagState *s = LSM303DLHC_MAG(i2c);
503 
504     /* Set the device into its default reset state. */
505     lsm303dlhc_mag_default_cfg(s);
506 }
507 
508 /*
509  * Initialisation of any public properties.
510  */
511 static void lsm303dlhc_mag_initfn(Object *obj)
512 {
513     object_property_add(obj, "mag-x", "int",
514                 lsm303dlhc_mag_get_x,
515                 lsm303dlhc_mag_set_x, NULL, NULL);
516 
517     object_property_add(obj, "mag-y", "int",
518                 lsm303dlhc_mag_get_y,
519                 lsm303dlhc_mag_set_y, NULL, NULL);
520 
521     object_property_add(obj, "mag-z", "int",
522                 lsm303dlhc_mag_get_z,
523                 lsm303dlhc_mag_set_z, NULL, NULL);
524 
525     object_property_add(obj, "temperature", "int",
526                 lsm303dlhc_mag_get_temperature,
527                 lsm303dlhc_mag_set_temperature, NULL, NULL);
528 }
529 
530 /*
531  * Set the virtual method pointers (bus state change, tx/rx, etc.).
532  */
533 static void lsm303dlhc_mag_class_init(ObjectClass *klass, void *data)
534 {
535     DeviceClass *dc = DEVICE_CLASS(klass);
536     I2CSlaveClass *k = I2C_SLAVE_CLASS(klass);
537 
538     dc->reset = lsm303dlhc_mag_reset;
539     dc->vmsd = &vmstate_lsm303dlhc_mag;
540     k->event = lsm303dlhc_mag_event;
541     k->recv = lsm303dlhc_mag_recv;
542     k->send = lsm303dlhc_mag_send;
543 }
544 
545 static const TypeInfo lsm303dlhc_mag_info = {
546     .name = TYPE_LSM303DLHC_MAG,
547     .parent = TYPE_I2C_SLAVE,
548     .instance_size = sizeof(LSM303DLHCMagState),
549     .instance_init = lsm303dlhc_mag_initfn,
550     .class_init = lsm303dlhc_mag_class_init,
551 };
552 
553 static void lsm303dlhc_mag_register_types(void)
554 {
555     type_register_static(&lsm303dlhc_mag_info);
556 }
557 
558 type_init(lsm303dlhc_mag_register_types)
559