1 // SPDX-License-Identifier: GPL-2.0+
3 * ADE7854/58/68/78 Polyphase Multifunction Energy Metering IC Driver (SPI Bus)
5 * Copyright 2010 Analog Devices Inc.
8 #include <linux/device.h>
9 #include <linux/kernel.h>
10 #include <linux/spi/spi.h>
11 #include <linux/slab.h>
12 #include <linux/module.h>
14 #include <linux/iio/iio.h>
17 static int ade7854_spi_write_reg(struct device *dev,
23 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
24 struct ade7854_state *st = iio_priv(indio_dev);
25 struct spi_transfer xfer = {
31 mutex_lock(&st->buf_lock);
32 st->tx[0] = ADE7854_WRITE_REG;
33 st->tx[1] = (reg_address >> 8) & 0xFF;
34 st->tx[2] = reg_address & 0xFF;
37 st->tx[3] = val & 0xFF;
41 st->tx[3] = (val >> 8) & 0xFF;
42 st->tx[4] = val & 0xFF;
46 st->tx[3] = (val >> 16) & 0xFF;
47 st->tx[4] = (val >> 8) & 0xFF;
48 st->tx[5] = val & 0xFF;
52 st->tx[3] = (val >> 24) & 0xFF;
53 st->tx[4] = (val >> 16) & 0xFF;
54 st->tx[5] = (val >> 8) & 0xFF;
55 st->tx[6] = val & 0xFF;
62 ret = spi_sync_transfer(st->spi, &xfer, 1);
64 mutex_unlock(&st->buf_lock);
69 static int ade7854_spi_read_reg(struct device *dev,
74 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
75 struct ade7854_state *st = iio_priv(indio_dev);
77 struct spi_transfer xfers[] = {
89 mutex_lock(&st->buf_lock);
91 st->tx[0] = ADE7854_READ_REG;
92 st->tx[1] = (reg_address >> 8) & 0xFF;
93 st->tx[2] = reg_address & 0xFF;
95 ret = spi_sync_transfer(st->spi, xfers, ARRAY_SIZE(xfers));
97 dev_err(&st->spi->dev, "problem when reading register 0x%02X",
107 *val = be16_to_cpup((const __be16 *)st->rx);
110 *val = (st->rx[0] << 16) | (st->rx[1] << 8) | st->rx[2];
113 *val = be32_to_cpup((const __be32 *)st->rx);
118 mutex_unlock(&st->buf_lock);
122 static int ade7854_spi_probe(struct spi_device *spi)
124 struct ade7854_state *st;
125 struct iio_dev *indio_dev;
127 indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
130 st = iio_priv(indio_dev);
131 spi_set_drvdata(spi, indio_dev);
132 st->read_reg = ade7854_spi_read_reg;
133 st->write_reg = ade7854_spi_write_reg;
137 return ade7854_probe(indio_dev, &spi->dev);
140 static const struct spi_device_id ade7854_id[] = {
147 MODULE_DEVICE_TABLE(spi, ade7854_id);
149 static struct spi_driver ade7854_driver = {
153 .probe = ade7854_spi_probe,
154 .id_table = ade7854_id,
156 module_spi_driver(ade7854_driver);
159 MODULE_DESCRIPTION("Analog Devices ADE7854/58/68/78 SPI Driver");
160 MODULE_LICENSE("GPL v2");