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