sca3000_core.c revision e5e26dd5bb740c34c975e2ae059126ba3486a1ce
1/*
2 * sca3000_core.c -- support VTI sca3000 series accelerometers via SPI
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 as published by
6 * the Free Software Foundation.
7 *
8 * Copyright (c) 2009 Jonathan Cameron <jic23@kernel.org>
9 *
10 * See industrialio/accels/sca3000.h for comments.
11 */
12
13#include <linux/interrupt.h>
14#include <linux/fs.h>
15#include <linux/device.h>
16#include <linux/slab.h>
17#include <linux/kernel.h>
18#include <linux/spi/spi.h>
19#include <linux/sysfs.h>
20#include <linux/module.h>
21#include <linux/iio/iio.h>
22#include <linux/iio/sysfs.h>
23#include <linux/iio/events.h>
24#include <linux/iio/buffer.h>
25
26#include "sca3000.h"
27
28enum sca3000_variant {
29	d01,
30	e02,
31	e04,
32	e05,
33};
34
35/* Note where option modes are not defined, the chip simply does not
36 * support any.
37 * Other chips in the sca3000 series use i2c and are not included here.
38 *
39 * Some of these devices are only listed in the family data sheet and
40 * do not actually appear to be available.
41 */
42static const struct sca3000_chip_info sca3000_spi_chip_info_tbl[] = {
43	[d01] = {
44		.scale = 7357,
45		.temp_output = true,
46		.measurement_mode_freq = 250,
47		.option_mode_1 = SCA3000_OP_MODE_BYPASS,
48		.option_mode_1_freq = 250,
49		.mot_det_mult_xz = {50, 100, 200, 350, 650, 1300},
50		.mot_det_mult_y = {50, 100, 150, 250, 450, 850, 1750},
51	},
52	[e02] = {
53		.scale = 9810,
54		.measurement_mode_freq = 125,
55		.option_mode_1 = SCA3000_OP_MODE_NARROW,
56		.option_mode_1_freq = 63,
57		.mot_det_mult_xz = {100, 150, 300, 550, 1050, 2050},
58		.mot_det_mult_y = {50, 100, 200, 350, 700, 1350, 2700},
59	},
60	[e04] = {
61		.scale = 19620,
62		.measurement_mode_freq = 100,
63		.option_mode_1 = SCA3000_OP_MODE_NARROW,
64		.option_mode_1_freq = 50,
65		.option_mode_2 = SCA3000_OP_MODE_WIDE,
66		.option_mode_2_freq = 400,
67		.mot_det_mult_xz = {200, 300, 600, 1100, 2100, 4100},
68		.mot_det_mult_y = {100, 200, 400, 7000, 1400, 2700, 54000},
69	},
70	[e05] = {
71		.scale = 61313,
72		.measurement_mode_freq = 200,
73		.option_mode_1 = SCA3000_OP_MODE_NARROW,
74		.option_mode_1_freq = 50,
75		.option_mode_2 = SCA3000_OP_MODE_WIDE,
76		.option_mode_2_freq = 400,
77		.mot_det_mult_xz = {600, 900, 1700, 3200, 6100, 11900},
78		.mot_det_mult_y = {300, 600, 1200, 2000, 4100, 7800, 15600},
79	},
80};
81
82int sca3000_write_reg(struct sca3000_state *st, u8 address, u8 val)
83{
84	st->tx[0] = SCA3000_WRITE_REG(address);
85	st->tx[1] = val;
86	return spi_write(st->us, st->tx, 2);
87}
88
89int sca3000_read_data_short(struct sca3000_state *st,
90			    uint8_t reg_address_high,
91			    int len)
92{
93	struct spi_transfer xfer[2] = {
94		{
95			.len = 1,
96			.tx_buf = st->tx,
97		}, {
98			.len = len,
99			.rx_buf = st->rx,
100		}
101	};
102	st->tx[0] = SCA3000_READ_REG(reg_address_high);
103
104	return spi_sync_transfer(st->us, xfer, ARRAY_SIZE(xfer));
105}
106
107/**
108 * sca3000_reg_lock_on() test if the ctrl register lock is on
109 *
110 * Lock must be held.
111 **/
112static int sca3000_reg_lock_on(struct sca3000_state *st)
113{
114	int ret;
115
116	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_STATUS, 1);
117	if (ret < 0)
118		return ret;
119
120	return !(st->rx[0] & SCA3000_LOCKED);
121}
122
123/**
124 * __sca3000_unlock_reg_lock() unlock the control registers
125 *
126 * Note the device does not appear to support doing this in a single transfer.
127 * This should only ever be used as part of ctrl reg read.
128 * Lock must be held before calling this
129 **/
130static int __sca3000_unlock_reg_lock(struct sca3000_state *st)
131{
132	struct spi_transfer xfer[3] = {
133		{
134			.len = 2,
135			.cs_change = 1,
136			.tx_buf = st->tx,
137		}, {
138			.len = 2,
139			.cs_change = 1,
140			.tx_buf = st->tx + 2,
141		}, {
142			.len = 2,
143			.tx_buf = st->tx + 4,
144		},
145	};
146	st->tx[0] = SCA3000_WRITE_REG(SCA3000_REG_ADDR_UNLOCK);
147	st->tx[1] = 0x00;
148	st->tx[2] = SCA3000_WRITE_REG(SCA3000_REG_ADDR_UNLOCK);
149	st->tx[3] = 0x50;
150	st->tx[4] = SCA3000_WRITE_REG(SCA3000_REG_ADDR_UNLOCK);
151	st->tx[5] = 0xA0;
152
153	return spi_sync_transfer(st->us, xfer, ARRAY_SIZE(xfer));
154}
155
156/**
157 * sca3000_write_ctrl_reg() write to a lock protect ctrl register
158 * @sel: selects which registers we wish to write to
159 * @val: the value to be written
160 *
161 * Certain control registers are protected against overwriting by the lock
162 * register and use a shared write address. This function allows writing of
163 * these registers.
164 * Lock must be held.
165 **/
166static int sca3000_write_ctrl_reg(struct sca3000_state *st,
167				  uint8_t sel,
168				  uint8_t val)
169{
170
171	int ret;
172
173	ret = sca3000_reg_lock_on(st);
174	if (ret < 0)
175		goto error_ret;
176	if (ret) {
177		ret = __sca3000_unlock_reg_lock(st);
178		if (ret)
179			goto error_ret;
180	}
181
182	/* Set the control select register */
183	ret = sca3000_write_reg(st, SCA3000_REG_ADDR_CTRL_SEL, sel);
184	if (ret)
185		goto error_ret;
186
187	/* Write the actual value into the register */
188	ret = sca3000_write_reg(st, SCA3000_REG_ADDR_CTRL_DATA, val);
189
190error_ret:
191	return ret;
192}
193
194/* Crucial that lock is called before calling this */
195/**
196 * sca3000_read_ctrl_reg() read from lock protected control register.
197 *
198 * Lock must be held.
199 **/
200static int sca3000_read_ctrl_reg(struct sca3000_state *st,
201				 u8 ctrl_reg)
202{
203	int ret;
204
205	ret = sca3000_reg_lock_on(st);
206	if (ret < 0)
207		goto error_ret;
208	if (ret) {
209		ret = __sca3000_unlock_reg_lock(st);
210		if (ret)
211			goto error_ret;
212	}
213	/* Set the control select register */
214	ret = sca3000_write_reg(st, SCA3000_REG_ADDR_CTRL_SEL, ctrl_reg);
215	if (ret)
216		goto error_ret;
217	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_CTRL_DATA, 1);
218	if (ret)
219		goto error_ret;
220	else
221		return st->rx[0];
222error_ret:
223	return ret;
224}
225
226#ifdef SCA3000_DEBUG
227/**
228 * sca3000_check_status() check the status register
229 *
230 * Only used for debugging purposes
231 **/
232static int sca3000_check_status(struct device *dev)
233{
234	int ret;
235	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
236	struct sca3000_state *st = iio_priv(indio_dev);
237
238	mutex_lock(&st->lock);
239	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_STATUS, 1);
240	if (ret < 0)
241		goto error_ret;
242	if (st->rx[0] & SCA3000_EEPROM_CS_ERROR)
243		dev_err(dev, "eeprom error\n");
244	if (st->rx[0] & SCA3000_SPI_FRAME_ERROR)
245		dev_err(dev, "Previous SPI Frame was corrupt\n");
246
247error_ret:
248	mutex_unlock(&st->lock);
249	return ret;
250}
251#endif /* SCA3000_DEBUG */
252
253
254/**
255 * sca3000_show_reg() - sysfs interface to read the chip revision number
256 **/
257static ssize_t sca3000_show_rev(struct device *dev,
258				struct device_attribute *attr,
259				char *buf)
260{
261	int len = 0, ret;
262	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
263	struct sca3000_state *st = iio_priv(indio_dev);
264
265	mutex_lock(&st->lock);
266	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_REVID, 1);
267	if (ret < 0)
268		goto error_ret;
269	len += sprintf(buf + len,
270		       "major=%d, minor=%d\n",
271		       st->rx[0] & SCA3000_REVID_MAJOR_MASK,
272		       st->rx[0] & SCA3000_REVID_MINOR_MASK);
273error_ret:
274	mutex_unlock(&st->lock);
275
276	return ret ? ret : len;
277}
278
279/**
280 * sca3000_show_available_measurement_modes() display available modes
281 *
282 * This is all read from chip specific data in the driver. Not all
283 * of the sca3000 series support modes other than normal.
284 **/
285static ssize_t
286sca3000_show_available_measurement_modes(struct device *dev,
287					 struct device_attribute *attr,
288					 char *buf)
289{
290	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
291	struct sca3000_state *st = iio_priv(indio_dev);
292	int len = 0;
293
294	len += sprintf(buf + len, "0 - normal mode");
295	switch (st->info->option_mode_1) {
296	case SCA3000_OP_MODE_NARROW:
297		len += sprintf(buf + len, ", 1 - narrow mode");
298		break;
299	case SCA3000_OP_MODE_BYPASS:
300		len += sprintf(buf + len, ", 1 - bypass mode");
301		break;
302	}
303	switch (st->info->option_mode_2) {
304	case SCA3000_OP_MODE_WIDE:
305		len += sprintf(buf + len, ", 2 - wide mode");
306		break;
307	}
308	/* always supported */
309	len += sprintf(buf + len, " 3 - motion detection\n");
310
311	return len;
312}
313
314/**
315 * sca3000_show_measurmenet_mode() sysfs read of current mode
316 **/
317static ssize_t
318sca3000_show_measurement_mode(struct device *dev,
319			      struct device_attribute *attr,
320			      char *buf)
321{
322	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
323	struct sca3000_state *st = iio_priv(indio_dev);
324	int len = 0, ret;
325
326	mutex_lock(&st->lock);
327	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_MODE, 1);
328	if (ret)
329		goto error_ret;
330	/* mask bottom 2 bits - only ones that are relevant */
331	st->rx[0] &= 0x03;
332	switch (st->rx[0]) {
333	case SCA3000_MEAS_MODE_NORMAL:
334		len += sprintf(buf + len, "0 - normal mode\n");
335		break;
336	case SCA3000_MEAS_MODE_MOT_DET:
337		len += sprintf(buf + len, "3 - motion detection\n");
338		break;
339	case SCA3000_MEAS_MODE_OP_1:
340		switch (st->info->option_mode_1) {
341		case SCA3000_OP_MODE_NARROW:
342			len += sprintf(buf + len, "1 - narrow mode\n");
343			break;
344		case SCA3000_OP_MODE_BYPASS:
345			len += sprintf(buf + len, "1 - bypass mode\n");
346			break;
347		}
348		break;
349	case SCA3000_MEAS_MODE_OP_2:
350		switch (st->info->option_mode_2) {
351		case SCA3000_OP_MODE_WIDE:
352			len += sprintf(buf + len, "2 - wide mode\n");
353			break;
354		}
355		break;
356	}
357
358error_ret:
359	mutex_unlock(&st->lock);
360
361	return ret ? ret : len;
362}
363
364/**
365 * sca3000_store_measurement_mode() set the current mode
366 **/
367static ssize_t
368sca3000_store_measurement_mode(struct device *dev,
369			       struct device_attribute *attr,
370			       const char *buf,
371			       size_t len)
372{
373	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
374	struct sca3000_state *st = iio_priv(indio_dev);
375	int ret;
376	u8 mask = 0x03;
377	u8 val;
378
379	mutex_lock(&st->lock);
380	ret = kstrtou8(buf, 10, &val);
381	if (ret)
382		goto error_ret;
383	if (val > 3) {
384		ret = -EINVAL;
385		goto error_ret;
386	}
387	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_MODE, 1);
388	if (ret)
389		goto error_ret;
390	st->rx[0] &= ~mask;
391	st->rx[0] |= (val & mask);
392	ret = sca3000_write_reg(st, SCA3000_REG_ADDR_MODE, st->rx[0]);
393	if (ret)
394		goto error_ret;
395	mutex_unlock(&st->lock);
396
397	return len;
398
399error_ret:
400	mutex_unlock(&st->lock);
401
402	return ret;
403}
404
405
406/* Not even vaguely standard attributes so defined here rather than
407 * in the relevant IIO core headers
408 */
409static IIO_DEVICE_ATTR(measurement_mode_available, S_IRUGO,
410		       sca3000_show_available_measurement_modes,
411		       NULL, 0);
412
413static IIO_DEVICE_ATTR(measurement_mode, S_IRUGO | S_IWUSR,
414		       sca3000_show_measurement_mode,
415		       sca3000_store_measurement_mode,
416		       0);
417
418/* More standard attributes */
419
420static IIO_DEVICE_ATTR(revision, S_IRUGO, sca3000_show_rev, NULL, 0);
421
422#define SCA3000_EVENT_MASK					\
423	(IIO_EV_BIT(IIO_EV_TYPE_MAG, IIO_EV_DIR_RISING))
424
425#define SCA3000_CHAN(index, mod)				\
426	{							\
427		.type = IIO_ACCEL,				\
428		.modified = 1,					\
429		.channel2 = mod,				\
430		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),	\
431		.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),\
432		.address = index,				\
433		.scan_index = index,				\
434		.scan_type = {					\
435			.sign = 's',				\
436			.realbits = 11,				\
437			.storagebits = 16,			\
438			.shift = 5,				\
439		},						\
440		.event_mask = SCA3000_EVENT_MASK,		\
441	 }
442
443static const struct iio_chan_spec sca3000_channels[] = {
444	SCA3000_CHAN(0, IIO_MOD_X),
445	SCA3000_CHAN(1, IIO_MOD_Y),
446	SCA3000_CHAN(2, IIO_MOD_Z),
447};
448
449static u8 sca3000_addresses[3][3] = {
450	[0] = {SCA3000_REG_ADDR_X_MSB, SCA3000_REG_CTRL_SEL_MD_X_TH,
451	       SCA3000_MD_CTRL_OR_X},
452	[1] = {SCA3000_REG_ADDR_Y_MSB, SCA3000_REG_CTRL_SEL_MD_Y_TH,
453	       SCA3000_MD_CTRL_OR_Y},
454	[2] = {SCA3000_REG_ADDR_Z_MSB, SCA3000_REG_CTRL_SEL_MD_Z_TH,
455	       SCA3000_MD_CTRL_OR_Z},
456};
457
458static int sca3000_read_raw(struct iio_dev *indio_dev,
459			    struct iio_chan_spec const *chan,
460			    int *val,
461			    int *val2,
462			    long mask)
463{
464	struct sca3000_state *st = iio_priv(indio_dev);
465	int ret;
466	u8 address;
467
468	switch (mask) {
469	case IIO_CHAN_INFO_RAW:
470		mutex_lock(&st->lock);
471		if (st->mo_det_use_count) {
472			mutex_unlock(&st->lock);
473			return -EBUSY;
474		}
475		address = sca3000_addresses[chan->address][0];
476		ret = sca3000_read_data_short(st, address, 2);
477		if (ret < 0) {
478			mutex_unlock(&st->lock);
479			return ret;
480		}
481		*val = (be16_to_cpup((__be16 *)st->rx) >> 3) & 0x1FFF;
482		*val = ((*val) << (sizeof(*val)*8 - 13)) >>
483			(sizeof(*val)*8 - 13);
484		mutex_unlock(&st->lock);
485		return IIO_VAL_INT;
486	case IIO_CHAN_INFO_SCALE:
487		*val = 0;
488		if (chan->type == IIO_ACCEL)
489			*val2 = st->info->scale;
490		else /* temperature */
491			*val2 = 555556;
492		return IIO_VAL_INT_PLUS_MICRO;
493	default:
494		return -EINVAL;
495	}
496}
497
498/**
499 * sca3000_read_av_freq() sysfs function to get available frequencies
500 *
501 * The later modes are only relevant to the ring buffer - and depend on current
502 * mode. Note that data sheet gives rather wide tolerances for these so integer
503 * division will give good enough answer and not all chips have them specified
504 * at all.
505 **/
506static ssize_t sca3000_read_av_freq(struct device *dev,
507			     struct device_attribute *attr,
508			     char *buf)
509{
510	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
511	struct sca3000_state *st = iio_priv(indio_dev);
512	int len = 0, ret, val;
513
514	mutex_lock(&st->lock);
515	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_MODE, 1);
516	val = st->rx[0];
517	mutex_unlock(&st->lock);
518	if (ret)
519		goto error_ret;
520
521	switch (val & 0x03) {
522	case SCA3000_MEAS_MODE_NORMAL:
523		len += sprintf(buf + len, "%d %d %d\n",
524			       st->info->measurement_mode_freq,
525			       st->info->measurement_mode_freq/2,
526			       st->info->measurement_mode_freq/4);
527		break;
528	case SCA3000_MEAS_MODE_OP_1:
529		len += sprintf(buf + len, "%d %d %d\n",
530			       st->info->option_mode_1_freq,
531			       st->info->option_mode_1_freq/2,
532			       st->info->option_mode_1_freq/4);
533		break;
534	case SCA3000_MEAS_MODE_OP_2:
535		len += sprintf(buf + len, "%d %d %d\n",
536			       st->info->option_mode_2_freq,
537			       st->info->option_mode_2_freq/2,
538			       st->info->option_mode_2_freq/4);
539		break;
540	}
541	return len;
542error_ret:
543	return ret;
544}
545/**
546 * __sca3000_get_base_frequency() obtain mode specific base frequency
547 *
548 * lock must be held
549 **/
550static inline int __sca3000_get_base_freq(struct sca3000_state *st,
551					  const struct sca3000_chip_info *info,
552					  int *base_freq)
553{
554	int ret;
555
556	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_MODE, 1);
557	if (ret)
558		goto error_ret;
559	switch (0x03 & st->rx[0]) {
560	case SCA3000_MEAS_MODE_NORMAL:
561		*base_freq = info->measurement_mode_freq;
562		break;
563	case SCA3000_MEAS_MODE_OP_1:
564		*base_freq = info->option_mode_1_freq;
565		break;
566	case SCA3000_MEAS_MODE_OP_2:
567		*base_freq = info->option_mode_2_freq;
568		break;
569	}
570error_ret:
571	return ret;
572}
573
574/**
575 * sca3000_read_frequency() sysfs interface to get the current frequency
576 **/
577static ssize_t sca3000_read_frequency(struct device *dev,
578			       struct device_attribute *attr,
579			       char *buf)
580{
581	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
582	struct sca3000_state *st = iio_priv(indio_dev);
583	int ret, len = 0, base_freq = 0, val;
584
585	mutex_lock(&st->lock);
586	ret = __sca3000_get_base_freq(st, st->info, &base_freq);
587	if (ret)
588		goto error_ret_mut;
589	ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL);
590	mutex_unlock(&st->lock);
591	if (ret)
592		goto error_ret;
593	val = ret;
594	if (base_freq > 0)
595		switch (val & 0x03) {
596		case 0x00:
597		case 0x03:
598			len = sprintf(buf, "%d\n", base_freq);
599			break;
600		case 0x01:
601			len = sprintf(buf, "%d\n", base_freq/2);
602			break;
603		case 0x02:
604			len = sprintf(buf, "%d\n", base_freq/4);
605			break;
606	}
607
608	return len;
609error_ret_mut:
610	mutex_unlock(&st->lock);
611error_ret:
612	return ret;
613}
614
615/**
616 * sca3000_set_frequency() sysfs interface to set the current frequency
617 **/
618static ssize_t sca3000_set_frequency(struct device *dev,
619			      struct device_attribute *attr,
620			      const char *buf,
621			      size_t len)
622{
623	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
624	struct sca3000_state *st = iio_priv(indio_dev);
625	int ret, base_freq = 0;
626	int ctrlval;
627	int val;
628
629	ret = kstrtoint(buf, 10, &val);
630	if (ret)
631		return ret;
632
633	mutex_lock(&st->lock);
634	/* What mode are we in? */
635	ret = __sca3000_get_base_freq(st, st->info, &base_freq);
636	if (ret)
637		goto error_free_lock;
638
639	ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL);
640	if (ret < 0)
641		goto error_free_lock;
642	ctrlval = ret;
643	/* clear the bits */
644	ctrlval &= ~0x03;
645
646	if (val == base_freq/2) {
647		ctrlval |= SCA3000_OUT_CTRL_BUF_DIV_2;
648	} else if (val == base_freq/4) {
649		ctrlval |= SCA3000_OUT_CTRL_BUF_DIV_4;
650	} else if (val != base_freq) {
651		ret = -EINVAL;
652		goto error_free_lock;
653	}
654	ret = sca3000_write_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL,
655				     ctrlval);
656error_free_lock:
657	mutex_unlock(&st->lock);
658
659	return ret ? ret : len;
660}
661
662/* Should only really be registered if ring buffer support is compiled in.
663 * Does no harm however and doing it right would add a fair bit of complexity
664 */
665static IIO_DEV_ATTR_SAMP_FREQ_AVAIL(sca3000_read_av_freq);
666
667static IIO_DEV_ATTR_SAMP_FREQ(S_IWUSR | S_IRUGO,
668			      sca3000_read_frequency,
669			      sca3000_set_frequency);
670
671
672/**
673 * sca3000_read_temp() sysfs interface to get the temperature when available
674 *
675* The alignment of data in here is downright odd. See data sheet.
676* Converting this into a meaningful value is left to inline functions in
677* userspace part of header.
678**/
679static ssize_t sca3000_read_temp(struct device *dev,
680				 struct device_attribute *attr,
681				 char *buf)
682{
683	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
684	struct sca3000_state *st = iio_priv(indio_dev);
685	int ret;
686	int val;
687	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_TEMP_MSB, 2);
688	if (ret < 0)
689		goto error_ret;
690	val = ((st->rx[0] & 0x3F) << 3) | ((st->rx[1] & 0xE0) >> 5);
691
692	return sprintf(buf, "%d\n", val);
693
694error_ret:
695	return ret;
696}
697static IIO_DEV_ATTR_TEMP_RAW(sca3000_read_temp);
698
699static IIO_CONST_ATTR_TEMP_SCALE("0.555556");
700static IIO_CONST_ATTR_TEMP_OFFSET("-214.6");
701
702/**
703 * sca3000_read_thresh() - query of a threshold
704 **/
705static int sca3000_read_thresh(struct iio_dev *indio_dev,
706			       u64 e,
707			       int *val)
708{
709	int ret, i;
710	struct sca3000_state *st = iio_priv(indio_dev);
711	int num = IIO_EVENT_CODE_EXTRACT_MODIFIER(e);
712	mutex_lock(&st->lock);
713	ret = sca3000_read_ctrl_reg(st, sca3000_addresses[num][1]);
714	mutex_unlock(&st->lock);
715	if (ret < 0)
716		return ret;
717	*val = 0;
718	if (num == 1)
719		for_each_set_bit(i, (unsigned long *)&ret,
720				 ARRAY_SIZE(st->info->mot_det_mult_y))
721			*val += st->info->mot_det_mult_y[i];
722	else
723		for_each_set_bit(i, (unsigned long *)&ret,
724				 ARRAY_SIZE(st->info->mot_det_mult_xz))
725			*val += st->info->mot_det_mult_xz[i];
726
727	return 0;
728}
729
730/**
731 * sca3000_write_thresh() control of threshold
732 **/
733static int sca3000_write_thresh(struct iio_dev *indio_dev,
734				u64 e,
735				int val)
736{
737	struct sca3000_state *st = iio_priv(indio_dev);
738	int num = IIO_EVENT_CODE_EXTRACT_MODIFIER(e);
739	int ret;
740	int i;
741	u8 nonlinear = 0;
742
743	if (num == 1) {
744		i = ARRAY_SIZE(st->info->mot_det_mult_y);
745		while (i > 0)
746			if (val >= st->info->mot_det_mult_y[--i]) {
747				nonlinear |= (1 << i);
748				val -= st->info->mot_det_mult_y[i];
749			}
750	} else {
751		i = ARRAY_SIZE(st->info->mot_det_mult_xz);
752		while (i > 0)
753			if (val >= st->info->mot_det_mult_xz[--i]) {
754				nonlinear |= (1 << i);
755				val -= st->info->mot_det_mult_xz[i];
756			}
757	}
758
759	mutex_lock(&st->lock);
760	ret = sca3000_write_ctrl_reg(st, sca3000_addresses[num][1], nonlinear);
761	mutex_unlock(&st->lock);
762
763	return ret;
764}
765
766static struct attribute *sca3000_attributes[] = {
767	&iio_dev_attr_revision.dev_attr.attr,
768	&iio_dev_attr_measurement_mode_available.dev_attr.attr,
769	&iio_dev_attr_measurement_mode.dev_attr.attr,
770	&iio_dev_attr_sampling_frequency_available.dev_attr.attr,
771	&iio_dev_attr_sampling_frequency.dev_attr.attr,
772	NULL,
773};
774
775static struct attribute *sca3000_attributes_with_temp[] = {
776	&iio_dev_attr_revision.dev_attr.attr,
777	&iio_dev_attr_measurement_mode_available.dev_attr.attr,
778	&iio_dev_attr_measurement_mode.dev_attr.attr,
779	&iio_dev_attr_sampling_frequency_available.dev_attr.attr,
780	&iio_dev_attr_sampling_frequency.dev_attr.attr,
781	/* Only present if temp sensor is */
782	&iio_dev_attr_in_temp_raw.dev_attr.attr,
783	&iio_const_attr_in_temp_offset.dev_attr.attr,
784	&iio_const_attr_in_temp_scale.dev_attr.attr,
785	NULL,
786};
787
788static const struct attribute_group sca3000_attribute_group = {
789	.attrs = sca3000_attributes,
790};
791
792static const struct attribute_group sca3000_attribute_group_with_temp = {
793	.attrs = sca3000_attributes_with_temp,
794};
795
796/* RING RELATED interrupt handler */
797/* depending on event, push to the ring buffer event chrdev or the event one */
798
799/**
800 * sca3000_event_handler() - handling ring and non ring events
801 *
802 * This function is complicated by the fact that the devices can signify ring
803 * and non ring events via the same interrupt line and they can only
804 * be distinguished via a read of the relevant status register.
805 **/
806static irqreturn_t sca3000_event_handler(int irq, void *private)
807{
808	struct iio_dev *indio_dev = private;
809	struct sca3000_state *st = iio_priv(indio_dev);
810	int ret, val;
811	s64 last_timestamp = iio_get_time_ns();
812
813	/* Could lead if badly timed to an extra read of status reg,
814	 * but ensures no interrupt is missed.
815	 */
816	mutex_lock(&st->lock);
817	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_INT_STATUS, 1);
818	val = st->rx[0];
819	mutex_unlock(&st->lock);
820	if (ret)
821		goto done;
822
823	sca3000_ring_int_process(val, indio_dev->buffer);
824
825	if (val & SCA3000_INT_STATUS_FREE_FALL)
826		iio_push_event(indio_dev,
827			       IIO_MOD_EVENT_CODE(IIO_ACCEL,
828						  0,
829						  IIO_MOD_X_AND_Y_AND_Z,
830						  IIO_EV_TYPE_MAG,
831						  IIO_EV_DIR_FALLING),
832			       last_timestamp);
833
834	if (val & SCA3000_INT_STATUS_Y_TRIGGER)
835		iio_push_event(indio_dev,
836			       IIO_MOD_EVENT_CODE(IIO_ACCEL,
837						  0,
838						  IIO_MOD_Y,
839						  IIO_EV_TYPE_MAG,
840						  IIO_EV_DIR_RISING),
841			       last_timestamp);
842
843	if (val & SCA3000_INT_STATUS_X_TRIGGER)
844		iio_push_event(indio_dev,
845			       IIO_MOD_EVENT_CODE(IIO_ACCEL,
846						  0,
847						  IIO_MOD_X,
848						  IIO_EV_TYPE_MAG,
849						  IIO_EV_DIR_RISING),
850			       last_timestamp);
851
852	if (val & SCA3000_INT_STATUS_Z_TRIGGER)
853		iio_push_event(indio_dev,
854			       IIO_MOD_EVENT_CODE(IIO_ACCEL,
855						  0,
856						  IIO_MOD_Z,
857						  IIO_EV_TYPE_MAG,
858						  IIO_EV_DIR_RISING),
859			       last_timestamp);
860
861done:
862	return IRQ_HANDLED;
863}
864
865/**
866 * sca3000_read_event_config() what events are enabled
867 **/
868static int sca3000_read_event_config(struct iio_dev *indio_dev,
869				     u64 e)
870{
871	struct sca3000_state *st = iio_priv(indio_dev);
872	int ret;
873	u8 protect_mask = 0x03;
874	int num = IIO_EVENT_CODE_EXTRACT_MODIFIER(e);
875
876	/* read current value of mode register */
877	mutex_lock(&st->lock);
878	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_MODE, 1);
879	if (ret)
880		goto error_ret;
881
882	if ((st->rx[0] & protect_mask) != SCA3000_MEAS_MODE_MOT_DET)
883		ret = 0;
884	else {
885		ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_MD_CTRL);
886		if (ret < 0)
887			goto error_ret;
888		/* only supporting logical or's for now */
889		ret = !!(ret & sca3000_addresses[num][2]);
890	}
891error_ret:
892	mutex_unlock(&st->lock);
893
894	return ret;
895}
896/**
897 * sca3000_query_free_fall_mode() is free fall mode enabled
898 **/
899static ssize_t sca3000_query_free_fall_mode(struct device *dev,
900					    struct device_attribute *attr,
901					    char *buf)
902{
903	int ret, len;
904	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
905	struct sca3000_state *st = iio_priv(indio_dev);
906	int val;
907
908	mutex_lock(&st->lock);
909	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_MODE, 1);
910	val = st->rx[0];
911	mutex_unlock(&st->lock);
912	if (ret < 0)
913		return ret;
914	len = sprintf(buf, "%d\n",
915		      !!(val & SCA3000_FREE_FALL_DETECT));
916	return len;
917}
918
919/**
920 * sca3000_set_free_fall_mode() simple on off control for free fall int
921 *
922 * In these chips the free fall detector should send an interrupt if
923 * the device falls more than 25cm.  This has not been tested due
924 * to fragile wiring.
925 **/
926
927static ssize_t sca3000_set_free_fall_mode(struct device *dev,
928					  struct device_attribute *attr,
929					  const char *buf,
930					  size_t len)
931{
932	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
933	struct sca3000_state *st = iio_priv(indio_dev);
934	u8 val;
935	int ret;
936	u8 protect_mask = SCA3000_FREE_FALL_DETECT;
937
938	mutex_lock(&st->lock);
939	ret = kstrtou8(buf, 10, &val);
940	if (ret)
941		goto error_ret;
942
943	/* read current value of mode register */
944	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_MODE, 1);
945	if (ret)
946		goto error_ret;
947
948	/*if off and should be on*/
949	if (val && !(st->rx[0] & protect_mask))
950		ret = sca3000_write_reg(st, SCA3000_REG_ADDR_MODE,
951					(st->rx[0] | SCA3000_FREE_FALL_DETECT));
952	/* if on and should be off */
953	else if (!val && (st->rx[0] & protect_mask))
954		ret = sca3000_write_reg(st, SCA3000_REG_ADDR_MODE,
955					(st->rx[0] & ~protect_mask));
956error_ret:
957	mutex_unlock(&st->lock);
958
959	return ret ? ret : len;
960}
961
962/**
963 * sca3000_set_mo_det() simple on off control for motion detector
964 *
965 * This is a per axis control, but enabling any will result in the
966 * motion detector unit being enabled.
967 * N.B. enabling motion detector stops normal data acquisition.
968 * There is a complexity in knowing which mode to return to when
969 * this mode is disabled.  Currently normal mode is assumed.
970 **/
971static int sca3000_write_event_config(struct iio_dev *indio_dev,
972				      u64 e,
973				      int state)
974{
975	struct sca3000_state *st = iio_priv(indio_dev);
976	int ret, ctrlval;
977	u8 protect_mask = 0x03;
978	int num = IIO_EVENT_CODE_EXTRACT_MODIFIER(e);
979
980	mutex_lock(&st->lock);
981	/* First read the motion detector config to find out if
982	 * this axis is on*/
983	ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_MD_CTRL);
984	if (ret < 0)
985		goto exit_point;
986	ctrlval = ret;
987	/* Off and should be on */
988	if (state && !(ctrlval & sca3000_addresses[num][2])) {
989		ret = sca3000_write_ctrl_reg(st,
990					     SCA3000_REG_CTRL_SEL_MD_CTRL,
991					     ctrlval |
992					     sca3000_addresses[num][2]);
993		if (ret)
994			goto exit_point;
995		st->mo_det_use_count++;
996	} else if (!state && (ctrlval & sca3000_addresses[num][2])) {
997		ret = sca3000_write_ctrl_reg(st,
998					     SCA3000_REG_CTRL_SEL_MD_CTRL,
999					     ctrlval &
1000					     ~(sca3000_addresses[num][2]));
1001		if (ret)
1002			goto exit_point;
1003		st->mo_det_use_count--;
1004	}
1005
1006	/* read current value of mode register */
1007	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_MODE, 1);
1008	if (ret)
1009		goto exit_point;
1010	/*if off and should be on*/
1011	if ((st->mo_det_use_count)
1012	    && ((st->rx[0] & protect_mask) != SCA3000_MEAS_MODE_MOT_DET))
1013		ret = sca3000_write_reg(st, SCA3000_REG_ADDR_MODE,
1014					(st->rx[0] & ~protect_mask)
1015					| SCA3000_MEAS_MODE_MOT_DET);
1016	/* if on and should be off */
1017	else if (!(st->mo_det_use_count)
1018		 && ((st->rx[0] & protect_mask) == SCA3000_MEAS_MODE_MOT_DET))
1019		ret = sca3000_write_reg(st, SCA3000_REG_ADDR_MODE,
1020					(st->rx[0] & ~protect_mask));
1021exit_point:
1022	mutex_unlock(&st->lock);
1023
1024	return ret;
1025}
1026
1027/* Free fall detector related event attribute */
1028static IIO_DEVICE_ATTR_NAMED(accel_xayaz_mag_falling_en,
1029			     in_accel_x&y&z_mag_falling_en,
1030			     S_IRUGO | S_IWUSR,
1031			     sca3000_query_free_fall_mode,
1032			     sca3000_set_free_fall_mode,
1033			     0);
1034
1035static IIO_CONST_ATTR_NAMED(accel_xayaz_mag_falling_period,
1036			    in_accel_x&y&z_mag_falling_period,
1037			    "0.226");
1038
1039static struct attribute *sca3000_event_attributes[] = {
1040	&iio_dev_attr_accel_xayaz_mag_falling_en.dev_attr.attr,
1041	&iio_const_attr_accel_xayaz_mag_falling_period.dev_attr.attr,
1042	NULL,
1043};
1044
1045static struct attribute_group sca3000_event_attribute_group = {
1046	.attrs = sca3000_event_attributes,
1047	.name = "events",
1048};
1049
1050/**
1051 * sca3000_clean_setup() get the device into a predictable state
1052 *
1053 * Devices use flash memory to store many of the register values
1054 * and hence can come up in somewhat unpredictable states.
1055 * Hence reset everything on driver load.
1056  **/
1057static int sca3000_clean_setup(struct sca3000_state *st)
1058{
1059	int ret;
1060
1061	mutex_lock(&st->lock);
1062	/* Ensure all interrupts have been acknowledged */
1063	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_INT_STATUS, 1);
1064	if (ret)
1065		goto error_ret;
1066
1067	/* Turn off all motion detection channels */
1068	ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_MD_CTRL);
1069	if (ret < 0)
1070		goto error_ret;
1071	ret = sca3000_write_ctrl_reg(st, SCA3000_REG_CTRL_SEL_MD_CTRL,
1072				     ret & SCA3000_MD_CTRL_PROT_MASK);
1073	if (ret)
1074		goto error_ret;
1075
1076	/* Disable ring buffer */
1077	ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL);
1078	ret = sca3000_write_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL,
1079				     (ret & SCA3000_OUT_CTRL_PROT_MASK)
1080				     | SCA3000_OUT_CTRL_BUF_X_EN
1081				     | SCA3000_OUT_CTRL_BUF_Y_EN
1082				     | SCA3000_OUT_CTRL_BUF_Z_EN
1083				     | SCA3000_OUT_CTRL_BUF_DIV_4);
1084	if (ret)
1085		goto error_ret;
1086	/* Enable interrupts, relevant to mode and set up as active low */
1087	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_INT_MASK, 1);
1088	if (ret)
1089		goto error_ret;
1090	ret = sca3000_write_reg(st,
1091				SCA3000_REG_ADDR_INT_MASK,
1092				(ret & SCA3000_INT_MASK_PROT_MASK)
1093				| SCA3000_INT_MASK_ACTIVE_LOW);
1094	if (ret)
1095		goto error_ret;
1096	/* Select normal measurement mode, free fall off, ring off */
1097	/* Ring in 12 bit mode - it is fine to overwrite reserved bits 3,5
1098	 * as that occurs in one of the example on the datasheet */
1099	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_MODE, 1);
1100	if (ret)
1101		goto error_ret;
1102	ret = sca3000_write_reg(st, SCA3000_REG_ADDR_MODE,
1103				(st->rx[0] & SCA3000_MODE_PROT_MASK));
1104	st->bpse = 11;
1105
1106error_ret:
1107	mutex_unlock(&st->lock);
1108	return ret;
1109}
1110
1111static const struct iio_info sca3000_info = {
1112	.attrs = &sca3000_attribute_group,
1113	.read_raw = &sca3000_read_raw,
1114	.event_attrs = &sca3000_event_attribute_group,
1115	.read_event_value = &sca3000_read_thresh,
1116	.write_event_value = &sca3000_write_thresh,
1117	.read_event_config = &sca3000_read_event_config,
1118	.write_event_config = &sca3000_write_event_config,
1119	.driver_module = THIS_MODULE,
1120};
1121
1122static const struct iio_info sca3000_info_with_temp = {
1123	.attrs = &sca3000_attribute_group_with_temp,
1124	.read_raw = &sca3000_read_raw,
1125	.read_event_value = &sca3000_read_thresh,
1126	.write_event_value = &sca3000_write_thresh,
1127	.read_event_config = &sca3000_read_event_config,
1128	.write_event_config = &sca3000_write_event_config,
1129	.driver_module = THIS_MODULE,
1130};
1131
1132static int sca3000_probe(struct spi_device *spi)
1133{
1134	int ret;
1135	struct sca3000_state *st;
1136	struct iio_dev *indio_dev;
1137
1138	indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
1139	if (!indio_dev)
1140		return -ENOMEM;
1141
1142	st = iio_priv(indio_dev);
1143	spi_set_drvdata(spi, indio_dev);
1144	st->us = spi;
1145	mutex_init(&st->lock);
1146	st->info = &sca3000_spi_chip_info_tbl[spi_get_device_id(spi)
1147					      ->driver_data];
1148
1149	indio_dev->dev.parent = &spi->dev;
1150	indio_dev->name = spi_get_device_id(spi)->name;
1151	if (st->info->temp_output)
1152		indio_dev->info = &sca3000_info_with_temp;
1153	else {
1154		indio_dev->info = &sca3000_info;
1155		indio_dev->channels = sca3000_channels;
1156		indio_dev->num_channels = ARRAY_SIZE(sca3000_channels);
1157	}
1158	indio_dev->modes = INDIO_DIRECT_MODE;
1159
1160	sca3000_configure_ring(indio_dev);
1161	ret = iio_device_register(indio_dev);
1162	if (ret < 0)
1163		return ret;
1164
1165	ret = iio_buffer_register(indio_dev,
1166				  sca3000_channels,
1167				  ARRAY_SIZE(sca3000_channels));
1168	if (ret < 0)
1169		goto error_unregister_dev;
1170	if (indio_dev->buffer) {
1171		iio_scan_mask_set(indio_dev, indio_dev->buffer, 0);
1172		iio_scan_mask_set(indio_dev, indio_dev->buffer, 1);
1173		iio_scan_mask_set(indio_dev, indio_dev->buffer, 2);
1174	}
1175
1176	if (spi->irq) {
1177		ret = request_threaded_irq(spi->irq,
1178					   NULL,
1179					   &sca3000_event_handler,
1180					   IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
1181					   "sca3000",
1182					   indio_dev);
1183		if (ret)
1184			goto error_unregister_ring;
1185	}
1186	sca3000_register_ring_funcs(indio_dev);
1187	ret = sca3000_clean_setup(st);
1188	if (ret)
1189		goto error_free_irq;
1190	return 0;
1191
1192error_free_irq:
1193	if (spi->irq)
1194		free_irq(spi->irq, indio_dev);
1195error_unregister_ring:
1196	iio_buffer_unregister(indio_dev);
1197error_unregister_dev:
1198	iio_device_unregister(indio_dev);
1199	return ret;
1200}
1201
1202static int sca3000_stop_all_interrupts(struct sca3000_state *st)
1203{
1204	int ret;
1205
1206	mutex_lock(&st->lock);
1207	ret = sca3000_read_data_short(st, SCA3000_REG_ADDR_INT_MASK, 1);
1208	if (ret)
1209		goto error_ret;
1210	ret = sca3000_write_reg(st, SCA3000_REG_ADDR_INT_MASK,
1211				(st->rx[0] &
1212				 ~(SCA3000_INT_MASK_RING_THREE_QUARTER |
1213				   SCA3000_INT_MASK_RING_HALF |
1214				   SCA3000_INT_MASK_ALL_INTS)));
1215error_ret:
1216	mutex_unlock(&st->lock);
1217	return ret;
1218}
1219
1220static int sca3000_remove(struct spi_device *spi)
1221{
1222	struct iio_dev *indio_dev = spi_get_drvdata(spi);
1223	struct sca3000_state *st = iio_priv(indio_dev);
1224
1225	/* Must ensure no interrupts can be generated after this!*/
1226	sca3000_stop_all_interrupts(st);
1227	if (spi->irq)
1228		free_irq(spi->irq, indio_dev);
1229	iio_device_unregister(indio_dev);
1230	iio_buffer_unregister(indio_dev);
1231	sca3000_unconfigure_ring(indio_dev);
1232
1233	return 0;
1234}
1235
1236static const struct spi_device_id sca3000_id[] = {
1237	{"sca3000_d01", d01},
1238	{"sca3000_e02", e02},
1239	{"sca3000_e04", e04},
1240	{"sca3000_e05", e05},
1241	{}
1242};
1243MODULE_DEVICE_TABLE(spi, sca3000_id);
1244
1245static struct spi_driver sca3000_driver = {
1246	.driver = {
1247		.name = "sca3000",
1248		.owner = THIS_MODULE,
1249	},
1250	.probe = sca3000_probe,
1251	.remove = sca3000_remove,
1252	.id_table = sca3000_id,
1253};
1254module_spi_driver(sca3000_driver);
1255
1256MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1257MODULE_DESCRIPTION("VTI SCA3000 Series Accelerometers SPI driver");
1258MODULE_LICENSE("GPL v2");
1259