2 * SPI slave handler reporting uptime at reception of previous SPI message
4 * This SPI slave handler sends the time of reception of the last SPI message
5 * as two 32-bit unsigned integers in binary format and in network byte order,
6 * representing the number of seconds and fractional seconds (in microseconds)
9 * Copyright (C) 2016-2017 Glider bvba
11 * This file is subject to the terms and conditions of the GNU General Public
12 * License. See the file "COPYING" in the main directory of this archive
15 * Usage (assuming /dev/spidev2.0 corresponds to the SPI master on the remote
18 * # spidev_test -D /dev/spidev2.0 -p dummy-8B
21 * max speed: 500000 Hz (500 KHz)
22 * RX | 00 00 04 6D 00 09 5B BB ...
24 * seconds microseconds
27 #include <linux/completion.h>
28 #include <linux/module.h>
29 #include <linux/sched/clock.h>
30 #include <linux/spi/spi.h>
33 struct spi_slave_time_priv
{
34 struct spi_device
*spi
;
35 struct completion finished
;
36 struct spi_transfer xfer
;
37 struct spi_message msg
;
41 static int spi_slave_time_submit(struct spi_slave_time_priv
*priv
);
43 static void spi_slave_time_complete(void *arg
)
45 struct spi_slave_time_priv
*priv
= arg
;
48 ret
= priv
->msg
.status
;
52 ret
= spi_slave_time_submit(priv
);
59 dev_info(&priv
->spi
->dev
, "Terminating\n");
60 complete(&priv
->finished
);
63 static int spi_slave_time_submit(struct spi_slave_time_priv
*priv
)
70 rem_us
= do_div(ts
, 1000000000) / 1000;
72 priv
->buf
[0] = cpu_to_be32(ts
);
73 priv
->buf
[1] = cpu_to_be32(rem_us
);
75 spi_message_init_with_transfers(&priv
->msg
, &priv
->xfer
, 1);
77 priv
->msg
.complete
= spi_slave_time_complete
;
78 priv
->msg
.context
= priv
;
80 ret
= spi_async(priv
->spi
, &priv
->msg
);
82 dev_err(&priv
->spi
->dev
, "spi_async() failed %d\n", ret
);
87 static int spi_slave_time_probe(struct spi_device
*spi
)
89 struct spi_slave_time_priv
*priv
;
92 priv
= devm_kzalloc(&spi
->dev
, sizeof(*priv
), GFP_KERNEL
);
97 init_completion(&priv
->finished
);
98 priv
->xfer
.tx_buf
= priv
->buf
;
99 priv
->xfer
.len
= sizeof(priv
->buf
);
101 ret
= spi_slave_time_submit(priv
);
105 spi_set_drvdata(spi
, priv
);
109 static int spi_slave_time_remove(struct spi_device
*spi
)
111 struct spi_slave_time_priv
*priv
= spi_get_drvdata(spi
);
113 spi_slave_abort(spi
);
114 wait_for_completion(&priv
->finished
);
118 static struct spi_driver spi_slave_time_driver
= {
120 .name
= "spi-slave-time",
122 .probe
= spi_slave_time_probe
,
123 .remove
= spi_slave_time_remove
,
125 module_spi_driver(spi_slave_time_driver
);
127 MODULE_AUTHOR("Geert Uytterhoeven <geert+renesas@glider.be>");
128 MODULE_DESCRIPTION("SPI slave reporting uptime at previous SPI message");
129 MODULE_LICENSE("GPL v2");