1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * gpio-max3191x.c - GPIO driver for Maxim MAX3191x industrial serializer
4 *
5 * Copyright (C) 2017 KUNBUS GmbH
6 *
7 * The MAX3191x makes 8 digital 24V inputs available via SPI.
8 * Multiple chips can be daisy-chained, the spec does not impose
9 * a limit on the number of chips and neither does this driver.
10 *
11 * Either of two modes is selectable: In 8-bit mode, only the state
12 * of the inputs is clocked out to achieve high readout speeds;
13 * In 16-bit mode, an additional status byte is clocked out with
14 * a CRC and indicator bits for undervoltage and overtemperature.
15 * The driver returns an error instead of potentially bogus data
16 * if any of these fault conditions occur.  However it does allow
17 * readout of non-faulting chips in the same daisy-chain.
18 *
19 * MAX3191x supports four debounce settings and the driver is
20 * capable of configuring these differently for each chip in the
21 * daisy-chain.
22 *
23 * If the chips are hardwired to 8-bit mode ("modesel" pulled high),
24 * gpio-pisosr.c can be used alternatively to this driver.
25 *
26 * https://datasheets.maximintegrated.com/en/ds/MAX31910.pdf
27 * https://datasheets.maximintegrated.com/en/ds/MAX31911.pdf
28 * https://datasheets.maximintegrated.com/en/ds/MAX31912.pdf
29 * https://datasheets.maximintegrated.com/en/ds/MAX31913.pdf
30 * https://datasheets.maximintegrated.com/en/ds/MAX31953-MAX31963.pdf
31 */
32
33#include <linux/bitmap.h>
34#include <linux/bitops.h>
35#include <linux/crc8.h>
36#include <linux/gpio/consumer.h>
37#include <linux/gpio/driver.h>
38#include <linux/module.h>
39#include <linux/spi/spi.h>
40
41enum max3191x_mode {
42	STATUS_BYTE_ENABLED,
43	STATUS_BYTE_DISABLED,
44};
45
46/**
47 * struct max3191x_chip - max3191x daisy-chain
48 * @gpio: GPIO controller struct
49 * @lock: protects read sequences
50 * @nchips: number of chips in the daisy-chain
51 * @mode: current mode, 0 for 16-bit, 1 for 8-bit;
52 *	for simplicity, all chips in the daisy-chain are assumed
53 *	to use the same mode
54 * @modesel_pins: GPIO pins to configure modesel of each chip
55 * @fault_pins: GPIO pins to detect fault of each chip
56 * @db0_pins: GPIO pins to configure debounce of each chip
57 * @db1_pins: GPIO pins to configure debounce of each chip
58 * @mesg: SPI message to perform a readout
59 * @xfer: SPI transfer used by @mesg
60 * @crc_error: bitmap signaling CRC error for each chip
61 * @overtemp: bitmap signaling overtemperature alarm for each chip
62 * @undervolt1: bitmap signaling undervoltage alarm for each chip
63 * @undervolt2: bitmap signaling undervoltage warning for each chip
64 * @fault: bitmap signaling assertion of @fault_pins for each chip
65 * @ignore_uv: whether to ignore undervoltage alarms;
66 *	set by a device property if the chips are powered through
67 *	5VOUT instead of VCC24V, in which case they will constantly
68 *	signal undervoltage;
69 *	for simplicity, all chips in the daisy-chain are assumed
70 *	to be powered the same way
71 */
72struct max3191x_chip {
73	struct gpio_chip gpio;
74	struct mutex lock;
75	u32 nchips;
76	enum max3191x_mode mode;
77	struct gpio_descs *modesel_pins;
78	struct gpio_descs *fault_pins;
79	struct gpio_descs *db0_pins;
80	struct gpio_descs *db1_pins;
81	struct spi_message mesg;
82	struct spi_transfer xfer;
83	unsigned long *crc_error;
84	unsigned long *overtemp;
85	unsigned long *undervolt1;
86	unsigned long *undervolt2;
87	unsigned long *fault;
88	bool ignore_uv;
89};
90
91#define MAX3191X_NGPIO 8
92#define MAX3191X_CRC8_POLYNOMIAL 0xa8 /* (x^5) + x^4 + x^2 + x^0 */
93
94DECLARE_CRC8_TABLE(max3191x_crc8);
95
96static int max3191x_get_direction(struct gpio_chip *gpio, unsigned int offset)
97{
98	return GPIO_LINE_DIRECTION_IN; /* always in */
99}
100
101static int max3191x_direction_input(struct gpio_chip *gpio, unsigned int offset)
102{
103	return 0;
104}
105
106static int max3191x_direction_output(struct gpio_chip *gpio,
107				     unsigned int offset, int value)
108{
109	return -EINVAL;
110}
111
112static void max3191x_set(struct gpio_chip *gpio, unsigned int offset, int value)
113{ }
114
115static void max3191x_set_multiple(struct gpio_chip *gpio, unsigned long *mask,
116				  unsigned long *bits)
117{ }
118
119static unsigned int max3191x_wordlen(struct max3191x_chip *max3191x)
120{
121	return max3191x->mode == STATUS_BYTE_ENABLED ? 2 : 1;
122}
123
124static int max3191x_readout_locked(struct max3191x_chip *max3191x)
125{
126	struct device *dev = max3191x->gpio.parent;
127	struct spi_device *spi = to_spi_device(dev);
128	int val, i, ot = 0, uv1 = 0;
129
130	val = spi_sync(spi, &max3191x->mesg);
131	if (val) {
132		dev_err_ratelimited(dev, "SPI receive error %d\n", val);
133		return val;
134	}
135
136	for (i = 0; i < max3191x->nchips; i++) {
137		if (max3191x->mode == STATUS_BYTE_ENABLED) {
138			u8 in	  = ((u8 *)max3191x->xfer.rx_buf)[i * 2];
139			u8 status = ((u8 *)max3191x->xfer.rx_buf)[i * 2 + 1];
140
141			val = (status & 0xf8) != crc8(max3191x_crc8, &in, 1, 0);
142			__assign_bit(i, max3191x->crc_error, val);
143			if (val)
144				dev_err_ratelimited(dev,
145					"chip %d: CRC error\n", i);
146
147			ot  = (status >> 1) & 1;
148			__assign_bit(i, max3191x->overtemp, ot);
149			if (ot)
150				dev_err_ratelimited(dev,
151					"chip %d: overtemperature\n", i);
152
153			if (!max3191x->ignore_uv) {
154				uv1 = !((status >> 2) & 1);
155				__assign_bit(i, max3191x->undervolt1, uv1);
156				if (uv1)
157					dev_err_ratelimited(dev,
158						"chip %d: undervoltage\n", i);
159
160				val = !(status & 1);
161				__assign_bit(i, max3191x->undervolt2, val);
162				if (val && !uv1)
163					dev_warn_ratelimited(dev,
164						"chip %d: voltage warn\n", i);
165			}
166		}
167
168		if (max3191x->fault_pins && !max3191x->ignore_uv) {
169			/* fault pin shared by all chips or per chip */
170			struct gpio_desc *fault_pin =
171				(max3191x->fault_pins->ndescs == 1)
172					? max3191x->fault_pins->desc[0]
173					: max3191x->fault_pins->desc[i];
174
175			val = gpiod_get_value_cansleep(fault_pin);
176			if (val < 0) {
177				dev_err_ratelimited(dev,
178					"GPIO read error %d\n", val);
179				return val;
180			}
181			__assign_bit(i, max3191x->fault, val);
182			if (val && !uv1 && !ot)
183				dev_err_ratelimited(dev,
184					"chip %d: fault\n", i);
185		}
186	}
187
188	return 0;
189}
190
191static bool max3191x_chip_is_faulting(struct max3191x_chip *max3191x,
192				      unsigned int chipnum)
193{
194	/* without status byte the only diagnostic is the fault pin */
195	if (!max3191x->ignore_uv && test_bit(chipnum, max3191x->fault))
196		return true;
197
198	if (max3191x->mode == STATUS_BYTE_DISABLED)
199		return false;
200
201	return test_bit(chipnum, max3191x->crc_error) ||
202	       test_bit(chipnum, max3191x->overtemp)  ||
203	       (!max3191x->ignore_uv &&
204		test_bit(chipnum, max3191x->undervolt1));
205}
206
207static int max3191x_get(struct gpio_chip *gpio, unsigned int offset)
208{
209	struct max3191x_chip *max3191x = gpiochip_get_data(gpio);
210	int ret, chipnum, wordlen = max3191x_wordlen(max3191x);
211	u8 in;
212
213	mutex_lock(&max3191x->lock);
214	ret = max3191x_readout_locked(max3191x);
215	if (ret)
216		goto out_unlock;
217
218	chipnum = offset / MAX3191X_NGPIO;
219	if (max3191x_chip_is_faulting(max3191x, chipnum)) {
220		ret = -EIO;
221		goto out_unlock;
222	}
223
224	in = ((u8 *)max3191x->xfer.rx_buf)[chipnum * wordlen];
225	ret = (in >> (offset % MAX3191X_NGPIO)) & 1;
226
227out_unlock:
228	mutex_unlock(&max3191x->lock);
229	return ret;
230}
231
232static int max3191x_get_multiple(struct gpio_chip *gpio, unsigned long *mask,
233				 unsigned long *bits)
234{
235	struct max3191x_chip *max3191x = gpiochip_get_data(gpio);
236	const unsigned int wordlen = max3191x_wordlen(max3191x);
237	int ret;
238	unsigned long bit;
239	unsigned long gpio_mask;
240	unsigned long in;
241
242	mutex_lock(&max3191x->lock);
243	ret = max3191x_readout_locked(max3191x);
244	if (ret)
245		goto out_unlock;
246
247	bitmap_zero(bits, gpio->ngpio);
248	for_each_set_clump8(bit, gpio_mask, mask, gpio->ngpio) {
249		unsigned int chipnum = bit / MAX3191X_NGPIO;
250
251		if (max3191x_chip_is_faulting(max3191x, chipnum)) {
252			ret = -EIO;
253			goto out_unlock;
254		}
255
256		in = ((u8 *)max3191x->xfer.rx_buf)[chipnum * wordlen];
257		in &= gpio_mask;
258		bitmap_set_value8(bits, in, bit);
259	}
260
261out_unlock:
262	mutex_unlock(&max3191x->lock);
263	return ret;
264}
265
266static int max3191x_set_config(struct gpio_chip *gpio, unsigned int offset,
267			       unsigned long config)
268{
269	struct max3191x_chip *max3191x = gpiochip_get_data(gpio);
270	u32 debounce, chipnum, db0_val, db1_val;
271
272	if (pinconf_to_config_param(config) != PIN_CONFIG_INPUT_DEBOUNCE)
273		return -ENOTSUPP;
274
275	if (!max3191x->db0_pins || !max3191x->db1_pins)
276		return -EINVAL;
277
278	debounce = pinconf_to_config_argument(config);
279	switch (debounce) {
280	case 0:
281		db0_val = 0;
282		db1_val = 0;
283		break;
284	case 1 ... 25:
285		db0_val = 0;
286		db1_val = 1;
287		break;
288	case 26 ... 750:
289		db0_val = 1;
290		db1_val = 0;
291		break;
292	case 751 ... 3000:
293		db0_val = 1;
294		db1_val = 1;
295		break;
296	default:
297		return -EINVAL;
298	}
299
300	if (max3191x->db0_pins->ndescs == 1)
301		chipnum = 0; /* all chips use the same pair of debounce pins */
302	else
303		chipnum = offset / MAX3191X_NGPIO; /* per chip debounce pins */
304
305	mutex_lock(&max3191x->lock);
306	gpiod_set_value_cansleep(max3191x->db0_pins->desc[chipnum], db0_val);
307	gpiod_set_value_cansleep(max3191x->db1_pins->desc[chipnum], db1_val);
308	mutex_unlock(&max3191x->lock);
309	return 0;
310}
311
312static void gpiod_set_array_single_value_cansleep(unsigned int ndescs,
313						  struct gpio_desc **desc,
314						  struct gpio_array *info,
315						  int value)
316{
317	unsigned long *values;
318
319	values = bitmap_alloc(ndescs, GFP_KERNEL);
320	if (!values)
321		return;
322
323	if (value)
324		bitmap_fill(values, ndescs);
325	else
326		bitmap_zero(values, ndescs);
327
328	gpiod_set_array_value_cansleep(ndescs, desc, info, values);
329	bitmap_free(values);
330}
331
332static struct gpio_descs *devm_gpiod_get_array_optional_count(
333				struct device *dev, const char *con_id,
334				enum gpiod_flags flags, unsigned int expected)
335{
336	struct gpio_descs *descs;
337	int found = gpiod_count(dev, con_id);
338
339	if (found == -ENOENT)
340		return NULL;
341
342	if (found != expected && found != 1) {
343		dev_err(dev, "ignoring %s-gpios: found %d, expected %u or 1\n",
344			con_id, found, expected);
345		return NULL;
346	}
347
348	descs = devm_gpiod_get_array_optional(dev, con_id, flags);
349
350	if (IS_ERR(descs)) {
351		dev_err(dev, "failed to get %s-gpios: %ld\n",
352			con_id, PTR_ERR(descs));
353		return NULL;
354	}
355
356	return descs;
357}
358
359static int max3191x_probe(struct spi_device *spi)
360{
361	struct device *dev = &spi->dev;
362	struct max3191x_chip *max3191x;
363	int n, ret;
364
365	max3191x = devm_kzalloc(dev, sizeof(*max3191x), GFP_KERNEL);
366	if (!max3191x)
367		return -ENOMEM;
368	spi_set_drvdata(spi, max3191x);
369
370	max3191x->nchips = 1;
371	device_property_read_u32(dev, "#daisy-chained-devices",
372				 &max3191x->nchips);
373
374	n = BITS_TO_LONGS(max3191x->nchips);
375	max3191x->crc_error   = devm_kcalloc(dev, n, sizeof(long), GFP_KERNEL);
376	max3191x->undervolt1  = devm_kcalloc(dev, n, sizeof(long), GFP_KERNEL);
377	max3191x->undervolt2  = devm_kcalloc(dev, n, sizeof(long), GFP_KERNEL);
378	max3191x->overtemp    = devm_kcalloc(dev, n, sizeof(long), GFP_KERNEL);
379	max3191x->fault       = devm_kcalloc(dev, n, sizeof(long), GFP_KERNEL);
380	max3191x->xfer.rx_buf = devm_kcalloc(dev, max3191x->nchips,
381								2, GFP_KERNEL);
382	if (!max3191x->crc_error || !max3191x->undervolt1 ||
383	    !max3191x->overtemp  || !max3191x->undervolt2 ||
384	    !max3191x->fault     || !max3191x->xfer.rx_buf)
385		return -ENOMEM;
386
387	max3191x->modesel_pins = devm_gpiod_get_array_optional_count(dev,
388				 "maxim,modesel", GPIOD_ASIS, max3191x->nchips);
389	max3191x->fault_pins   = devm_gpiod_get_array_optional_count(dev,
390				 "maxim,fault", GPIOD_IN, max3191x->nchips);
391	max3191x->db0_pins     = devm_gpiod_get_array_optional_count(dev,
392				 "maxim,db0", GPIOD_OUT_LOW, max3191x->nchips);
393	max3191x->db1_pins     = devm_gpiod_get_array_optional_count(dev,
394				 "maxim,db1", GPIOD_OUT_LOW, max3191x->nchips);
395
396	max3191x->mode = device_property_read_bool(dev, "maxim,modesel-8bit")
397				 ? STATUS_BYTE_DISABLED : STATUS_BYTE_ENABLED;
398	if (max3191x->modesel_pins)
399		gpiod_set_array_single_value_cansleep(
400				 max3191x->modesel_pins->ndescs,
401				 max3191x->modesel_pins->desc,
402				 max3191x->modesel_pins->info, max3191x->mode);
403
404	max3191x->ignore_uv = device_property_read_bool(dev,
405						  "maxim,ignore-undervoltage");
406
407	if (max3191x->db0_pins && max3191x->db1_pins &&
408	    max3191x->db0_pins->ndescs != max3191x->db1_pins->ndescs) {
409		dev_err(dev, "ignoring maxim,db*-gpios: array len mismatch\n");
410		devm_gpiod_put_array(dev, max3191x->db0_pins);
411		devm_gpiod_put_array(dev, max3191x->db1_pins);
412		max3191x->db0_pins = NULL;
413		max3191x->db1_pins = NULL;
414	}
415
416	max3191x->xfer.len = max3191x->nchips * max3191x_wordlen(max3191x);
417	spi_message_init_with_transfers(&max3191x->mesg, &max3191x->xfer, 1);
418
419	max3191x->gpio.label = spi->modalias;
420	max3191x->gpio.owner = THIS_MODULE;
421	max3191x->gpio.parent = dev;
422	max3191x->gpio.base = -1;
423	max3191x->gpio.ngpio = max3191x->nchips * MAX3191X_NGPIO;
424	max3191x->gpio.can_sleep = true;
425
426	max3191x->gpio.get_direction = max3191x_get_direction;
427	max3191x->gpio.direction_input = max3191x_direction_input;
428	max3191x->gpio.direction_output = max3191x_direction_output;
429	max3191x->gpio.set = max3191x_set;
430	max3191x->gpio.set_multiple = max3191x_set_multiple;
431	max3191x->gpio.get = max3191x_get;
432	max3191x->gpio.get_multiple = max3191x_get_multiple;
433	max3191x->gpio.set_config = max3191x_set_config;
434
435	mutex_init(&max3191x->lock);
436
437	ret = gpiochip_add_data(&max3191x->gpio, max3191x);
438	if (ret) {
439		mutex_destroy(&max3191x->lock);
440		return ret;
441	}
442
443	return 0;
444}
445
446static void max3191x_remove(struct spi_device *spi)
447{
448	struct max3191x_chip *max3191x = spi_get_drvdata(spi);
449
450	gpiochip_remove(&max3191x->gpio);
451	mutex_destroy(&max3191x->lock);
452}
453
454static int __init max3191x_register_driver(struct spi_driver *sdrv)
455{
456	crc8_populate_msb(max3191x_crc8, MAX3191X_CRC8_POLYNOMIAL);
457	return spi_register_driver(sdrv);
458}
459
460static const struct of_device_id max3191x_of_id[] = {
461	{ .compatible = "maxim,max31910" },
462	{ .compatible = "maxim,max31911" },
463	{ .compatible = "maxim,max31912" },
464	{ .compatible = "maxim,max31913" },
465	{ .compatible = "maxim,max31953" },
466	{ .compatible = "maxim,max31963" },
467	{ }
468};
469MODULE_DEVICE_TABLE(of, max3191x_of_id);
470
471static const struct spi_device_id max3191x_spi_id[] = {
472	{ "max31910" },
473	{ "max31911" },
474	{ "max31912" },
475	{ "max31913" },
476	{ "max31953" },
477	{ "max31963" },
478	{ }
479};
480MODULE_DEVICE_TABLE(spi, max3191x_spi_id);
481
482static struct spi_driver max3191x_driver = {
483	.driver = {
484		.name		= "max3191x",
485		.of_match_table	= max3191x_of_id,
486	},
487	.probe	  = max3191x_probe,
488	.remove	  = max3191x_remove,
489	.id_table = max3191x_spi_id,
490};
491module_driver(max3191x_driver, max3191x_register_driver, spi_unregister_driver);
492
493MODULE_AUTHOR("Lukas Wunner <lukas@wunner.de>");
494MODULE_DESCRIPTION("GPIO driver for Maxim MAX3191x industrial serializer");
495MODULE_LICENSE("GPL v2");
496