xref: /linux/drivers/iio/imu/bno055/bno055_ser_core.c (revision d2c9a99135da931377240942d44f3dea104cedb8)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Serial line interface for Bosh BNO055 IMU (via serdev).
4  * This file implements serial communication up to the register read/write
5  * level.
6  *
7  * Copyright (C) 2021-2022 Istituto Italiano di Tecnologia
8  * Electronic Design Laboratory
9  * Written by Andrea Merello <andrea.merello@iit.it>
10  *
11  * This driver is based on
12  *	Plantower PMS7003 particulate matter sensor driver
13  *	Which is
14  *	Copyright (c) Tomasz Duszynski <tduszyns@gmail.com>
15  */
16 
17 #include <linux/completion.h>
18 #include <linux/device.h>
19 #include <linux/errno.h>
20 #include <linux/jiffies.h>
21 #include <linux/kernel.h>
22 #include <linux/module.h>
23 #include <linux/mutex.h>
24 #include <linux/regmap.h>
25 #include <linux/serdev.h>
26 
27 #include "bno055_ser_trace.h"
28 #include "bno055.h"
29 
30 /*
31  * Register writes cmd have the following format
32  * +------+------+-----+-----+----- ... ----+
33  * | 0xAA | 0xOO | REG | LEN | payload[LEN] |
34  * +------+------+-----+-----+----- ... ----+
35  *
36  * Register write responses have the following format
37  * +------+----------+
38  * | 0xEE | ERROCODE |
39  * +------+----------+
40  *
41  * .. except when writing the SYS_RST bit (i.e. triggering a system reset); in
42  * case the IMU accepts the command, then it resets without responding. We don't
43  * handle this (yet) here (so we inform the common bno055 code not to perform
44  * sw resets - bno055 on serial bus basically requires the hw reset pin).
45  *
46  * Register read have the following format
47  * +------+------+-----+-----+
48  * | 0xAA | 0xO1 | REG | LEN |
49  * +------+------+-----+-----+
50  *
51  * Successful register read response have the following format
52  * +------+-----+----- ... ----+
53  * | 0xBB | LEN | payload[LEN] |
54  * +------+-----+----- ... ----+
55  *
56  * Failed register read response have the following format
57  * +------+--------+
58  * | 0xEE | ERRCODE|  (ERRCODE always > 1)
59  * +------+--------+
60  *
61  * Error codes are
62  * 01: OK
63  * 02: read/write FAIL
64  * 04: invalid address
65  * 05: write on RO
66  * 06: wrong start byte
67  * 07: bus overrun
68  * 08: len too high
69  * 09: len too low
70  * 10: bus RX byte timeout (timeout is 30mS)
71  *
72  *
73  * **WORKAROUND ALERT**
74  *
75  * Serial communication seems very fragile: the BNO055 buffer seems to overflow
76  * very easy; BNO055 seems able to sink few bytes, then it needs a brief pause.
77  * On the other hand, it is also picky on timeout: if there is a pause > 30mS in
78  * between two bytes then the transaction fails (IMU internal RX FSM resets).
79  *
80  * BNO055 has been seen also failing to process commands in case we send them
81  * too close each other (or if it is somehow busy?)
82  *
83  * In particular I saw these scenarios:
84  * 1) If we send 2 bytes per time, then the IMU never(?) overflows.
85  * 2) If we send 4 bytes per time (i.e. the full header), then the IMU could
86  *    overflow, but it seem to sink all 4 bytes, then it returns error.
87  * 3) If we send more than 4 bytes, the IMU could overflow, and I saw it sending
88  *    error after 4 bytes are sent; we have troubles in synchronizing again,
89  *    because we are still sending data, and the IMU interprets it as the 1st
90  *    byte of a new command.
91  *
92  * While we must avoid case 3, we could send 4 bytes per time and eventually
93  * retry in case of failure; this seemed convenient for reads (which requires
94  * TXing exactly 4 bytes), however it has been seen that, depending by the IMU
95  * settings (e.g. LPF), failures became less or more frequent; in certain IMU
96  * configurations they are very rare, but in certain others we keeps failing
97  * even after like 30 retries.
98  *
99  * So, we just split TXes in [2-bytes + delay] steps, and still keep an eye on
100  * the IMU response; in case it overflows (which is now unlikely), we retry.
101  */
102 
103 /*
104  * Read operation overhead:
105  *  4 bytes req + 2byte resp hdr.
106  *  6 bytes = 60 bit (considering 1start + 1stop bits).
107  *  60/115200 = ~520uS + about 2500mS delay -> ~3mS
108  * In 3mS we could read back about 34 bytes that means 17 samples, this means
109  * that in case of scattered reads in which the gap is 17 samples or less it is
110  * still convenient to go for a burst.
111  * We have to take into account also IMU response time - IMU seems to be often
112  * reasonably quick to respond, but sometimes it seems to be in some "critical
113  * section" in which it delays handling of serial protocol. Because of this we
114  * round-up to 22, which is the max number of samples, always bursting indeed.
115  */
116 #define BNO055_SER_XFER_BURST_BREAK_THRESHOLD 22
117 
118 struct bno055_ser_priv {
119 	enum {
120 		CMD_NONE,
121 		CMD_READ,
122 		CMD_WRITE,
123 	} expect_response;
124 	int expected_data_len;
125 	u8 *response_buf;
126 
127 	/**
128 	 * enum cmd_status - represent the status of a command sent to the HW.
129 	 * @STATUS_CRIT: The command failed: the serial communication failed.
130 	 * @STATUS_OK:   The command executed successfully.
131 	 * @STATUS_FAIL: The command failed: HW responded with an error.
132 	 */
133 	enum {
134 		STATUS_CRIT = -1,
135 		STATUS_OK = 0,
136 		STATUS_FAIL = 1,
137 	} cmd_status;
138 
139 	/*
140 	 * Protects all the above fields, which are accessed in behalf of both
141 	 * the serdev RX callback and the regmap side
142 	 */
143 	struct mutex lock;
144 
145 	/* Only accessed in serdev RX callback context*/
146 	struct {
147 		enum {
148 			RX_IDLE,
149 			RX_START,
150 			RX_DATA,
151 		} state;
152 		int databuf_count;
153 		int expected_len;
154 		int type;
155 	} rx;
156 
157 	/* Never accessed in behalf of serdev RX callback context */
158 	bool cmd_stale;
159 
160 	struct completion cmd_complete;
161 	struct serdev_device *serdev;
162 };
163 
bno055_ser_send_chunk(struct bno055_ser_priv * priv,const u8 * data,int len)164 static int bno055_ser_send_chunk(struct bno055_ser_priv *priv, const u8 *data, int len)
165 {
166 	int ret;
167 
168 	trace_send_chunk(len, data);
169 	ret = serdev_device_write(priv->serdev, data, len, msecs_to_jiffies(25));
170 	if (ret < 0)
171 		return ret;
172 
173 	if (ret < len)
174 		return -EIO;
175 
176 	return 0;
177 }
178 
179 /*
180  * Send a read or write command.
181  * 'data' can be NULL (used in read case). 'len' parameter is always valid; in
182  * case 'data' is non-NULL then it must match 'data' size.
183  */
bno055_ser_do_send_cmd(struct bno055_ser_priv * priv,bool read,int addr,int len,const u8 * data)184 static int bno055_ser_do_send_cmd(struct bno055_ser_priv *priv,
185 				  bool read, int addr, int len, const u8 *data)
186 {
187 	u8 hdr[] = {0xAA, read, addr, len};
188 	int chunk_len;
189 	int ret;
190 
191 	ret = bno055_ser_send_chunk(priv, hdr, 2);
192 	if (ret)
193 		goto fail;
194 	usleep_range(2000, 3000);
195 	ret = bno055_ser_send_chunk(priv, hdr + 2, 2);
196 	if (ret)
197 		goto fail;
198 
199 	if (read)
200 		return 0;
201 
202 	while (len) {
203 		chunk_len = min(len, 2);
204 		usleep_range(2000, 3000);
205 		ret = bno055_ser_send_chunk(priv, data, chunk_len);
206 		if (ret)
207 			goto fail;
208 		data += chunk_len;
209 		len -= chunk_len;
210 	}
211 
212 	return 0;
213 fail:
214 	/* waiting more than 30mS should clear the BNO055 internal state */
215 	usleep_range(40000, 50000);
216 	return ret;
217 }
218 
bno055_ser_send_cmd(struct bno055_ser_priv * priv,bool read,int addr,int len,const u8 * data)219 static int bno055_ser_send_cmd(struct bno055_ser_priv *priv,
220 			       bool read, int addr, int len, const u8 *data)
221 {
222 	const int retry_max = 5;
223 	int retry = retry_max;
224 	int ret = 0;
225 
226 	/*
227 	 * In case previous command was interrupted we still need to wait it to
228 	 * complete before we can issue new commands
229 	 */
230 	if (priv->cmd_stale) {
231 		ret = wait_for_completion_interruptible_timeout(&priv->cmd_complete,
232 								msecs_to_jiffies(100));
233 		if (ret == -ERESTARTSYS)
234 			return -ERESTARTSYS;
235 
236 		priv->cmd_stale = false;
237 		/* if serial protocol broke, bail out */
238 		if (priv->cmd_status == STATUS_CRIT)
239 			return -EIO;
240 	}
241 
242 	/*
243 	 * Try to convince the IMU to cooperate.. as explained in the comments
244 	 * at the top of this file, the IMU could also refuse the command (i.e.
245 	 * it is not ready yet); retry in this case.
246 	 */
247 	do {
248 		mutex_lock(&priv->lock);
249 		priv->expect_response = read ? CMD_READ : CMD_WRITE;
250 		reinit_completion(&priv->cmd_complete);
251 		mutex_unlock(&priv->lock);
252 
253 		if (retry != retry_max)
254 			trace_cmd_retry(read, addr, retry_max - retry);
255 		ret = bno055_ser_do_send_cmd(priv, read, addr, len, data);
256 		if (ret)
257 			continue;
258 
259 		ret = wait_for_completion_interruptible_timeout(&priv->cmd_complete,
260 								msecs_to_jiffies(100));
261 		if (ret == -ERESTARTSYS) {
262 			priv->cmd_stale = true;
263 			return -ERESTARTSYS;
264 		}
265 
266 		if (!ret)
267 			return -ETIMEDOUT;
268 
269 		if (priv->cmd_status == STATUS_OK)
270 			return 0;
271 		if (priv->cmd_status == STATUS_CRIT)
272 			return -EIO;
273 
274 		/* loop in case priv->cmd_status == STATUS_FAIL */
275 	} while (--retry);
276 
277 	if (ret < 0)
278 		return ret;
279 	if (priv->cmd_status == STATUS_FAIL)
280 		return -EINVAL;
281 	return 0;
282 }
283 
bno055_ser_write_reg(void * context,const void * _data,size_t count)284 static int bno055_ser_write_reg(void *context, const void *_data, size_t count)
285 {
286 	const u8 *data = _data;
287 	struct bno055_ser_priv *priv = context;
288 
289 	if (count < 2) {
290 		dev_err(&priv->serdev->dev, "Invalid write count %zu\n", count);
291 		return -EINVAL;
292 	}
293 
294 	trace_write_reg(data[0], data[1]);
295 	return bno055_ser_send_cmd(priv, 0, data[0], count - 1, data + 1);
296 }
297 
bno055_ser_read_reg(void * context,const void * _reg,size_t reg_size,void * val,size_t val_size)298 static int bno055_ser_read_reg(void *context,
299 			       const void *_reg, size_t reg_size,
300 			       void *val, size_t val_size)
301 {
302 	int ret;
303 	int reg_addr;
304 	const u8 *reg = _reg;
305 	struct bno055_ser_priv *priv = context;
306 
307 	if (val_size > 128) {
308 		dev_err(&priv->serdev->dev, "Invalid read valsize %zu\n", val_size);
309 		return -EINVAL;
310 	}
311 
312 	reg_addr = *reg;
313 	trace_read_reg(reg_addr, val_size);
314 	mutex_lock(&priv->lock);
315 	priv->expected_data_len = val_size;
316 	priv->response_buf = val;
317 	mutex_unlock(&priv->lock);
318 
319 	ret = bno055_ser_send_cmd(priv, 1, reg_addr, val_size, NULL);
320 
321 	mutex_lock(&priv->lock);
322 	priv->response_buf = NULL;
323 	mutex_unlock(&priv->lock);
324 
325 	return ret;
326 }
327 
328 /*
329  * Handler for received data; this is called from the receiver callback whenever
330  * it got some packet from the serial bus. The status tells us whether the
331  * packet is valid (i.e. header ok && received payload len consistent wrt the
332  * header). It's now our responsibility to check whether this is what we
333  * expected, of whether we got some unexpected, yet valid, packet.
334  */
bno055_ser_handle_rx(struct bno055_ser_priv * priv,int status)335 static void bno055_ser_handle_rx(struct bno055_ser_priv *priv, int status)
336 {
337 	mutex_lock(&priv->lock);
338 	switch (priv->expect_response) {
339 	case CMD_NONE:
340 		dev_warn(&priv->serdev->dev, "received unexpected, yet valid, data from sensor");
341 		mutex_unlock(&priv->lock);
342 		return;
343 
344 	case CMD_READ:
345 		priv->cmd_status = status;
346 		if (status == STATUS_OK &&
347 		    priv->rx.databuf_count != priv->expected_data_len) {
348 			/*
349 			 * If we got here, then the lower layer serial protocol
350 			 * seems consistent with itself; if we got an unexpected
351 			 * amount of data then signal it as a non critical error
352 			 */
353 			priv->cmd_status = STATUS_FAIL;
354 			dev_warn(&priv->serdev->dev,
355 				 "received an unexpected amount of, yet valid, data from sensor");
356 		}
357 		break;
358 
359 	case CMD_WRITE:
360 		priv->cmd_status = status;
361 		break;
362 	}
363 
364 	priv->expect_response = CMD_NONE;
365 	mutex_unlock(&priv->lock);
366 	complete(&priv->cmd_complete);
367 }
368 
369 /*
370  * Serdev receiver FSM. This tracks the serial communication and parse the
371  * header. It pushes packets to bno055_ser_handle_rx(), eventually communicating
372  * failures (i.e. malformed packets).
373  * Ideally it doesn't know anything about upper layer (i.e. if this is the
374  * packet we were really expecting), but since we copies the payload into the
375  * receiver buffer (that is not valid when i.e. we don't expect data), we
376  * snoop a bit in the upper layer..
377  * Also, we assume to RX one pkt per time (i.e. the HW doesn't send anything
378  * unless we require to AND we don't queue more than one request per time).
379  */
bno055_ser_receive_buf(struct serdev_device * serdev,const u8 * buf,size_t size)380 static size_t bno055_ser_receive_buf(struct serdev_device *serdev,
381 				     const u8 *buf, size_t size)
382 {
383 	int status;
384 	struct bno055_ser_priv *priv = serdev_device_get_drvdata(serdev);
385 	size_t remaining = size;
386 
387 	if (size == 0)
388 		return 0;
389 
390 	trace_recv(size, buf);
391 	switch (priv->rx.state) {
392 	case RX_IDLE:
393 		/*
394 		 * New packet.
395 		 * Check for its 1st byte that identifies the pkt type.
396 		 */
397 		if (buf[0] != 0xEE && buf[0] != 0xBB) {
398 			dev_err(&priv->serdev->dev,
399 				"Invalid packet start %x", buf[0]);
400 			bno055_ser_handle_rx(priv, STATUS_CRIT);
401 			break;
402 		}
403 		priv->rx.type = buf[0];
404 		priv->rx.state = RX_START;
405 		remaining--;
406 		buf++;
407 		priv->rx.databuf_count = 0;
408 		fallthrough;
409 
410 	case RX_START:
411 		/*
412 		 * Packet RX in progress, we expect either 1-byte len or 1-byte
413 		 * status depending by the packet type.
414 		 */
415 		if (remaining == 0)
416 			break;
417 
418 		if (priv->rx.type == 0xEE) {
419 			if (remaining > 1) {
420 				dev_err(&priv->serdev->dev, "EE pkt. Extra data received");
421 				status = STATUS_CRIT;
422 			} else {
423 				status = (buf[0] == 1) ? STATUS_OK : STATUS_FAIL;
424 			}
425 			bno055_ser_handle_rx(priv, status);
426 			priv->rx.state = RX_IDLE;
427 			break;
428 
429 		} else {
430 			/*priv->rx.type == 0xBB */
431 			priv->rx.state = RX_DATA;
432 			priv->rx.expected_len = buf[0];
433 			remaining--;
434 			buf++;
435 		}
436 		fallthrough;
437 
438 	case RX_DATA:
439 		/* Header parsed; now receiving packet data payload */
440 		if (remaining == 0)
441 			break;
442 
443 		if (priv->rx.databuf_count + remaining > priv->rx.expected_len) {
444 			/*
445 			 * This is an inconsistency in serial protocol, we lost
446 			 * sync and we don't know how to handle further data
447 			 */
448 			dev_err(&priv->serdev->dev, "BB pkt. Extra data received");
449 			bno055_ser_handle_rx(priv, STATUS_CRIT);
450 			priv->rx.state = RX_IDLE;
451 			break;
452 		}
453 
454 		mutex_lock(&priv->lock);
455 		/*
456 		 * NULL e.g. when read cmd is stale or when no read cmd is
457 		 * actually pending.
458 		 */
459 		if (priv->response_buf &&
460 		    /*
461 		     * Snoop on the upper layer protocol stuff to make sure not
462 		     * to write to an invalid memory. Apart for this, let's the
463 		     * upper layer manage any inconsistency wrt expected data
464 		     * len (as long as the serial protocol is consistent wrt
465 		     * itself (i.e. response header is consistent with received
466 		     * response len.
467 		     */
468 		    (priv->rx.databuf_count + remaining <= priv->expected_data_len))
469 			memcpy(priv->response_buf + priv->rx.databuf_count,
470 			       buf, remaining);
471 		mutex_unlock(&priv->lock);
472 
473 		priv->rx.databuf_count += remaining;
474 
475 		/*
476 		 * Reached expected len advertised by the IMU for the current
477 		 * packet. Pass it to the upper layer (for us it is just valid).
478 		 */
479 		if (priv->rx.databuf_count == priv->rx.expected_len) {
480 			bno055_ser_handle_rx(priv, STATUS_OK);
481 			priv->rx.state = RX_IDLE;
482 		}
483 		break;
484 	}
485 
486 	return size;
487 }
488 
489 static const struct serdev_device_ops bno055_ser_serdev_ops = {
490 	.receive_buf = bno055_ser_receive_buf,
491 	.write_wakeup = serdev_device_write_wakeup,
492 };
493 
494 static const struct regmap_bus bno055_ser_regmap_bus = {
495 	.write = bno055_ser_write_reg,
496 	.read = bno055_ser_read_reg,
497 };
498 
bno055_ser_probe(struct serdev_device * serdev)499 static int bno055_ser_probe(struct serdev_device *serdev)
500 {
501 	struct bno055_ser_priv *priv;
502 	struct regmap *regmap;
503 	int ret;
504 
505 	priv = devm_kzalloc(&serdev->dev, sizeof(*priv), GFP_KERNEL);
506 	if (!priv)
507 		return -ENOMEM;
508 
509 	serdev_device_set_drvdata(serdev, priv);
510 	priv->serdev = serdev;
511 	mutex_init(&priv->lock);
512 	init_completion(&priv->cmd_complete);
513 
514 	serdev_device_set_client_ops(serdev, &bno055_ser_serdev_ops);
515 	ret = devm_serdev_device_open(&serdev->dev, serdev);
516 	if (ret)
517 		return ret;
518 
519 	if (serdev_device_set_baudrate(serdev, 115200) != 115200) {
520 		dev_err(&serdev->dev, "Cannot set required baud rate");
521 		return -EIO;
522 	}
523 
524 	ret = serdev_device_set_parity(serdev, SERDEV_PARITY_NONE);
525 	if (ret) {
526 		dev_err(&serdev->dev, "Cannot set required parity setting");
527 		return ret;
528 	}
529 	serdev_device_set_flow_control(serdev, false);
530 
531 	regmap = devm_regmap_init(&serdev->dev, &bno055_ser_regmap_bus,
532 				  priv, &bno055_regmap_config);
533 	if (IS_ERR(regmap))
534 		return dev_err_probe(&serdev->dev, PTR_ERR(regmap),
535 				     "Unable to init register map");
536 
537 	return bno055_probe(&serdev->dev, regmap,
538 			    BNO055_SER_XFER_BURST_BREAK_THRESHOLD, false);
539 }
540 
541 static const struct of_device_id bno055_ser_of_match[] = {
542 	{ .compatible = "bosch,bno055" },
543 	{ }
544 };
545 MODULE_DEVICE_TABLE(of, bno055_ser_of_match);
546 
547 static struct serdev_device_driver bno055_ser_driver = {
548 	.driver = {
549 		.name = "bno055-ser",
550 		.of_match_table = bno055_ser_of_match,
551 	},
552 	.probe = bno055_ser_probe,
553 };
554 module_serdev_device_driver(bno055_ser_driver);
555 
556 MODULE_AUTHOR("Andrea Merello <andrea.merello@iit.it>");
557 MODULE_DESCRIPTION("Bosch BNO055 serdev interface");
558 MODULE_IMPORT_NS("IIO_BNO055");
559 MODULE_LICENSE("GPL");
560