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