GNU Linux-libre 5.16.19-gnu
[releases.git] / drivers / iio / accel / sca3000.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * sca3000_core.c -- support VTI sca3000 series accelerometers via SPI
4  *
5  * Copyright (c) 2009 Jonathan Cameron <jic23@kernel.org>
6  *
7  * See industrialio/accels/sca3000.h for comments.
8  */
9
10 #include <linux/interrupt.h>
11 #include <linux/fs.h>
12 #include <linux/device.h>
13 #include <linux/slab.h>
14 #include <linux/kernel.h>
15 #include <linux/spi/spi.h>
16 #include <linux/sysfs.h>
17 #include <linux/module.h>
18 #include <linux/uaccess.h>
19 #include <linux/iio/iio.h>
20 #include <linux/iio/sysfs.h>
21 #include <linux/iio/events.h>
22 #include <linux/iio/buffer.h>
23 #include <linux/iio/kfifo_buf.h>
24
25 #define SCA3000_WRITE_REG(a) (((a) << 2) | 0x02)
26 #define SCA3000_READ_REG(a) ((a) << 2)
27
28 #define SCA3000_REG_REVID_ADDR                          0x00
29 #define   SCA3000_REG_REVID_MAJOR_MASK                  GENMASK(8, 4)
30 #define   SCA3000_REG_REVID_MINOR_MASK                  GENMASK(3, 0)
31
32 #define SCA3000_REG_STATUS_ADDR                         0x02
33 #define   SCA3000_LOCKED                                BIT(5)
34 #define   SCA3000_EEPROM_CS_ERROR                       BIT(1)
35 #define   SCA3000_SPI_FRAME_ERROR                       BIT(0)
36
37 /* All reads done using register decrement so no need to directly access LSBs */
38 #define SCA3000_REG_X_MSB_ADDR                          0x05
39 #define SCA3000_REG_Y_MSB_ADDR                          0x07
40 #define SCA3000_REG_Z_MSB_ADDR                          0x09
41
42 #define SCA3000_REG_RING_OUT_ADDR                       0x0f
43
44 /* Temp read untested - the e05 doesn't have the sensor */
45 #define SCA3000_REG_TEMP_MSB_ADDR                       0x13
46
47 #define SCA3000_REG_MODE_ADDR                           0x14
48 #define SCA3000_MODE_PROT_MASK                          0x28
49 #define   SCA3000_REG_MODE_RING_BUF_ENABLE              BIT(7)
50 #define   SCA3000_REG_MODE_RING_BUF_8BIT                BIT(6)
51
52 /*
53  * Free fall detection triggers an interrupt if the acceleration
54  * is below a threshold for equivalent of 25cm drop
55  */
56 #define   SCA3000_REG_MODE_FREE_FALL_DETECT             BIT(4)
57 #define   SCA3000_REG_MODE_MEAS_MODE_NORMAL             0x00
58 #define   SCA3000_REG_MODE_MEAS_MODE_OP_1               0x01
59 #define   SCA3000_REG_MODE_MEAS_MODE_OP_2               0x02
60
61 /*
62  * In motion detection mode the accelerations are band pass filtered
63  * (approx 1 - 25Hz) and then a programmable threshold used to trigger
64  * and interrupt.
65  */
66 #define   SCA3000_REG_MODE_MEAS_MODE_MOT_DET            0x03
67 #define   SCA3000_REG_MODE_MODE_MASK                    0x03
68
69 #define SCA3000_REG_BUF_COUNT_ADDR                      0x15
70
71 #define SCA3000_REG_INT_STATUS_ADDR                     0x16
72 #define   SCA3000_REG_INT_STATUS_THREE_QUARTERS         BIT(7)
73 #define   SCA3000_REG_INT_STATUS_HALF                   BIT(6)
74
75 #define SCA3000_INT_STATUS_FREE_FALL                    BIT(3)
76 #define SCA3000_INT_STATUS_Y_TRIGGER                    BIT(2)
77 #define SCA3000_INT_STATUS_X_TRIGGER                    BIT(1)
78 #define SCA3000_INT_STATUS_Z_TRIGGER                    BIT(0)
79
80 /* Used to allow access to multiplexed registers */
81 #define SCA3000_REG_CTRL_SEL_ADDR                       0x18
82 /* Only available for SCA3000-D03 and SCA3000-D01 */
83 #define   SCA3000_REG_CTRL_SEL_I2C_DISABLE              0x01
84 #define   SCA3000_REG_CTRL_SEL_MD_CTRL                  0x02
85 #define   SCA3000_REG_CTRL_SEL_MD_Y_TH                  0x03
86 #define   SCA3000_REG_CTRL_SEL_MD_X_TH                  0x04
87 #define   SCA3000_REG_CTRL_SEL_MD_Z_TH                  0x05
88 /*
89  * BE VERY CAREFUL WITH THIS, IF 3 BITS ARE NOT SET the device
90  * will not function
91  */
92 #define   SCA3000_REG_CTRL_SEL_OUT_CTRL                 0x0B
93
94 #define     SCA3000_REG_OUT_CTRL_PROT_MASK              0xE0
95 #define     SCA3000_REG_OUT_CTRL_BUF_X_EN               0x10
96 #define     SCA3000_REG_OUT_CTRL_BUF_Y_EN               0x08
97 #define     SCA3000_REG_OUT_CTRL_BUF_Z_EN               0x04
98 #define     SCA3000_REG_OUT_CTRL_BUF_DIV_MASK           0x03
99 #define     SCA3000_REG_OUT_CTRL_BUF_DIV_4              0x02
100 #define     SCA3000_REG_OUT_CTRL_BUF_DIV_2              0x01
101
102
103 /*
104  * Control which motion detector interrupts are on.
105  * For now only OR combinations are supported.
106  */
107 #define SCA3000_MD_CTRL_PROT_MASK                       0xC0
108 #define SCA3000_MD_CTRL_OR_Y                            BIT(0)
109 #define SCA3000_MD_CTRL_OR_X                            BIT(1)
110 #define SCA3000_MD_CTRL_OR_Z                            BIT(2)
111 /* Currently unsupported */
112 #define SCA3000_MD_CTRL_AND_Y                           BIT(3)
113 #define SCA3000_MD_CTRL_AND_X                           BIT(4)
114 #define SCA3000_MD_CTRL_AND_Z                           BIT(5)
115
116 /*
117  * Some control registers of complex access methods requiring this register to
118  * be used to remove a lock.
119  */
120 #define SCA3000_REG_UNLOCK_ADDR                         0x1e
121
122 #define SCA3000_REG_INT_MASK_ADDR                       0x21
123 #define   SCA3000_REG_INT_MASK_PROT_MASK                0x1C
124
125 #define   SCA3000_REG_INT_MASK_RING_THREE_QUARTER       BIT(7)
126 #define   SCA3000_REG_INT_MASK_RING_HALF                BIT(6)
127
128 #define SCA3000_REG_INT_MASK_ALL_INTS                   0x02
129 #define SCA3000_REG_INT_MASK_ACTIVE_HIGH                0x01
130 #define SCA3000_REG_INT_MASK_ACTIVE_LOW                 0x00
131 /* Values of multiplexed registers (write to ctrl_data after select) */
132 #define SCA3000_REG_CTRL_DATA_ADDR                      0x22
133
134 /*
135  * Measurement modes available on some sca3000 series chips. Code assumes others
136  * may become available in the future.
137  *
138  * Bypass - Bypass the low-pass filter in the signal channel so as to increase
139  *          signal bandwidth.
140  *
141  * Narrow - Narrow low-pass filtering of the signal channel and half output
142  *          data rate by decimation.
143  *
144  * Wide - Widen low-pass filtering of signal channel to increase bandwidth
145  */
146 #define SCA3000_OP_MODE_BYPASS                          0x01
147 #define SCA3000_OP_MODE_NARROW                          0x02
148 #define SCA3000_OP_MODE_WIDE                            0x04
149 #define SCA3000_MAX_TX 6
150 #define SCA3000_MAX_RX 2
151
152 /**
153  * struct sca3000_state - device instance state information
154  * @us:                 the associated spi device
155  * @info:                       chip variant information
156  * @last_timestamp:             the timestamp of the last event
157  * @mo_det_use_count:           reference counter for the motion detection unit
158  * @lock:                       lock used to protect elements of sca3000_state
159  *                              and the underlying device state.
160  * @tx:                 dma-able transmit buffer
161  * @rx:                 dma-able receive buffer
162  **/
163 struct sca3000_state {
164         struct spi_device               *us;
165         const struct sca3000_chip_info  *info;
166         s64                             last_timestamp;
167         int                             mo_det_use_count;
168         struct mutex                    lock;
169         /* Can these share a cacheline ? */
170         u8                              rx[384] ____cacheline_aligned;
171         u8                              tx[6] ____cacheline_aligned;
172 };
173
174 /**
175  * struct sca3000_chip_info - model dependent parameters
176  * @scale:                      scale * 10^-6
177  * @temp_output:                some devices have temperature sensors.
178  * @measurement_mode_freq:      normal mode sampling frequency
179  * @measurement_mode_3db_freq:  3db cutoff frequency of the low pass filter for
180  * the normal measurement mode.
181  * @option_mode_1:              first optional mode. Not all models have one
182  * @option_mode_1_freq:         option mode 1 sampling frequency
183  * @option_mode_1_3db_freq:     3db cutoff frequency of the low pass filter for
184  * the first option mode.
185  * @option_mode_2:              second optional mode. Not all chips have one
186  * @option_mode_2_freq:         option mode 2 sampling frequency
187  * @option_mode_2_3db_freq:     3db cutoff frequency of the low pass filter for
188  * the second option mode.
189  * @mot_det_mult_xz:            Bit wise multipliers to calculate the threshold
190  * for motion detection in the x and z axis.
191  * @mot_det_mult_y:             Bit wise multipliers to calculate the threshold
192  * for motion detection in the y axis.
193  *
194  * This structure is used to hold information about the functionality of a given
195  * sca3000 variant.
196  **/
197 struct sca3000_chip_info {
198         unsigned int            scale;
199         bool                    temp_output;
200         int                     measurement_mode_freq;
201         int                     measurement_mode_3db_freq;
202         int                     option_mode_1;
203         int                     option_mode_1_freq;
204         int                     option_mode_1_3db_freq;
205         int                     option_mode_2;
206         int                     option_mode_2_freq;
207         int                     option_mode_2_3db_freq;
208         int                     mot_det_mult_xz[6];
209         int                     mot_det_mult_y[7];
210 };
211
212 enum sca3000_variant {
213         d01,
214         e02,
215         e04,
216         e05,
217 };
218
219 /*
220  * Note where option modes are not defined, the chip simply does not
221  * support any.
222  * Other chips in the sca3000 series use i2c and are not included here.
223  *
224  * Some of these devices are only listed in the family data sheet and
225  * do not actually appear to be available.
226  */
227 static const struct sca3000_chip_info sca3000_spi_chip_info_tbl[] = {
228         [d01] = {
229                 .scale = 7357,
230                 .temp_output = true,
231                 .measurement_mode_freq = 250,
232                 .measurement_mode_3db_freq = 45,
233                 .option_mode_1 = SCA3000_OP_MODE_BYPASS,
234                 .option_mode_1_freq = 250,
235                 .option_mode_1_3db_freq = 70,
236                 .mot_det_mult_xz = {50, 100, 200, 350, 650, 1300},
237                 .mot_det_mult_y = {50, 100, 150, 250, 450, 850, 1750},
238         },
239         [e02] = {
240                 .scale = 9810,
241                 .measurement_mode_freq = 125,
242                 .measurement_mode_3db_freq = 40,
243                 .option_mode_1 = SCA3000_OP_MODE_NARROW,
244                 .option_mode_1_freq = 63,
245                 .option_mode_1_3db_freq = 11,
246                 .mot_det_mult_xz = {100, 150, 300, 550, 1050, 2050},
247                 .mot_det_mult_y = {50, 100, 200, 350, 700, 1350, 2700},
248         },
249         [e04] = {
250                 .scale = 19620,
251                 .measurement_mode_freq = 100,
252                 .measurement_mode_3db_freq = 38,
253                 .option_mode_1 = SCA3000_OP_MODE_NARROW,
254                 .option_mode_1_freq = 50,
255                 .option_mode_1_3db_freq = 9,
256                 .option_mode_2 = SCA3000_OP_MODE_WIDE,
257                 .option_mode_2_freq = 400,
258                 .option_mode_2_3db_freq = 70,
259                 .mot_det_mult_xz = {200, 300, 600, 1100, 2100, 4100},
260                 .mot_det_mult_y = {100, 200, 400, 7000, 1400, 2700, 54000},
261         },
262         [e05] = {
263                 .scale = 61313,
264                 .measurement_mode_freq = 200,
265                 .measurement_mode_3db_freq = 60,
266                 .option_mode_1 = SCA3000_OP_MODE_NARROW,
267                 .option_mode_1_freq = 50,
268                 .option_mode_1_3db_freq = 9,
269                 .option_mode_2 = SCA3000_OP_MODE_WIDE,
270                 .option_mode_2_freq = 400,
271                 .option_mode_2_3db_freq = 75,
272                 .mot_det_mult_xz = {600, 900, 1700, 3200, 6100, 11900},
273                 .mot_det_mult_y = {300, 600, 1200, 2000, 4100, 7800, 15600},
274         },
275 };
276
277 static int sca3000_write_reg(struct sca3000_state *st, u8 address, u8 val)
278 {
279         st->tx[0] = SCA3000_WRITE_REG(address);
280         st->tx[1] = val;
281         return spi_write(st->us, st->tx, 2);
282 }
283
284 static int sca3000_read_data_short(struct sca3000_state *st,
285                                    u8 reg_address_high,
286                                    int len)
287 {
288         struct spi_transfer xfer[2] = {
289                 {
290                         .len = 1,
291                         .tx_buf = st->tx,
292                 }, {
293                         .len = len,
294                         .rx_buf = st->rx,
295                 }
296         };
297         st->tx[0] = SCA3000_READ_REG(reg_address_high);
298
299         return spi_sync_transfer(st->us, xfer, ARRAY_SIZE(xfer));
300 }
301
302 /**
303  * sca3000_reg_lock_on() - test if the ctrl register lock is on
304  * @st: Driver specific device instance data.
305  *
306  * Lock must be held.
307  **/
308 static int sca3000_reg_lock_on(struct sca3000_state *st)
309 {
310         int ret;
311
312         ret = sca3000_read_data_short(st, SCA3000_REG_STATUS_ADDR, 1);
313         if (ret < 0)
314                 return ret;
315
316         return !(st->rx[0] & SCA3000_LOCKED);
317 }
318
319 /**
320  * __sca3000_unlock_reg_lock() - unlock the control registers
321  * @st: Driver specific device instance data.
322  *
323  * Note the device does not appear to support doing this in a single transfer.
324  * This should only ever be used as part of ctrl reg read.
325  * Lock must be held before calling this
326  */
327 static int __sca3000_unlock_reg_lock(struct sca3000_state *st)
328 {
329         struct spi_transfer xfer[3] = {
330                 {
331                         .len = 2,
332                         .cs_change = 1,
333                         .tx_buf = st->tx,
334                 }, {
335                         .len = 2,
336                         .cs_change = 1,
337                         .tx_buf = st->tx + 2,
338                 }, {
339                         .len = 2,
340                         .tx_buf = st->tx + 4,
341                 },
342         };
343         st->tx[0] = SCA3000_WRITE_REG(SCA3000_REG_UNLOCK_ADDR);
344         st->tx[1] = 0x00;
345         st->tx[2] = SCA3000_WRITE_REG(SCA3000_REG_UNLOCK_ADDR);
346         st->tx[3] = 0x50;
347         st->tx[4] = SCA3000_WRITE_REG(SCA3000_REG_UNLOCK_ADDR);
348         st->tx[5] = 0xA0;
349
350         return spi_sync_transfer(st->us, xfer, ARRAY_SIZE(xfer));
351 }
352
353 /**
354  * sca3000_write_ctrl_reg() - write to a lock protect ctrl register
355  * @st: Driver specific device instance data.
356  * @sel: selects which registers we wish to write to
357  * @val: the value to be written
358  *
359  * Certain control registers are protected against overwriting by the lock
360  * register and use a shared write address. This function allows writing of
361  * these registers.
362  * Lock must be held.
363  */
364 static int sca3000_write_ctrl_reg(struct sca3000_state *st,
365                                   u8 sel,
366                                   uint8_t val)
367 {
368         int ret;
369
370         ret = sca3000_reg_lock_on(st);
371         if (ret < 0)
372                 goto error_ret;
373         if (ret) {
374                 ret = __sca3000_unlock_reg_lock(st);
375                 if (ret)
376                         goto error_ret;
377         }
378
379         /* Set the control select register */
380         ret = sca3000_write_reg(st, SCA3000_REG_CTRL_SEL_ADDR, sel);
381         if (ret)
382                 goto error_ret;
383
384         /* Write the actual value into the register */
385         ret = sca3000_write_reg(st, SCA3000_REG_CTRL_DATA_ADDR, val);
386
387 error_ret:
388         return ret;
389 }
390
391 /**
392  * sca3000_read_ctrl_reg() - read from lock protected control register.
393  * @st: Driver specific device instance data.
394  * @ctrl_reg: Which ctrl register do we want to read.
395  *
396  * Lock must be held.
397  */
398 static int sca3000_read_ctrl_reg(struct sca3000_state *st,
399                                  u8 ctrl_reg)
400 {
401         int ret;
402
403         ret = sca3000_reg_lock_on(st);
404         if (ret < 0)
405                 goto error_ret;
406         if (ret) {
407                 ret = __sca3000_unlock_reg_lock(st);
408                 if (ret)
409                         goto error_ret;
410         }
411         /* Set the control select register */
412         ret = sca3000_write_reg(st, SCA3000_REG_CTRL_SEL_ADDR, ctrl_reg);
413         if (ret)
414                 goto error_ret;
415         ret = sca3000_read_data_short(st, SCA3000_REG_CTRL_DATA_ADDR, 1);
416         if (ret)
417                 goto error_ret;
418         return st->rx[0];
419 error_ret:
420         return ret;
421 }
422
423 /**
424  * sca3000_print_rev() - sysfs interface to read the chip revision number
425  * @indio_dev: Device instance specific generic IIO data.
426  * Driver specific device instance data can be obtained via
427  * via iio_priv(indio_dev)
428  */
429 static int sca3000_print_rev(struct iio_dev *indio_dev)
430 {
431         int ret;
432         struct sca3000_state *st = iio_priv(indio_dev);
433
434         mutex_lock(&st->lock);
435         ret = sca3000_read_data_short(st, SCA3000_REG_REVID_ADDR, 1);
436         if (ret < 0)
437                 goto error_ret;
438         dev_info(&indio_dev->dev,
439                  "sca3000 revision major=%lu, minor=%lu\n",
440                  st->rx[0] & SCA3000_REG_REVID_MAJOR_MASK,
441                  st->rx[0] & SCA3000_REG_REVID_MINOR_MASK);
442 error_ret:
443         mutex_unlock(&st->lock);
444
445         return ret;
446 }
447
448 static ssize_t
449 sca3000_show_available_3db_freqs(struct device *dev,
450                                  struct device_attribute *attr,
451                                  char *buf)
452 {
453         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
454         struct sca3000_state *st = iio_priv(indio_dev);
455         int len;
456
457         len = sprintf(buf, "%d", st->info->measurement_mode_3db_freq);
458         if (st->info->option_mode_1)
459                 len += sprintf(buf + len, " %d",
460                                st->info->option_mode_1_3db_freq);
461         if (st->info->option_mode_2)
462                 len += sprintf(buf + len, " %d",
463                                st->info->option_mode_2_3db_freq);
464         len += sprintf(buf + len, "\n");
465
466         return len;
467 }
468
469 static IIO_DEVICE_ATTR(in_accel_filter_low_pass_3db_frequency_available,
470                        S_IRUGO, sca3000_show_available_3db_freqs,
471                        NULL, 0);
472
473 static const struct iio_event_spec sca3000_event = {
474         .type = IIO_EV_TYPE_MAG,
475         .dir = IIO_EV_DIR_RISING,
476         .mask_separate = BIT(IIO_EV_INFO_VALUE) | BIT(IIO_EV_INFO_ENABLE),
477 };
478
479 /*
480  * Note the hack in the number of bits to pretend we have 2 more than
481  * we do in the fifo.
482  */
483 #define SCA3000_CHAN(index, mod)                                \
484         {                                                       \
485                 .type = IIO_ACCEL,                              \
486                 .modified = 1,                                  \
487                 .channel2 = mod,                                \
488                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),   \
489                 .info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |\
490                         BIT(IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY),\
491                 .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ),\
492                 .address = index,                               \
493                 .scan_index = index,                            \
494                 .scan_type = {                                  \
495                         .sign = 's',                            \
496                         .realbits = 13,                         \
497                         .storagebits = 16,                      \
498                         .shift = 3,                             \
499                         .endianness = IIO_BE,                   \
500                 },                                              \
501                 .event_spec = &sca3000_event,                   \
502                 .num_event_specs = 1,                           \
503         }
504
505 static const struct iio_event_spec sca3000_freefall_event_spec = {
506         .type = IIO_EV_TYPE_MAG,
507         .dir = IIO_EV_DIR_FALLING,
508         .mask_separate = BIT(IIO_EV_INFO_ENABLE) |
509                 BIT(IIO_EV_INFO_PERIOD),
510 };
511
512 static const struct iio_chan_spec sca3000_channels[] = {
513         SCA3000_CHAN(0, IIO_MOD_X),
514         SCA3000_CHAN(1, IIO_MOD_Y),
515         SCA3000_CHAN(2, IIO_MOD_Z),
516         {
517                 .type = IIO_ACCEL,
518                 .modified = 1,
519                 .channel2 = IIO_MOD_X_AND_Y_AND_Z,
520                 .scan_index = -1, /* Fake channel */
521                 .event_spec = &sca3000_freefall_event_spec,
522                 .num_event_specs = 1,
523         },
524 };
525
526 static const struct iio_chan_spec sca3000_channels_with_temp[] = {
527         SCA3000_CHAN(0, IIO_MOD_X),
528         SCA3000_CHAN(1, IIO_MOD_Y),
529         SCA3000_CHAN(2, IIO_MOD_Z),
530         {
531                 .type = IIO_TEMP,
532                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
533                 .info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |
534                         BIT(IIO_CHAN_INFO_OFFSET),
535                 /* No buffer support */
536                 .scan_index = -1,
537         },
538         {
539                 .type = IIO_ACCEL,
540                 .modified = 1,
541                 .channel2 = IIO_MOD_X_AND_Y_AND_Z,
542                 .scan_index = -1, /* Fake channel */
543                 .event_spec = &sca3000_freefall_event_spec,
544                 .num_event_specs = 1,
545         },
546 };
547
548 static u8 sca3000_addresses[3][3] = {
549         [0] = {SCA3000_REG_X_MSB_ADDR, SCA3000_REG_CTRL_SEL_MD_X_TH,
550                SCA3000_MD_CTRL_OR_X},
551         [1] = {SCA3000_REG_Y_MSB_ADDR, SCA3000_REG_CTRL_SEL_MD_Y_TH,
552                SCA3000_MD_CTRL_OR_Y},
553         [2] = {SCA3000_REG_Z_MSB_ADDR, SCA3000_REG_CTRL_SEL_MD_Z_TH,
554                SCA3000_MD_CTRL_OR_Z},
555 };
556
557 /**
558  * __sca3000_get_base_freq() - obtain mode specific base frequency
559  * @st: Private driver specific device instance specific state.
560  * @info: chip type specific information.
561  * @base_freq: Base frequency for the current measurement mode.
562  *
563  * lock must be held
564  */
565 static inline int __sca3000_get_base_freq(struct sca3000_state *st,
566                                           const struct sca3000_chip_info *info,
567                                           int *base_freq)
568 {
569         int ret;
570
571         ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
572         if (ret)
573                 goto error_ret;
574         switch (SCA3000_REG_MODE_MODE_MASK & st->rx[0]) {
575         case SCA3000_REG_MODE_MEAS_MODE_NORMAL:
576                 *base_freq = info->measurement_mode_freq;
577                 break;
578         case SCA3000_REG_MODE_MEAS_MODE_OP_1:
579                 *base_freq = info->option_mode_1_freq;
580                 break;
581         case SCA3000_REG_MODE_MEAS_MODE_OP_2:
582                 *base_freq = info->option_mode_2_freq;
583                 break;
584         default:
585                 ret = -EINVAL;
586         }
587 error_ret:
588         return ret;
589 }
590
591 /**
592  * sca3000_read_raw_samp_freq() - read_raw handler for IIO_CHAN_INFO_SAMP_FREQ
593  * @st: Private driver specific device instance specific state.
594  * @val: The frequency read back.
595  *
596  * lock must be held
597  **/
598 static int sca3000_read_raw_samp_freq(struct sca3000_state *st, int *val)
599 {
600         int ret;
601
602         ret = __sca3000_get_base_freq(st, st->info, val);
603         if (ret)
604                 return ret;
605
606         ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL);
607         if (ret < 0)
608                 return ret;
609
610         if (*val > 0) {
611                 ret &= SCA3000_REG_OUT_CTRL_BUF_DIV_MASK;
612                 switch (ret) {
613                 case SCA3000_REG_OUT_CTRL_BUF_DIV_2:
614                         *val /= 2;
615                         break;
616                 case SCA3000_REG_OUT_CTRL_BUF_DIV_4:
617                         *val /= 4;
618                         break;
619                 }
620         }
621
622         return 0;
623 }
624
625 /**
626  * sca3000_write_raw_samp_freq() - write_raw handler for IIO_CHAN_INFO_SAMP_FREQ
627  * @st: Private driver specific device instance specific state.
628  * @val: The frequency desired.
629  *
630  * lock must be held
631  */
632 static int sca3000_write_raw_samp_freq(struct sca3000_state *st, int val)
633 {
634         int ret, base_freq, ctrlval;
635
636         ret = __sca3000_get_base_freq(st, st->info, &base_freq);
637         if (ret)
638                 return ret;
639
640         ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL);
641         if (ret < 0)
642                 return ret;
643
644         ctrlval = ret & ~SCA3000_REG_OUT_CTRL_BUF_DIV_MASK;
645
646         if (val == base_freq / 2)
647                 ctrlval |= SCA3000_REG_OUT_CTRL_BUF_DIV_2;
648         if (val == base_freq / 4)
649                 ctrlval |= SCA3000_REG_OUT_CTRL_BUF_DIV_4;
650         else if (val != base_freq)
651                 return -EINVAL;
652
653         return sca3000_write_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL,
654                                      ctrlval);
655 }
656
657 static int sca3000_read_3db_freq(struct sca3000_state *st, int *val)
658 {
659         int ret;
660
661         ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
662         if (ret)
663                 return ret;
664
665         /* mask bottom 2 bits - only ones that are relevant */
666         st->rx[0] &= SCA3000_REG_MODE_MODE_MASK;
667         switch (st->rx[0]) {
668         case SCA3000_REG_MODE_MEAS_MODE_NORMAL:
669                 *val = st->info->measurement_mode_3db_freq;
670                 return IIO_VAL_INT;
671         case SCA3000_REG_MODE_MEAS_MODE_MOT_DET:
672                 return -EBUSY;
673         case SCA3000_REG_MODE_MEAS_MODE_OP_1:
674                 *val = st->info->option_mode_1_3db_freq;
675                 return IIO_VAL_INT;
676         case SCA3000_REG_MODE_MEAS_MODE_OP_2:
677                 *val = st->info->option_mode_2_3db_freq;
678                 return IIO_VAL_INT;
679         default:
680                 return -EINVAL;
681         }
682 }
683
684 static int sca3000_write_3db_freq(struct sca3000_state *st, int val)
685 {
686         int ret;
687         int mode;
688
689         if (val == st->info->measurement_mode_3db_freq)
690                 mode = SCA3000_REG_MODE_MEAS_MODE_NORMAL;
691         else if (st->info->option_mode_1 &&
692                  (val == st->info->option_mode_1_3db_freq))
693                 mode = SCA3000_REG_MODE_MEAS_MODE_OP_1;
694         else if (st->info->option_mode_2 &&
695                  (val == st->info->option_mode_2_3db_freq))
696                 mode = SCA3000_REG_MODE_MEAS_MODE_OP_2;
697         else
698                 return -EINVAL;
699         ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
700         if (ret)
701                 return ret;
702
703         st->rx[0] &= ~SCA3000_REG_MODE_MODE_MASK;
704         st->rx[0] |= (mode & SCA3000_REG_MODE_MODE_MASK);
705
706         return sca3000_write_reg(st, SCA3000_REG_MODE_ADDR, st->rx[0]);
707 }
708
709 static int sca3000_read_raw(struct iio_dev *indio_dev,
710                             struct iio_chan_spec const *chan,
711                             int *val,
712                             int *val2,
713                             long mask)
714 {
715         struct sca3000_state *st = iio_priv(indio_dev);
716         int ret;
717         u8 address;
718
719         switch (mask) {
720         case IIO_CHAN_INFO_RAW:
721                 mutex_lock(&st->lock);
722                 if (chan->type == IIO_ACCEL) {
723                         if (st->mo_det_use_count) {
724                                 mutex_unlock(&st->lock);
725                                 return -EBUSY;
726                         }
727                         address = sca3000_addresses[chan->address][0];
728                         ret = sca3000_read_data_short(st, address, 2);
729                         if (ret < 0) {
730                                 mutex_unlock(&st->lock);
731                                 return ret;
732                         }
733                         *val = (be16_to_cpup((__be16 *)st->rx) >> 3) & 0x1FFF;
734                         *val = sign_extend32(*val, 12);
735                 } else {
736                         /* get the temperature when available */
737                         ret = sca3000_read_data_short(st,
738                                                       SCA3000_REG_TEMP_MSB_ADDR,
739                                                       2);
740                         if (ret < 0) {
741                                 mutex_unlock(&st->lock);
742                                 return ret;
743                         }
744                         *val = ((st->rx[0] & 0x3F) << 3) |
745                                ((st->rx[1] & 0xE0) >> 5);
746                 }
747                 mutex_unlock(&st->lock);
748                 return IIO_VAL_INT;
749         case IIO_CHAN_INFO_SCALE:
750                 *val = 0;
751                 if (chan->type == IIO_ACCEL)
752                         *val2 = st->info->scale;
753                 else /* temperature */
754                         *val2 = 555556;
755                 return IIO_VAL_INT_PLUS_MICRO;
756         case IIO_CHAN_INFO_OFFSET:
757                 *val = -214;
758                 *val2 = 600000;
759                 return IIO_VAL_INT_PLUS_MICRO;
760         case IIO_CHAN_INFO_SAMP_FREQ:
761                 mutex_lock(&st->lock);
762                 ret = sca3000_read_raw_samp_freq(st, val);
763                 mutex_unlock(&st->lock);
764                 return ret ? ret : IIO_VAL_INT;
765         case IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY:
766                 mutex_lock(&st->lock);
767                 ret = sca3000_read_3db_freq(st, val);
768                 mutex_unlock(&st->lock);
769                 return ret;
770         default:
771                 return -EINVAL;
772         }
773 }
774
775 static int sca3000_write_raw(struct iio_dev *indio_dev,
776                              struct iio_chan_spec const *chan,
777                              int val, int val2, long mask)
778 {
779         struct sca3000_state *st = iio_priv(indio_dev);
780         int ret;
781
782         switch (mask) {
783         case IIO_CHAN_INFO_SAMP_FREQ:
784                 if (val2)
785                         return -EINVAL;
786                 mutex_lock(&st->lock);
787                 ret = sca3000_write_raw_samp_freq(st, val);
788                 mutex_unlock(&st->lock);
789                 return ret;
790         case IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY:
791                 if (val2)
792                         return -EINVAL;
793                 mutex_lock(&st->lock);
794                 ret = sca3000_write_3db_freq(st, val);
795                 mutex_unlock(&st->lock);
796                 return ret;
797         default:
798                 return -EINVAL;
799         }
800
801         return ret;
802 }
803
804 /**
805  * sca3000_read_av_freq() - sysfs function to get available frequencies
806  * @dev: Device structure for this device.
807  * @attr: Description of the attribute.
808  * @buf: Incoming string
809  *
810  * The later modes are only relevant to the ring buffer - and depend on current
811  * mode. Note that data sheet gives rather wide tolerances for these so integer
812  * division will give good enough answer and not all chips have them specified
813  * at all.
814  **/
815 static ssize_t sca3000_read_av_freq(struct device *dev,
816                                     struct device_attribute *attr,
817                                     char *buf)
818 {
819         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
820         struct sca3000_state *st = iio_priv(indio_dev);
821         int len = 0, ret, val;
822
823         mutex_lock(&st->lock);
824         ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
825         val = st->rx[0];
826         mutex_unlock(&st->lock);
827         if (ret)
828                 goto error_ret;
829
830         switch (val & SCA3000_REG_MODE_MODE_MASK) {
831         case SCA3000_REG_MODE_MEAS_MODE_NORMAL:
832                 len += sprintf(buf + len, "%d %d %d\n",
833                                st->info->measurement_mode_freq,
834                                st->info->measurement_mode_freq / 2,
835                                st->info->measurement_mode_freq / 4);
836                 break;
837         case SCA3000_REG_MODE_MEAS_MODE_OP_1:
838                 len += sprintf(buf + len, "%d %d %d\n",
839                                st->info->option_mode_1_freq,
840                                st->info->option_mode_1_freq / 2,
841                                st->info->option_mode_1_freq / 4);
842                 break;
843         case SCA3000_REG_MODE_MEAS_MODE_OP_2:
844                 len += sprintf(buf + len, "%d %d %d\n",
845                                st->info->option_mode_2_freq,
846                                st->info->option_mode_2_freq / 2,
847                                st->info->option_mode_2_freq / 4);
848                 break;
849         }
850         return len;
851 error_ret:
852         return ret;
853 }
854
855 /*
856  * Should only really be registered if ring buffer support is compiled in.
857  * Does no harm however and doing it right would add a fair bit of complexity
858  */
859 static IIO_DEV_ATTR_SAMP_FREQ_AVAIL(sca3000_read_av_freq);
860
861 /*
862  * sca3000_read_event_value() - query of a threshold or period
863  */
864 static int sca3000_read_event_value(struct iio_dev *indio_dev,
865                                     const struct iio_chan_spec *chan,
866                                     enum iio_event_type type,
867                                     enum iio_event_direction dir,
868                                     enum iio_event_info info,
869                                     int *val, int *val2)
870 {
871         struct sca3000_state *st = iio_priv(indio_dev);
872         long ret;
873         int i;
874
875         switch (info) {
876         case IIO_EV_INFO_VALUE:
877                 mutex_lock(&st->lock);
878                 ret = sca3000_read_ctrl_reg(st,
879                                             sca3000_addresses[chan->address][1]);
880                 mutex_unlock(&st->lock);
881                 if (ret < 0)
882                         return ret;
883                 *val = 0;
884                 if (chan->channel2 == IIO_MOD_Y)
885                         for_each_set_bit(i, &ret,
886                                          ARRAY_SIZE(st->info->mot_det_mult_y))
887                                 *val += st->info->mot_det_mult_y[i];
888                 else
889                         for_each_set_bit(i, &ret,
890                                          ARRAY_SIZE(st->info->mot_det_mult_xz))
891                                 *val += st->info->mot_det_mult_xz[i];
892
893                 return IIO_VAL_INT;
894         case IIO_EV_INFO_PERIOD:
895                 *val = 0;
896                 *val2 = 226000;
897                 return IIO_VAL_INT_PLUS_MICRO;
898         default:
899                 return -EINVAL;
900         }
901 }
902
903 /**
904  * sca3000_write_event_value() - control of threshold and period
905  * @indio_dev: Device instance specific IIO information.
906  * @chan: Description of the channel for which the event is being
907  * configured.
908  * @type: The type of event being configured, here magnitude rising
909  * as everything else is read only.
910  * @dir: Direction of the event (here rising)
911  * @info: What information about the event are we configuring.
912  * Here the threshold only.
913  * @val: Integer part of the value being written..
914  * @val2: Non integer part of the value being written. Here always 0.
915  */
916 static int sca3000_write_event_value(struct iio_dev *indio_dev,
917                                      const struct iio_chan_spec *chan,
918                                      enum iio_event_type type,
919                                      enum iio_event_direction dir,
920                                      enum iio_event_info info,
921                                      int val, int val2)
922 {
923         struct sca3000_state *st = iio_priv(indio_dev);
924         int ret;
925         int i;
926         u8 nonlinear = 0;
927
928         if (chan->channel2 == IIO_MOD_Y) {
929                 i = ARRAY_SIZE(st->info->mot_det_mult_y);
930                 while (i > 0)
931                         if (val >= st->info->mot_det_mult_y[--i]) {
932                                 nonlinear |= (1 << i);
933                                 val -= st->info->mot_det_mult_y[i];
934                         }
935         } else {
936                 i = ARRAY_SIZE(st->info->mot_det_mult_xz);
937                 while (i > 0)
938                         if (val >= st->info->mot_det_mult_xz[--i]) {
939                                 nonlinear |= (1 << i);
940                                 val -= st->info->mot_det_mult_xz[i];
941                         }
942         }
943
944         mutex_lock(&st->lock);
945         ret = sca3000_write_ctrl_reg(st,
946                                      sca3000_addresses[chan->address][1],
947                                      nonlinear);
948         mutex_unlock(&st->lock);
949
950         return ret;
951 }
952
953 static struct attribute *sca3000_attributes[] = {
954         &iio_dev_attr_in_accel_filter_low_pass_3db_frequency_available.dev_attr.attr,
955         &iio_dev_attr_sampling_frequency_available.dev_attr.attr,
956         NULL,
957 };
958
959 static const struct attribute_group sca3000_attribute_group = {
960         .attrs = sca3000_attributes,
961 };
962
963 static int sca3000_read_data(struct sca3000_state *st,
964                              u8 reg_address_high,
965                              u8 *rx,
966                              int len)
967 {
968         int ret;
969         struct spi_transfer xfer[2] = {
970                 {
971                         .len = 1,
972                         .tx_buf = st->tx,
973                 }, {
974                         .len = len,
975                         .rx_buf = rx,
976                 }
977         };
978
979         st->tx[0] = SCA3000_READ_REG(reg_address_high);
980         ret = spi_sync_transfer(st->us, xfer, ARRAY_SIZE(xfer));
981         if (ret) {
982                 dev_err(&st->us->dev, "problem reading register\n");
983                 return ret;
984         }
985
986         return 0;
987 }
988
989 /**
990  * sca3000_ring_int_process() - ring specific interrupt handling.
991  * @val: Value of the interrupt status register.
992  * @indio_dev: Device instance specific IIO device structure.
993  */
994 static void sca3000_ring_int_process(u8 val, struct iio_dev *indio_dev)
995 {
996         struct sca3000_state *st = iio_priv(indio_dev);
997         int ret, i, num_available;
998
999         mutex_lock(&st->lock);
1000
1001         if (val & SCA3000_REG_INT_STATUS_HALF) {
1002                 ret = sca3000_read_data_short(st, SCA3000_REG_BUF_COUNT_ADDR,
1003                                               1);
1004                 if (ret)
1005                         goto error_ret;
1006                 num_available = st->rx[0];
1007                 /*
1008                  * num_available is the total number of samples available
1009                  * i.e. number of time points * number of channels.
1010                  */
1011                 ret = sca3000_read_data(st, SCA3000_REG_RING_OUT_ADDR, st->rx,
1012                                         num_available * 2);
1013                 if (ret)
1014                         goto error_ret;
1015                 for (i = 0; i < num_available / 3; i++) {
1016                         /*
1017                          * Dirty hack to cover for 11 bit in fifo, 13 bit
1018                          * direct reading.
1019                          *
1020                          * In theory the bottom two bits are undefined.
1021                          * In reality they appear to always be 0.
1022                          */
1023                         iio_push_to_buffers(indio_dev, st->rx + i * 3 * 2);
1024                 }
1025         }
1026 error_ret:
1027         mutex_unlock(&st->lock);
1028 }
1029
1030 /**
1031  * sca3000_event_handler() - handling ring and non ring events
1032  * @irq: The irq being handled.
1033  * @private: struct iio_device pointer for the device.
1034  *
1035  * Ring related interrupt handler. Depending on event, push to
1036  * the ring buffer event chrdev or the event one.
1037  *
1038  * This function is complicated by the fact that the devices can signify ring
1039  * and non ring events via the same interrupt line and they can only
1040  * be distinguished via a read of the relevant status register.
1041  */
1042 static irqreturn_t sca3000_event_handler(int irq, void *private)
1043 {
1044         struct iio_dev *indio_dev = private;
1045         struct sca3000_state *st = iio_priv(indio_dev);
1046         int ret, val;
1047         s64 last_timestamp = iio_get_time_ns(indio_dev);
1048
1049         /*
1050          * Could lead if badly timed to an extra read of status reg,
1051          * but ensures no interrupt is missed.
1052          */
1053         mutex_lock(&st->lock);
1054         ret = sca3000_read_data_short(st, SCA3000_REG_INT_STATUS_ADDR, 1);
1055         val = st->rx[0];
1056         mutex_unlock(&st->lock);
1057         if (ret)
1058                 goto done;
1059
1060         sca3000_ring_int_process(val, indio_dev);
1061
1062         if (val & SCA3000_INT_STATUS_FREE_FALL)
1063                 iio_push_event(indio_dev,
1064                                IIO_MOD_EVENT_CODE(IIO_ACCEL,
1065                                                   0,
1066                                                   IIO_MOD_X_AND_Y_AND_Z,
1067                                                   IIO_EV_TYPE_MAG,
1068                                                   IIO_EV_DIR_FALLING),
1069                                last_timestamp);
1070
1071         if (val & SCA3000_INT_STATUS_Y_TRIGGER)
1072                 iio_push_event(indio_dev,
1073                                IIO_MOD_EVENT_CODE(IIO_ACCEL,
1074                                                   0,
1075                                                   IIO_MOD_Y,
1076                                                   IIO_EV_TYPE_MAG,
1077                                                   IIO_EV_DIR_RISING),
1078                                last_timestamp);
1079
1080         if (val & SCA3000_INT_STATUS_X_TRIGGER)
1081                 iio_push_event(indio_dev,
1082                                IIO_MOD_EVENT_CODE(IIO_ACCEL,
1083                                                   0,
1084                                                   IIO_MOD_X,
1085                                                   IIO_EV_TYPE_MAG,
1086                                                   IIO_EV_DIR_RISING),
1087                                last_timestamp);
1088
1089         if (val & SCA3000_INT_STATUS_Z_TRIGGER)
1090                 iio_push_event(indio_dev,
1091                                IIO_MOD_EVENT_CODE(IIO_ACCEL,
1092                                                   0,
1093                                                   IIO_MOD_Z,
1094                                                   IIO_EV_TYPE_MAG,
1095                                                   IIO_EV_DIR_RISING),
1096                                last_timestamp);
1097
1098 done:
1099         return IRQ_HANDLED;
1100 }
1101
1102 /*
1103  * sca3000_read_event_config() what events are enabled
1104  */
1105 static int sca3000_read_event_config(struct iio_dev *indio_dev,
1106                                      const struct iio_chan_spec *chan,
1107                                      enum iio_event_type type,
1108                                      enum iio_event_direction dir)
1109 {
1110         struct sca3000_state *st = iio_priv(indio_dev);
1111         int ret;
1112         /* read current value of mode register */
1113         mutex_lock(&st->lock);
1114
1115         ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
1116         if (ret)
1117                 goto error_ret;
1118
1119         switch (chan->channel2) {
1120         case IIO_MOD_X_AND_Y_AND_Z:
1121                 ret = !!(st->rx[0] & SCA3000_REG_MODE_FREE_FALL_DETECT);
1122                 break;
1123         case IIO_MOD_X:
1124         case IIO_MOD_Y:
1125         case IIO_MOD_Z:
1126                 /*
1127                  * Motion detection mode cannot run at the same time as
1128                  * acceleration data being read.
1129                  */
1130                 if ((st->rx[0] & SCA3000_REG_MODE_MODE_MASK)
1131                     != SCA3000_REG_MODE_MEAS_MODE_MOT_DET) {
1132                         ret = 0;
1133                 } else {
1134                         ret = sca3000_read_ctrl_reg(st,
1135                                                 SCA3000_REG_CTRL_SEL_MD_CTRL);
1136                         if (ret < 0)
1137                                 goto error_ret;
1138                         /* only supporting logical or's for now */
1139                         ret = !!(ret & sca3000_addresses[chan->address][2]);
1140                 }
1141                 break;
1142         default:
1143                 ret = -EINVAL;
1144         }
1145
1146 error_ret:
1147         mutex_unlock(&st->lock);
1148
1149         return ret;
1150 }
1151
1152 static int sca3000_freefall_set_state(struct iio_dev *indio_dev, int state)
1153 {
1154         struct sca3000_state *st = iio_priv(indio_dev);
1155         int ret;
1156
1157         /* read current value of mode register */
1158         ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
1159         if (ret)
1160                 return ret;
1161
1162         /* if off and should be on */
1163         if (state && !(st->rx[0] & SCA3000_REG_MODE_FREE_FALL_DETECT))
1164                 return sca3000_write_reg(st, SCA3000_REG_MODE_ADDR,
1165                                          st->rx[0] | SCA3000_REG_MODE_FREE_FALL_DETECT);
1166         /* if on and should be off */
1167         else if (!state && (st->rx[0] & SCA3000_REG_MODE_FREE_FALL_DETECT))
1168                 return sca3000_write_reg(st, SCA3000_REG_MODE_ADDR,
1169                                          st->rx[0] & ~SCA3000_REG_MODE_FREE_FALL_DETECT);
1170         else
1171                 return 0;
1172 }
1173
1174 static int sca3000_motion_detect_set_state(struct iio_dev *indio_dev, int axis,
1175                                            int state)
1176 {
1177         struct sca3000_state *st = iio_priv(indio_dev);
1178         int ret, ctrlval;
1179
1180         /*
1181          * First read the motion detector config to find out if
1182          * this axis is on
1183          */
1184         ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_MD_CTRL);
1185         if (ret < 0)
1186                 return ret;
1187         ctrlval = ret;
1188         /* if off and should be on */
1189         if (state && !(ctrlval & sca3000_addresses[axis][2])) {
1190                 ret = sca3000_write_ctrl_reg(st,
1191                                              SCA3000_REG_CTRL_SEL_MD_CTRL,
1192                                              ctrlval |
1193                                              sca3000_addresses[axis][2]);
1194                 if (ret)
1195                         return ret;
1196                 st->mo_det_use_count++;
1197         } else if (!state && (ctrlval & sca3000_addresses[axis][2])) {
1198                 ret = sca3000_write_ctrl_reg(st,
1199                                              SCA3000_REG_CTRL_SEL_MD_CTRL,
1200                                              ctrlval &
1201                                              ~(sca3000_addresses[axis][2]));
1202                 if (ret)
1203                         return ret;
1204                 st->mo_det_use_count--;
1205         }
1206
1207         /* read current value of mode register */
1208         ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
1209         if (ret)
1210                 return ret;
1211         /* if off and should be on */
1212         if ((st->mo_det_use_count) &&
1213             ((st->rx[0] & SCA3000_REG_MODE_MODE_MASK)
1214              != SCA3000_REG_MODE_MEAS_MODE_MOT_DET))
1215                 return sca3000_write_reg(st, SCA3000_REG_MODE_ADDR,
1216                         (st->rx[0] & ~SCA3000_REG_MODE_MODE_MASK)
1217                         | SCA3000_REG_MODE_MEAS_MODE_MOT_DET);
1218         /* if on and should be off */
1219         else if (!(st->mo_det_use_count) &&
1220                  ((st->rx[0] & SCA3000_REG_MODE_MODE_MASK)
1221                   == SCA3000_REG_MODE_MEAS_MODE_MOT_DET))
1222                 return sca3000_write_reg(st, SCA3000_REG_MODE_ADDR,
1223                         st->rx[0] & SCA3000_REG_MODE_MODE_MASK);
1224         else
1225                 return 0;
1226 }
1227
1228 /**
1229  * sca3000_write_event_config() - simple on off control for motion detector
1230  * @indio_dev: IIO device instance specific structure. Data specific to this
1231  * particular driver may be accessed via iio_priv(indio_dev).
1232  * @chan: Description of the channel whose event we are configuring.
1233  * @type: The type of event.
1234  * @dir: The direction of the event.
1235  * @state: Desired state of event being configured.
1236  *
1237  * This is a per axis control, but enabling any will result in the
1238  * motion detector unit being enabled.
1239  * N.B. enabling motion detector stops normal data acquisition.
1240  * There is a complexity in knowing which mode to return to when
1241  * this mode is disabled.  Currently normal mode is assumed.
1242  **/
1243 static int sca3000_write_event_config(struct iio_dev *indio_dev,
1244                                       const struct iio_chan_spec *chan,
1245                                       enum iio_event_type type,
1246                                       enum iio_event_direction dir,
1247                                       int state)
1248 {
1249         struct sca3000_state *st = iio_priv(indio_dev);
1250         int ret;
1251
1252         mutex_lock(&st->lock);
1253         switch (chan->channel2) {
1254         case IIO_MOD_X_AND_Y_AND_Z:
1255                 ret = sca3000_freefall_set_state(indio_dev, state);
1256                 break;
1257
1258         case IIO_MOD_X:
1259         case IIO_MOD_Y:
1260         case IIO_MOD_Z:
1261                 ret = sca3000_motion_detect_set_state(indio_dev,
1262                                                       chan->address,
1263                                                       state);
1264                 break;
1265         default:
1266                 ret = -EINVAL;
1267                 break;
1268         }
1269         mutex_unlock(&st->lock);
1270
1271         return ret;
1272 }
1273
1274 static inline
1275 int __sca3000_hw_ring_state_set(struct iio_dev *indio_dev, bool state)
1276 {
1277         struct sca3000_state *st = iio_priv(indio_dev);
1278         int ret;
1279
1280         mutex_lock(&st->lock);
1281         ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
1282         if (ret)
1283                 goto error_ret;
1284         if (state) {
1285                 dev_info(&indio_dev->dev, "supposedly enabling ring buffer\n");
1286                 ret = sca3000_write_reg(st,
1287                         SCA3000_REG_MODE_ADDR,
1288                         (st->rx[0] | SCA3000_REG_MODE_RING_BUF_ENABLE));
1289         } else
1290                 ret = sca3000_write_reg(st,
1291                         SCA3000_REG_MODE_ADDR,
1292                         (st->rx[0] & ~SCA3000_REG_MODE_RING_BUF_ENABLE));
1293 error_ret:
1294         mutex_unlock(&st->lock);
1295
1296         return ret;
1297 }
1298
1299 /**
1300  * sca3000_hw_ring_preenable() - hw ring buffer preenable function
1301  * @indio_dev: structure representing the IIO device. Device instance
1302  * specific state can be accessed via iio_priv(indio_dev).
1303  *
1304  * Very simple enable function as the chip will allows normal reads
1305  * during ring buffer operation so as long as it is indeed running
1306  * before we notify the core, the precise ordering does not matter.
1307  */
1308 static int sca3000_hw_ring_preenable(struct iio_dev *indio_dev)
1309 {
1310         int ret;
1311         struct sca3000_state *st = iio_priv(indio_dev);
1312
1313         mutex_lock(&st->lock);
1314
1315         /* Enable the 50% full interrupt */
1316         ret = sca3000_read_data_short(st, SCA3000_REG_INT_MASK_ADDR, 1);
1317         if (ret)
1318                 goto error_unlock;
1319         ret = sca3000_write_reg(st,
1320                                 SCA3000_REG_INT_MASK_ADDR,
1321                                 st->rx[0] | SCA3000_REG_INT_MASK_RING_HALF);
1322         if (ret)
1323                 goto error_unlock;
1324
1325         mutex_unlock(&st->lock);
1326
1327         return __sca3000_hw_ring_state_set(indio_dev, 1);
1328
1329 error_unlock:
1330         mutex_unlock(&st->lock);
1331
1332         return ret;
1333 }
1334
1335 static int sca3000_hw_ring_postdisable(struct iio_dev *indio_dev)
1336 {
1337         int ret;
1338         struct sca3000_state *st = iio_priv(indio_dev);
1339
1340         ret = __sca3000_hw_ring_state_set(indio_dev, 0);
1341         if (ret)
1342                 return ret;
1343
1344         /* Disable the 50% full interrupt */
1345         mutex_lock(&st->lock);
1346
1347         ret = sca3000_read_data_short(st, SCA3000_REG_INT_MASK_ADDR, 1);
1348         if (ret)
1349                 goto unlock;
1350         ret = sca3000_write_reg(st,
1351                                 SCA3000_REG_INT_MASK_ADDR,
1352                                 st->rx[0] & ~SCA3000_REG_INT_MASK_RING_HALF);
1353 unlock:
1354         mutex_unlock(&st->lock);
1355         return ret;
1356 }
1357
1358 static const struct iio_buffer_setup_ops sca3000_ring_setup_ops = {
1359         .preenable = &sca3000_hw_ring_preenable,
1360         .postdisable = &sca3000_hw_ring_postdisable,
1361 };
1362
1363 /**
1364  * sca3000_clean_setup() - get the device into a predictable state
1365  * @st: Device instance specific private data structure
1366  *
1367  * Devices use flash memory to store many of the register values
1368  * and hence can come up in somewhat unpredictable states.
1369  * Hence reset everything on driver load.
1370  */
1371 static int sca3000_clean_setup(struct sca3000_state *st)
1372 {
1373         int ret;
1374
1375         mutex_lock(&st->lock);
1376         /* Ensure all interrupts have been acknowledged */
1377         ret = sca3000_read_data_short(st, SCA3000_REG_INT_STATUS_ADDR, 1);
1378         if (ret)
1379                 goto error_ret;
1380
1381         /* Turn off all motion detection channels */
1382         ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_MD_CTRL);
1383         if (ret < 0)
1384                 goto error_ret;
1385         ret = sca3000_write_ctrl_reg(st, SCA3000_REG_CTRL_SEL_MD_CTRL,
1386                                      ret & SCA3000_MD_CTRL_PROT_MASK);
1387         if (ret)
1388                 goto error_ret;
1389
1390         /* Disable ring buffer */
1391         ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL);
1392         if (ret < 0)
1393                 goto error_ret;
1394         ret = sca3000_write_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL,
1395                                      (ret & SCA3000_REG_OUT_CTRL_PROT_MASK)
1396                                      | SCA3000_REG_OUT_CTRL_BUF_X_EN
1397                                      | SCA3000_REG_OUT_CTRL_BUF_Y_EN
1398                                      | SCA3000_REG_OUT_CTRL_BUF_Z_EN
1399                                      | SCA3000_REG_OUT_CTRL_BUF_DIV_4);
1400         if (ret)
1401                 goto error_ret;
1402         /* Enable interrupts, relevant to mode and set up as active low */
1403         ret = sca3000_read_data_short(st, SCA3000_REG_INT_MASK_ADDR, 1);
1404         if (ret)
1405                 goto error_ret;
1406         ret = sca3000_write_reg(st,
1407                                 SCA3000_REG_INT_MASK_ADDR,
1408                                 (ret & SCA3000_REG_INT_MASK_PROT_MASK)
1409                                 | SCA3000_REG_INT_MASK_ACTIVE_LOW);
1410         if (ret)
1411                 goto error_ret;
1412         /*
1413          * Select normal measurement mode, free fall off, ring off
1414          * Ring in 12 bit mode - it is fine to overwrite reserved bits 3,5
1415          * as that occurs in one of the example on the datasheet
1416          */
1417         ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
1418         if (ret)
1419                 goto error_ret;
1420         ret = sca3000_write_reg(st, SCA3000_REG_MODE_ADDR,
1421                                 (st->rx[0] & SCA3000_MODE_PROT_MASK));
1422
1423 error_ret:
1424         mutex_unlock(&st->lock);
1425         return ret;
1426 }
1427
1428 static const struct iio_info sca3000_info = {
1429         .attrs = &sca3000_attribute_group,
1430         .read_raw = &sca3000_read_raw,
1431         .write_raw = &sca3000_write_raw,
1432         .read_event_value = &sca3000_read_event_value,
1433         .write_event_value = &sca3000_write_event_value,
1434         .read_event_config = &sca3000_read_event_config,
1435         .write_event_config = &sca3000_write_event_config,
1436 };
1437
1438 static int sca3000_probe(struct spi_device *spi)
1439 {
1440         int ret;
1441         struct sca3000_state *st;
1442         struct iio_dev *indio_dev;
1443
1444         indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
1445         if (!indio_dev)
1446                 return -ENOMEM;
1447
1448         st = iio_priv(indio_dev);
1449         spi_set_drvdata(spi, indio_dev);
1450         st->us = spi;
1451         mutex_init(&st->lock);
1452         st->info = &sca3000_spi_chip_info_tbl[spi_get_device_id(spi)
1453                                               ->driver_data];
1454
1455         indio_dev->name = spi_get_device_id(spi)->name;
1456         indio_dev->info = &sca3000_info;
1457         if (st->info->temp_output) {
1458                 indio_dev->channels = sca3000_channels_with_temp;
1459                 indio_dev->num_channels =
1460                         ARRAY_SIZE(sca3000_channels_with_temp);
1461         } else {
1462                 indio_dev->channels = sca3000_channels;
1463                 indio_dev->num_channels = ARRAY_SIZE(sca3000_channels);
1464         }
1465         indio_dev->modes = INDIO_DIRECT_MODE;
1466
1467         ret = devm_iio_kfifo_buffer_setup(&spi->dev, indio_dev,
1468                                           INDIO_BUFFER_SOFTWARE,
1469                                           &sca3000_ring_setup_ops);
1470         if (ret)
1471                 return ret;
1472
1473         if (spi->irq) {
1474                 ret = request_threaded_irq(spi->irq,
1475                                            NULL,
1476                                            &sca3000_event_handler,
1477                                            IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
1478                                            "sca3000",
1479                                            indio_dev);
1480                 if (ret)
1481                         return ret;
1482         }
1483         ret = sca3000_clean_setup(st);
1484         if (ret)
1485                 goto error_free_irq;
1486
1487         ret = sca3000_print_rev(indio_dev);
1488         if (ret)
1489                 goto error_free_irq;
1490
1491         return iio_device_register(indio_dev);
1492
1493 error_free_irq:
1494         if (spi->irq)
1495                 free_irq(spi->irq, indio_dev);
1496
1497         return ret;
1498 }
1499
1500 static int sca3000_stop_all_interrupts(struct sca3000_state *st)
1501 {
1502         int ret;
1503
1504         mutex_lock(&st->lock);
1505         ret = sca3000_read_data_short(st, SCA3000_REG_INT_MASK_ADDR, 1);
1506         if (ret)
1507                 goto error_ret;
1508         ret = sca3000_write_reg(st, SCA3000_REG_INT_MASK_ADDR,
1509                                 (st->rx[0] &
1510                                  ~(SCA3000_REG_INT_MASK_RING_THREE_QUARTER |
1511                                    SCA3000_REG_INT_MASK_RING_HALF |
1512                                    SCA3000_REG_INT_MASK_ALL_INTS)));
1513 error_ret:
1514         mutex_unlock(&st->lock);
1515         return ret;
1516 }
1517
1518 static int sca3000_remove(struct spi_device *spi)
1519 {
1520         struct iio_dev *indio_dev = spi_get_drvdata(spi);
1521         struct sca3000_state *st = iio_priv(indio_dev);
1522
1523         iio_device_unregister(indio_dev);
1524
1525         /* Must ensure no interrupts can be generated after this! */
1526         sca3000_stop_all_interrupts(st);
1527         if (spi->irq)
1528                 free_irq(spi->irq, indio_dev);
1529
1530         return 0;
1531 }
1532
1533 static const struct spi_device_id sca3000_id[] = {
1534         {"sca3000_d01", d01},
1535         {"sca3000_e02", e02},
1536         {"sca3000_e04", e04},
1537         {"sca3000_e05", e05},
1538         {}
1539 };
1540 MODULE_DEVICE_TABLE(spi, sca3000_id);
1541
1542 static struct spi_driver sca3000_driver = {
1543         .driver = {
1544                 .name = "sca3000",
1545         },
1546         .probe = sca3000_probe,
1547         .remove = sca3000_remove,
1548         .id_table = sca3000_id,
1549 };
1550 module_spi_driver(sca3000_driver);
1551
1552 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1553 MODULE_DESCRIPTION("VTI SCA3000 Series Accelerometers SPI driver");
1554 MODULE_LICENSE("GPL v2");