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