1 // SPDX-License-Identifier: GPL-2.0-or-later
7 * This driver will read and write the value of 4 counters to w1_slave file in
9 * Inspired by the w1_therm and w1_ds2431 drivers.
12 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/moduleparam.h>
15 #include <linux/device.h>
16 #include <linux/types.h>
17 #include <linux/delay.h>
18 #include <linux/crc16.h>
22 #define W1_COUNTER_DS2423 0x1D
24 #define CRC16_VALID 0xb001
27 #define COUNTER_COUNT 4
28 #define READ_BYTE_COUNT 42
30 static ssize_t w1_slave_show(struct device *device,
31 struct device_attribute *attr, char *out_buf)
33 struct w1_slave *sl = dev_to_w1_slave(device);
34 struct w1_master *dev = sl->master;
35 u8 rbuf[COUNTER_COUNT * READ_BYTE_COUNT];
46 rom_addr = (12 << 5) + 31;
48 wrbuf[1] = rom_addr & 0xFF;
49 wrbuf[2] = rom_addr >> 8;
50 mutex_lock(&dev->bus_mutex);
51 if (!w1_reset_select_slave(sl)) {
52 w1_write_block(dev, wrbuf, 3);
54 for (p = 0; p < 4; p++) {
56 * 1 byte for first bytes in ram page read
58 * 4 bytes for zero bits
60 * 31 remaining bytes from the ram page
62 read_byte_count += w1_read_block(dev,
63 rbuf + (p * READ_BYTE_COUNT), READ_BYTE_COUNT);
64 for (ii = 0; ii < READ_BYTE_COUNT; ++ii)
65 c -= snprintf(out_buf + PAGE_SIZE - c,
67 rbuf[(p * READ_BYTE_COUNT) + ii]);
68 if (read_byte_count != (p + 1) * READ_BYTE_COUNT) {
70 "w1_counter_read() returned %u bytes "
71 "instead of %d bytes wanted.\n",
74 c -= snprintf(out_buf + PAGE_SIZE - c,
78 crc = crc16(CRC16_INIT, wrbuf, 3);
79 crc = crc16(crc, rbuf, 11);
82 * DS2423 calculates crc from all bytes
83 * read after the previous crc bytes.
85 crc = crc16(CRC16_INIT,
87 ((p - 1) * READ_BYTE_COUNT),
90 if (crc == CRC16_VALID) {
92 for (ii = 4; ii > 0; ii--) {
95 READ_BYTE_COUNT) + ii];
97 c -= snprintf(out_buf + PAGE_SIZE - c,
98 c, "crc=YES c=%d\n", result);
100 c -= snprintf(out_buf + PAGE_SIZE - c,
106 c -= snprintf(out_buf + PAGE_SIZE - c, c, "Connection error");
108 mutex_unlock(&dev->bus_mutex);
109 return PAGE_SIZE - c;
112 static DEVICE_ATTR_RO(w1_slave);
114 static struct attribute *w1_f1d_attrs[] = {
115 &dev_attr_w1_slave.attr,
118 ATTRIBUTE_GROUPS(w1_f1d);
120 static struct w1_family_ops w1_f1d_fops = {
121 .groups = w1_f1d_groups,
124 static struct w1_family w1_family_1d = {
125 .fid = W1_COUNTER_DS2423,
126 .fops = &w1_f1d_fops,
128 module_w1_family(w1_family_1d);
131 MODULE_DESCRIPTION("w1 family 1d driver for DS2423, 4 counters and 4kb ram");
132 MODULE_LICENSE("GPL");
133 MODULE_ALIAS("w1-family-" __stringify(W1_COUNTER_DS2423));