Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * sca3000_core.c -- support VTI sca3000 series accelerometers via SPI
0004  *
0005  * Copyright (c) 2009 Jonathan Cameron <jic23@kernel.org>
0006  *
0007  * See industrialio/accels/sca3000.h for comments.
0008  */
0009 
0010 #include <linux/interrupt.h>
0011 #include <linux/fs.h>
0012 #include <linux/device.h>
0013 #include <linux/slab.h>
0014 #include <linux/kernel.h>
0015 #include <linux/spi/spi.h>
0016 #include <linux/sysfs.h>
0017 #include <linux/module.h>
0018 #include <linux/uaccess.h>
0019 #include <linux/iio/iio.h>
0020 #include <linux/iio/sysfs.h>
0021 #include <linux/iio/events.h>
0022 #include <linux/iio/buffer.h>
0023 #include <linux/iio/kfifo_buf.h>
0024 
0025 #define SCA3000_WRITE_REG(a) (((a) << 2) | 0x02)
0026 #define SCA3000_READ_REG(a) ((a) << 2)
0027 
0028 #define SCA3000_REG_REVID_ADDR              0x00
0029 #define   SCA3000_REG_REVID_MAJOR_MASK          GENMASK(8, 4)
0030 #define   SCA3000_REG_REVID_MINOR_MASK          GENMASK(3, 0)
0031 
0032 #define SCA3000_REG_STATUS_ADDR             0x02
0033 #define   SCA3000_LOCKED                BIT(5)
0034 #define   SCA3000_EEPROM_CS_ERROR           BIT(1)
0035 #define   SCA3000_SPI_FRAME_ERROR           BIT(0)
0036 
0037 /* All reads done using register decrement so no need to directly access LSBs */
0038 #define SCA3000_REG_X_MSB_ADDR              0x05
0039 #define SCA3000_REG_Y_MSB_ADDR              0x07
0040 #define SCA3000_REG_Z_MSB_ADDR              0x09
0041 
0042 #define SCA3000_REG_RING_OUT_ADDR           0x0f
0043 
0044 /* Temp read untested - the e05 doesn't have the sensor */
0045 #define SCA3000_REG_TEMP_MSB_ADDR           0x13
0046 
0047 #define SCA3000_REG_MODE_ADDR               0x14
0048 #define SCA3000_MODE_PROT_MASK              0x28
0049 #define   SCA3000_REG_MODE_RING_BUF_ENABLE      BIT(7)
0050 #define   SCA3000_REG_MODE_RING_BUF_8BIT        BIT(6)
0051 
0052 /*
0053  * Free fall detection triggers an interrupt if the acceleration
0054  * is below a threshold for equivalent of 25cm drop
0055  */
0056 #define   SCA3000_REG_MODE_FREE_FALL_DETECT     BIT(4)
0057 #define   SCA3000_REG_MODE_MEAS_MODE_NORMAL     0x00
0058 #define   SCA3000_REG_MODE_MEAS_MODE_OP_1       0x01
0059 #define   SCA3000_REG_MODE_MEAS_MODE_OP_2       0x02
0060 
0061 /*
0062  * In motion detection mode the accelerations are band pass filtered
0063  * (approx 1 - 25Hz) and then a programmable threshold used to trigger
0064  * and interrupt.
0065  */
0066 #define   SCA3000_REG_MODE_MEAS_MODE_MOT_DET        0x03
0067 #define   SCA3000_REG_MODE_MODE_MASK            0x03
0068 
0069 #define SCA3000_REG_BUF_COUNT_ADDR          0x15
0070 
0071 #define SCA3000_REG_INT_STATUS_ADDR         0x16
0072 #define   SCA3000_REG_INT_STATUS_THREE_QUARTERS     BIT(7)
0073 #define   SCA3000_REG_INT_STATUS_HALF           BIT(6)
0074 
0075 #define SCA3000_INT_STATUS_FREE_FALL            BIT(3)
0076 #define SCA3000_INT_STATUS_Y_TRIGGER            BIT(2)
0077 #define SCA3000_INT_STATUS_X_TRIGGER            BIT(1)
0078 #define SCA3000_INT_STATUS_Z_TRIGGER            BIT(0)
0079 
0080 /* Used to allow access to multiplexed registers */
0081 #define SCA3000_REG_CTRL_SEL_ADDR           0x18
0082 /* Only available for SCA3000-D03 and SCA3000-D01 */
0083 #define   SCA3000_REG_CTRL_SEL_I2C_DISABLE      0x01
0084 #define   SCA3000_REG_CTRL_SEL_MD_CTRL          0x02
0085 #define   SCA3000_REG_CTRL_SEL_MD_Y_TH          0x03
0086 #define   SCA3000_REG_CTRL_SEL_MD_X_TH          0x04
0087 #define   SCA3000_REG_CTRL_SEL_MD_Z_TH          0x05
0088 /*
0089  * BE VERY CAREFUL WITH THIS, IF 3 BITS ARE NOT SET the device
0090  * will not function
0091  */
0092 #define   SCA3000_REG_CTRL_SEL_OUT_CTRL         0x0B
0093 
0094 #define     SCA3000_REG_OUT_CTRL_PROT_MASK      0xE0
0095 #define     SCA3000_REG_OUT_CTRL_BUF_X_EN       0x10
0096 #define     SCA3000_REG_OUT_CTRL_BUF_Y_EN       0x08
0097 #define     SCA3000_REG_OUT_CTRL_BUF_Z_EN       0x04
0098 #define     SCA3000_REG_OUT_CTRL_BUF_DIV_MASK       0x03
0099 #define     SCA3000_REG_OUT_CTRL_BUF_DIV_4      0x02
0100 #define     SCA3000_REG_OUT_CTRL_BUF_DIV_2      0x01
0101 
0102 
0103 /*
0104  * Control which motion detector interrupts are on.
0105  * For now only OR combinations are supported.
0106  */
0107 #define SCA3000_MD_CTRL_PROT_MASK           0xC0
0108 #define SCA3000_MD_CTRL_OR_Y                BIT(0)
0109 #define SCA3000_MD_CTRL_OR_X                BIT(1)
0110 #define SCA3000_MD_CTRL_OR_Z                BIT(2)
0111 /* Currently unsupported */
0112 #define SCA3000_MD_CTRL_AND_Y               BIT(3)
0113 #define SCA3000_MD_CTRL_AND_X               BIT(4)
0114 #define SCA3000_MD_CTRL_AND_Z               BIT(5)
0115 
0116 /*
0117  * Some control registers of complex access methods requiring this register to
0118  * be used to remove a lock.
0119  */
0120 #define SCA3000_REG_UNLOCK_ADDR             0x1e
0121 
0122 #define SCA3000_REG_INT_MASK_ADDR           0x21
0123 #define   SCA3000_REG_INT_MASK_PROT_MASK        0x1C
0124 
0125 #define   SCA3000_REG_INT_MASK_RING_THREE_QUARTER   BIT(7)
0126 #define   SCA3000_REG_INT_MASK_RING_HALF        BIT(6)
0127 
0128 #define SCA3000_REG_INT_MASK_ALL_INTS           0x02
0129 #define SCA3000_REG_INT_MASK_ACTIVE_HIGH        0x01
0130 #define SCA3000_REG_INT_MASK_ACTIVE_LOW         0x00
0131 /* Values of multiplexed registers (write to ctrl_data after select) */
0132 #define SCA3000_REG_CTRL_DATA_ADDR          0x22
0133 
0134 /*
0135  * Measurement modes available on some sca3000 series chips. Code assumes others
0136  * may become available in the future.
0137  *
0138  * Bypass - Bypass the low-pass filter in the signal channel so as to increase
0139  *          signal bandwidth.
0140  *
0141  * Narrow - Narrow low-pass filtering of the signal channel and half output
0142  *          data rate by decimation.
0143  *
0144  * Wide - Widen low-pass filtering of signal channel to increase bandwidth
0145  */
0146 #define SCA3000_OP_MODE_BYPASS              0x01
0147 #define SCA3000_OP_MODE_NARROW              0x02
0148 #define SCA3000_OP_MODE_WIDE                0x04
0149 #define SCA3000_MAX_TX 6
0150 #define SCA3000_MAX_RX 2
0151 
0152 /**
0153  * struct sca3000_state - device instance state information
0154  * @us:         the associated spi device
0155  * @info:           chip variant information
0156  * @last_timestamp:     the timestamp of the last event
0157  * @mo_det_use_count:       reference counter for the motion detection unit
0158  * @lock:           lock used to protect elements of sca3000_state
0159  *              and the underlying device state.
0160  * @tx:         dma-able transmit buffer
0161  * @rx:         dma-able receive buffer
0162  **/
0163 struct sca3000_state {
0164     struct spi_device       *us;
0165     const struct sca3000_chip_info  *info;
0166     s64             last_timestamp;
0167     int             mo_det_use_count;
0168     struct mutex            lock;
0169     /* Can these share a cacheline ? */
0170     u8              rx[384] __aligned(IIO_DMA_MINALIGN);
0171     u8              tx[6] __aligned(IIO_DMA_MINALIGN);
0172 };
0173 
0174 /**
0175  * struct sca3000_chip_info - model dependent parameters
0176  * @scale:          scale * 10^-6
0177  * @temp_output:        some devices have temperature sensors.
0178  * @measurement_mode_freq:  normal mode sampling frequency
0179  * @measurement_mode_3db_freq:  3db cutoff frequency of the low pass filter for
0180  * the normal measurement mode.
0181  * @option_mode_1:      first optional mode. Not all models have one
0182  * @option_mode_1_freq:     option mode 1 sampling frequency
0183  * @option_mode_1_3db_freq: 3db cutoff frequency of the low pass filter for
0184  * the first option mode.
0185  * @option_mode_2:      second optional mode. Not all chips have one
0186  * @option_mode_2_freq:     option mode 2 sampling frequency
0187  * @option_mode_2_3db_freq: 3db cutoff frequency of the low pass filter for
0188  * the second option mode.
0189  * @mot_det_mult_xz:        Bit wise multipliers to calculate the threshold
0190  * for motion detection in the x and z axis.
0191  * @mot_det_mult_y:     Bit wise multipliers to calculate the threshold
0192  * for motion detection in the y axis.
0193  *
0194  * This structure is used to hold information about the functionality of a given
0195  * sca3000 variant.
0196  **/
0197 struct sca3000_chip_info {
0198     unsigned int        scale;
0199     bool            temp_output;
0200     int         measurement_mode_freq;
0201     int         measurement_mode_3db_freq;
0202     int         option_mode_1;
0203     int         option_mode_1_freq;
0204     int         option_mode_1_3db_freq;
0205     int         option_mode_2;
0206     int         option_mode_2_freq;
0207     int         option_mode_2_3db_freq;
0208     int         mot_det_mult_xz[6];
0209     int         mot_det_mult_y[7];
0210 };
0211 
0212 enum sca3000_variant {
0213     d01,
0214     e02,
0215     e04,
0216     e05,
0217 };
0218 
0219 /*
0220  * Note where option modes are not defined, the chip simply does not
0221  * support any.
0222  * Other chips in the sca3000 series use i2c and are not included here.
0223  *
0224  * Some of these devices are only listed in the family data sheet and
0225  * do not actually appear to be available.
0226  */
0227 static const struct sca3000_chip_info sca3000_spi_chip_info_tbl[] = {
0228     [d01] = {
0229         .scale = 7357,
0230         .temp_output = true,
0231         .measurement_mode_freq = 250,
0232         .measurement_mode_3db_freq = 45,
0233         .option_mode_1 = SCA3000_OP_MODE_BYPASS,
0234         .option_mode_1_freq = 250,
0235         .option_mode_1_3db_freq = 70,
0236         .mot_det_mult_xz = {50, 100, 200, 350, 650, 1300},
0237         .mot_det_mult_y = {50, 100, 150, 250, 450, 850, 1750},
0238     },
0239     [e02] = {
0240         .scale = 9810,
0241         .measurement_mode_freq = 125,
0242         .measurement_mode_3db_freq = 40,
0243         .option_mode_1 = SCA3000_OP_MODE_NARROW,
0244         .option_mode_1_freq = 63,
0245         .option_mode_1_3db_freq = 11,
0246         .mot_det_mult_xz = {100, 150, 300, 550, 1050, 2050},
0247         .mot_det_mult_y = {50, 100, 200, 350, 700, 1350, 2700},
0248     },
0249     [e04] = {
0250         .scale = 19620,
0251         .measurement_mode_freq = 100,
0252         .measurement_mode_3db_freq = 38,
0253         .option_mode_1 = SCA3000_OP_MODE_NARROW,
0254         .option_mode_1_freq = 50,
0255         .option_mode_1_3db_freq = 9,
0256         .option_mode_2 = SCA3000_OP_MODE_WIDE,
0257         .option_mode_2_freq = 400,
0258         .option_mode_2_3db_freq = 70,
0259         .mot_det_mult_xz = {200, 300, 600, 1100, 2100, 4100},
0260         .mot_det_mult_y = {100, 200, 400, 7000, 1400, 2700, 54000},
0261     },
0262     [e05] = {
0263         .scale = 61313,
0264         .measurement_mode_freq = 200,
0265         .measurement_mode_3db_freq = 60,
0266         .option_mode_1 = SCA3000_OP_MODE_NARROW,
0267         .option_mode_1_freq = 50,
0268         .option_mode_1_3db_freq = 9,
0269         .option_mode_2 = SCA3000_OP_MODE_WIDE,
0270         .option_mode_2_freq = 400,
0271         .option_mode_2_3db_freq = 75,
0272         .mot_det_mult_xz = {600, 900, 1700, 3200, 6100, 11900},
0273         .mot_det_mult_y = {300, 600, 1200, 2000, 4100, 7800, 15600},
0274     },
0275 };
0276 
0277 static int sca3000_write_reg(struct sca3000_state *st, u8 address, u8 val)
0278 {
0279     st->tx[0] = SCA3000_WRITE_REG(address);
0280     st->tx[1] = val;
0281     return spi_write(st->us, st->tx, 2);
0282 }
0283 
0284 static int sca3000_read_data_short(struct sca3000_state *st,
0285                    u8 reg_address_high,
0286                    int len)
0287 {
0288     struct spi_transfer xfer[2] = {
0289         {
0290             .len = 1,
0291             .tx_buf = st->tx,
0292         }, {
0293             .len = len,
0294             .rx_buf = st->rx,
0295         }
0296     };
0297     st->tx[0] = SCA3000_READ_REG(reg_address_high);
0298 
0299     return spi_sync_transfer(st->us, xfer, ARRAY_SIZE(xfer));
0300 }
0301 
0302 /**
0303  * sca3000_reg_lock_on() - test if the ctrl register lock is on
0304  * @st: Driver specific device instance data.
0305  *
0306  * Lock must be held.
0307  **/
0308 static int sca3000_reg_lock_on(struct sca3000_state *st)
0309 {
0310     int ret;
0311 
0312     ret = sca3000_read_data_short(st, SCA3000_REG_STATUS_ADDR, 1);
0313     if (ret < 0)
0314         return ret;
0315 
0316     return !(st->rx[0] & SCA3000_LOCKED);
0317 }
0318 
0319 /**
0320  * __sca3000_unlock_reg_lock() - unlock the control registers
0321  * @st: Driver specific device instance data.
0322  *
0323  * Note the device does not appear to support doing this in a single transfer.
0324  * This should only ever be used as part of ctrl reg read.
0325  * Lock must be held before calling this
0326  */
0327 static int __sca3000_unlock_reg_lock(struct sca3000_state *st)
0328 {
0329     struct spi_transfer xfer[3] = {
0330         {
0331             .len = 2,
0332             .cs_change = 1,
0333             .tx_buf = st->tx,
0334         }, {
0335             .len = 2,
0336             .cs_change = 1,
0337             .tx_buf = st->tx + 2,
0338         }, {
0339             .len = 2,
0340             .tx_buf = st->tx + 4,
0341         },
0342     };
0343     st->tx[0] = SCA3000_WRITE_REG(SCA3000_REG_UNLOCK_ADDR);
0344     st->tx[1] = 0x00;
0345     st->tx[2] = SCA3000_WRITE_REG(SCA3000_REG_UNLOCK_ADDR);
0346     st->tx[3] = 0x50;
0347     st->tx[4] = SCA3000_WRITE_REG(SCA3000_REG_UNLOCK_ADDR);
0348     st->tx[5] = 0xA0;
0349 
0350     return spi_sync_transfer(st->us, xfer, ARRAY_SIZE(xfer));
0351 }
0352 
0353 /**
0354  * sca3000_write_ctrl_reg() - write to a lock protect ctrl register
0355  * @st: Driver specific device instance data.
0356  * @sel: selects which registers we wish to write to
0357  * @val: the value to be written
0358  *
0359  * Certain control registers are protected against overwriting by the lock
0360  * register and use a shared write address. This function allows writing of
0361  * these registers.
0362  * Lock must be held.
0363  */
0364 static int sca3000_write_ctrl_reg(struct sca3000_state *st,
0365                   u8 sel,
0366                   uint8_t val)
0367 {
0368     int ret;
0369 
0370     ret = sca3000_reg_lock_on(st);
0371     if (ret < 0)
0372         goto error_ret;
0373     if (ret) {
0374         ret = __sca3000_unlock_reg_lock(st);
0375         if (ret)
0376             goto error_ret;
0377     }
0378 
0379     /* Set the control select register */
0380     ret = sca3000_write_reg(st, SCA3000_REG_CTRL_SEL_ADDR, sel);
0381     if (ret)
0382         goto error_ret;
0383 
0384     /* Write the actual value into the register */
0385     ret = sca3000_write_reg(st, SCA3000_REG_CTRL_DATA_ADDR, val);
0386 
0387 error_ret:
0388     return ret;
0389 }
0390 
0391 /**
0392  * sca3000_read_ctrl_reg() - read from lock protected control register.
0393  * @st: Driver specific device instance data.
0394  * @ctrl_reg: Which ctrl register do we want to read.
0395  *
0396  * Lock must be held.
0397  */
0398 static int sca3000_read_ctrl_reg(struct sca3000_state *st,
0399                  u8 ctrl_reg)
0400 {
0401     int ret;
0402 
0403     ret = sca3000_reg_lock_on(st);
0404     if (ret < 0)
0405         goto error_ret;
0406     if (ret) {
0407         ret = __sca3000_unlock_reg_lock(st);
0408         if (ret)
0409             goto error_ret;
0410     }
0411     /* Set the control select register */
0412     ret = sca3000_write_reg(st, SCA3000_REG_CTRL_SEL_ADDR, ctrl_reg);
0413     if (ret)
0414         goto error_ret;
0415     ret = sca3000_read_data_short(st, SCA3000_REG_CTRL_DATA_ADDR, 1);
0416     if (ret)
0417         goto error_ret;
0418     return st->rx[0];
0419 error_ret:
0420     return ret;
0421 }
0422 
0423 /**
0424  * sca3000_print_rev() - sysfs interface to read the chip revision number
0425  * @indio_dev: Device instance specific generic IIO data.
0426  * Driver specific device instance data can be obtained via
0427  * iio_priv(indio_dev)
0428  */
0429 static int sca3000_print_rev(struct iio_dev *indio_dev)
0430 {
0431     int ret;
0432     struct sca3000_state *st = iio_priv(indio_dev);
0433 
0434     mutex_lock(&st->lock);
0435     ret = sca3000_read_data_short(st, SCA3000_REG_REVID_ADDR, 1);
0436     if (ret < 0)
0437         goto error_ret;
0438     dev_info(&indio_dev->dev,
0439          "sca3000 revision major=%lu, minor=%lu\n",
0440          st->rx[0] & SCA3000_REG_REVID_MAJOR_MASK,
0441          st->rx[0] & SCA3000_REG_REVID_MINOR_MASK);
0442 error_ret:
0443     mutex_unlock(&st->lock);
0444 
0445     return ret;
0446 }
0447 
0448 static ssize_t
0449 sca3000_show_available_3db_freqs(struct device *dev,
0450                  struct device_attribute *attr,
0451                  char *buf)
0452 {
0453     struct iio_dev *indio_dev = dev_to_iio_dev(dev);
0454     struct sca3000_state *st = iio_priv(indio_dev);
0455     int len;
0456 
0457     len = sprintf(buf, "%d", st->info->measurement_mode_3db_freq);
0458     if (st->info->option_mode_1)
0459         len += sprintf(buf + len, " %d",
0460                    st->info->option_mode_1_3db_freq);
0461     if (st->info->option_mode_2)
0462         len += sprintf(buf + len, " %d",
0463                    st->info->option_mode_2_3db_freq);
0464     len += sprintf(buf + len, "\n");
0465 
0466     return len;
0467 }
0468 
0469 static IIO_DEVICE_ATTR(in_accel_filter_low_pass_3db_frequency_available,
0470                S_IRUGO, sca3000_show_available_3db_freqs,
0471                NULL, 0);
0472 
0473 static const struct iio_event_spec sca3000_event = {
0474     .type = IIO_EV_TYPE_MAG,
0475     .dir = IIO_EV_DIR_RISING,
0476     .mask_separate = BIT(IIO_EV_INFO_VALUE) | BIT(IIO_EV_INFO_ENABLE),
0477 };
0478 
0479 /*
0480  * Note the hack in the number of bits to pretend we have 2 more than
0481  * we do in the fifo.
0482  */
0483 #define SCA3000_CHAN(index, mod)                \
0484     {                           \
0485         .type = IIO_ACCEL,              \
0486         .modified = 1,                  \
0487         .channel2 = mod,                \
0488         .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),   \
0489         .info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |\
0490             BIT(IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY),\
0491         .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ),\
0492         .address = index,               \
0493         .scan_index = index,                \
0494         .scan_type = {                  \
0495             .sign = 's',                \
0496             .realbits = 13,             \
0497             .storagebits = 16,          \
0498             .shift = 3,             \
0499             .endianness = IIO_BE,           \
0500         },                      \
0501         .event_spec = &sca3000_event,           \
0502         .num_event_specs = 1,               \
0503     }
0504 
0505 static const struct iio_event_spec sca3000_freefall_event_spec = {
0506     .type = IIO_EV_TYPE_MAG,
0507     .dir = IIO_EV_DIR_FALLING,
0508     .mask_separate = BIT(IIO_EV_INFO_ENABLE) |
0509         BIT(IIO_EV_INFO_PERIOD),
0510 };
0511 
0512 static const struct iio_chan_spec sca3000_channels[] = {
0513     SCA3000_CHAN(0, IIO_MOD_X),
0514     SCA3000_CHAN(1, IIO_MOD_Y),
0515     SCA3000_CHAN(2, IIO_MOD_Z),
0516     {
0517         .type = IIO_ACCEL,
0518         .modified = 1,
0519         .channel2 = IIO_MOD_X_AND_Y_AND_Z,
0520         .scan_index = -1, /* Fake channel */
0521         .event_spec = &sca3000_freefall_event_spec,
0522         .num_event_specs = 1,
0523     },
0524 };
0525 
0526 static const struct iio_chan_spec sca3000_channels_with_temp[] = {
0527     SCA3000_CHAN(0, IIO_MOD_X),
0528     SCA3000_CHAN(1, IIO_MOD_Y),
0529     SCA3000_CHAN(2, IIO_MOD_Z),
0530     {
0531         .type = IIO_TEMP,
0532         .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
0533         .info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |
0534             BIT(IIO_CHAN_INFO_OFFSET),
0535         /* No buffer support */
0536         .scan_index = -1,
0537         .scan_type = {
0538             .sign = 'u',
0539             .realbits = 9,
0540             .storagebits = 16,
0541             .shift = 5,
0542             .endianness = IIO_BE,
0543         },
0544     },
0545     {
0546         .type = IIO_ACCEL,
0547         .modified = 1,
0548         .channel2 = IIO_MOD_X_AND_Y_AND_Z,
0549         .scan_index = -1, /* Fake channel */
0550         .event_spec = &sca3000_freefall_event_spec,
0551         .num_event_specs = 1,
0552     },
0553 };
0554 
0555 static u8 sca3000_addresses[3][3] = {
0556     [0] = {SCA3000_REG_X_MSB_ADDR, SCA3000_REG_CTRL_SEL_MD_X_TH,
0557            SCA3000_MD_CTRL_OR_X},
0558     [1] = {SCA3000_REG_Y_MSB_ADDR, SCA3000_REG_CTRL_SEL_MD_Y_TH,
0559            SCA3000_MD_CTRL_OR_Y},
0560     [2] = {SCA3000_REG_Z_MSB_ADDR, SCA3000_REG_CTRL_SEL_MD_Z_TH,
0561            SCA3000_MD_CTRL_OR_Z},
0562 };
0563 
0564 /**
0565  * __sca3000_get_base_freq() - obtain mode specific base frequency
0566  * @st: Private driver specific device instance specific state.
0567  * @info: chip type specific information.
0568  * @base_freq: Base frequency for the current measurement mode.
0569  *
0570  * lock must be held
0571  */
0572 static inline int __sca3000_get_base_freq(struct sca3000_state *st,
0573                       const struct sca3000_chip_info *info,
0574                       int *base_freq)
0575 {
0576     int ret;
0577 
0578     ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
0579     if (ret)
0580         goto error_ret;
0581     switch (SCA3000_REG_MODE_MODE_MASK & st->rx[0]) {
0582     case SCA3000_REG_MODE_MEAS_MODE_NORMAL:
0583         *base_freq = info->measurement_mode_freq;
0584         break;
0585     case SCA3000_REG_MODE_MEAS_MODE_OP_1:
0586         *base_freq = info->option_mode_1_freq;
0587         break;
0588     case SCA3000_REG_MODE_MEAS_MODE_OP_2:
0589         *base_freq = info->option_mode_2_freq;
0590         break;
0591     default:
0592         ret = -EINVAL;
0593     }
0594 error_ret:
0595     return ret;
0596 }
0597 
0598 /**
0599  * sca3000_read_raw_samp_freq() - read_raw handler for IIO_CHAN_INFO_SAMP_FREQ
0600  * @st: Private driver specific device instance specific state.
0601  * @val: The frequency read back.
0602  *
0603  * lock must be held
0604  **/
0605 static int sca3000_read_raw_samp_freq(struct sca3000_state *st, int *val)
0606 {
0607     int ret;
0608 
0609     ret = __sca3000_get_base_freq(st, st->info, val);
0610     if (ret)
0611         return ret;
0612 
0613     ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL);
0614     if (ret < 0)
0615         return ret;
0616 
0617     if (*val > 0) {
0618         ret &= SCA3000_REG_OUT_CTRL_BUF_DIV_MASK;
0619         switch (ret) {
0620         case SCA3000_REG_OUT_CTRL_BUF_DIV_2:
0621             *val /= 2;
0622             break;
0623         case SCA3000_REG_OUT_CTRL_BUF_DIV_4:
0624             *val /= 4;
0625             break;
0626         }
0627     }
0628 
0629     return 0;
0630 }
0631 
0632 /**
0633  * sca3000_write_raw_samp_freq() - write_raw handler for IIO_CHAN_INFO_SAMP_FREQ
0634  * @st: Private driver specific device instance specific state.
0635  * @val: The frequency desired.
0636  *
0637  * lock must be held
0638  */
0639 static int sca3000_write_raw_samp_freq(struct sca3000_state *st, int val)
0640 {
0641     int ret, base_freq, ctrlval;
0642 
0643     ret = __sca3000_get_base_freq(st, st->info, &base_freq);
0644     if (ret)
0645         return ret;
0646 
0647     ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL);
0648     if (ret < 0)
0649         return ret;
0650 
0651     ctrlval = ret & ~SCA3000_REG_OUT_CTRL_BUF_DIV_MASK;
0652 
0653     if (val == base_freq / 2)
0654         ctrlval |= SCA3000_REG_OUT_CTRL_BUF_DIV_2;
0655     if (val == base_freq / 4)
0656         ctrlval |= SCA3000_REG_OUT_CTRL_BUF_DIV_4;
0657     else if (val != base_freq)
0658         return -EINVAL;
0659 
0660     return sca3000_write_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL,
0661                      ctrlval);
0662 }
0663 
0664 static int sca3000_read_3db_freq(struct sca3000_state *st, int *val)
0665 {
0666     int ret;
0667 
0668     ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
0669     if (ret)
0670         return ret;
0671 
0672     /* mask bottom 2 bits - only ones that are relevant */
0673     st->rx[0] &= SCA3000_REG_MODE_MODE_MASK;
0674     switch (st->rx[0]) {
0675     case SCA3000_REG_MODE_MEAS_MODE_NORMAL:
0676         *val = st->info->measurement_mode_3db_freq;
0677         return IIO_VAL_INT;
0678     case SCA3000_REG_MODE_MEAS_MODE_MOT_DET:
0679         return -EBUSY;
0680     case SCA3000_REG_MODE_MEAS_MODE_OP_1:
0681         *val = st->info->option_mode_1_3db_freq;
0682         return IIO_VAL_INT;
0683     case SCA3000_REG_MODE_MEAS_MODE_OP_2:
0684         *val = st->info->option_mode_2_3db_freq;
0685         return IIO_VAL_INT;
0686     default:
0687         return -EINVAL;
0688     }
0689 }
0690 
0691 static int sca3000_write_3db_freq(struct sca3000_state *st, int val)
0692 {
0693     int ret;
0694     int mode;
0695 
0696     if (val == st->info->measurement_mode_3db_freq)
0697         mode = SCA3000_REG_MODE_MEAS_MODE_NORMAL;
0698     else if (st->info->option_mode_1 &&
0699          (val == st->info->option_mode_1_3db_freq))
0700         mode = SCA3000_REG_MODE_MEAS_MODE_OP_1;
0701     else if (st->info->option_mode_2 &&
0702          (val == st->info->option_mode_2_3db_freq))
0703         mode = SCA3000_REG_MODE_MEAS_MODE_OP_2;
0704     else
0705         return -EINVAL;
0706     ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
0707     if (ret)
0708         return ret;
0709 
0710     st->rx[0] &= ~SCA3000_REG_MODE_MODE_MASK;
0711     st->rx[0] |= (mode & SCA3000_REG_MODE_MODE_MASK);
0712 
0713     return sca3000_write_reg(st, SCA3000_REG_MODE_ADDR, st->rx[0]);
0714 }
0715 
0716 static int sca3000_read_raw(struct iio_dev *indio_dev,
0717                 struct iio_chan_spec const *chan,
0718                 int *val,
0719                 int *val2,
0720                 long mask)
0721 {
0722     struct sca3000_state *st = iio_priv(indio_dev);
0723     int ret;
0724     u8 address;
0725 
0726     switch (mask) {
0727     case IIO_CHAN_INFO_RAW:
0728         mutex_lock(&st->lock);
0729         if (chan->type == IIO_ACCEL) {
0730             if (st->mo_det_use_count) {
0731                 mutex_unlock(&st->lock);
0732                 return -EBUSY;
0733             }
0734             address = sca3000_addresses[chan->address][0];
0735             ret = sca3000_read_data_short(st, address, 2);
0736             if (ret < 0) {
0737                 mutex_unlock(&st->lock);
0738                 return ret;
0739             }
0740             *val = sign_extend32(be16_to_cpup((__be16 *)st->rx) >>
0741                          chan->scan_type.shift,
0742                          chan->scan_type.realbits - 1);
0743         } else {
0744             /* get the temperature when available */
0745             ret = sca3000_read_data_short(st,
0746                               SCA3000_REG_TEMP_MSB_ADDR,
0747                               2);
0748             if (ret < 0) {
0749                 mutex_unlock(&st->lock);
0750                 return ret;
0751             }
0752             *val = (be16_to_cpup((__be16 *)st->rx) >>
0753                 chan->scan_type.shift) &
0754                 GENMASK(chan->scan_type.realbits - 1, 0);
0755         }
0756         mutex_unlock(&st->lock);
0757         return IIO_VAL_INT;
0758     case IIO_CHAN_INFO_SCALE:
0759         *val = 0;
0760         if (chan->type == IIO_ACCEL)
0761             *val2 = st->info->scale;
0762         else /* temperature */
0763             *val2 = 555556;
0764         return IIO_VAL_INT_PLUS_MICRO;
0765     case IIO_CHAN_INFO_OFFSET:
0766         *val = -214;
0767         *val2 = 600000;
0768         return IIO_VAL_INT_PLUS_MICRO;
0769     case IIO_CHAN_INFO_SAMP_FREQ:
0770         mutex_lock(&st->lock);
0771         ret = sca3000_read_raw_samp_freq(st, val);
0772         mutex_unlock(&st->lock);
0773         return ret ? ret : IIO_VAL_INT;
0774     case IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY:
0775         mutex_lock(&st->lock);
0776         ret = sca3000_read_3db_freq(st, val);
0777         mutex_unlock(&st->lock);
0778         return ret;
0779     default:
0780         return -EINVAL;
0781     }
0782 }
0783 
0784 static int sca3000_write_raw(struct iio_dev *indio_dev,
0785                  struct iio_chan_spec const *chan,
0786                  int val, int val2, long mask)
0787 {
0788     struct sca3000_state *st = iio_priv(indio_dev);
0789     int ret;
0790 
0791     switch (mask) {
0792     case IIO_CHAN_INFO_SAMP_FREQ:
0793         if (val2)
0794             return -EINVAL;
0795         mutex_lock(&st->lock);
0796         ret = sca3000_write_raw_samp_freq(st, val);
0797         mutex_unlock(&st->lock);
0798         return ret;
0799     case IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY:
0800         if (val2)
0801             return -EINVAL;
0802         mutex_lock(&st->lock);
0803         ret = sca3000_write_3db_freq(st, val);
0804         mutex_unlock(&st->lock);
0805         return ret;
0806     default:
0807         return -EINVAL;
0808     }
0809 
0810     return ret;
0811 }
0812 
0813 /**
0814  * sca3000_read_av_freq() - sysfs function to get available frequencies
0815  * @dev: Device structure for this device.
0816  * @attr: Description of the attribute.
0817  * @buf: Incoming string
0818  *
0819  * The later modes are only relevant to the ring buffer - and depend on current
0820  * mode. Note that data sheet gives rather wide tolerances for these so integer
0821  * division will give good enough answer and not all chips have them specified
0822  * at all.
0823  **/
0824 static ssize_t sca3000_read_av_freq(struct device *dev,
0825                     struct device_attribute *attr,
0826                     char *buf)
0827 {
0828     struct iio_dev *indio_dev = dev_to_iio_dev(dev);
0829     struct sca3000_state *st = iio_priv(indio_dev);
0830     int len = 0, ret, val;
0831 
0832     mutex_lock(&st->lock);
0833     ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
0834     val = st->rx[0];
0835     mutex_unlock(&st->lock);
0836     if (ret)
0837         goto error_ret;
0838 
0839     switch (val & SCA3000_REG_MODE_MODE_MASK) {
0840     case SCA3000_REG_MODE_MEAS_MODE_NORMAL:
0841         len += sprintf(buf + len, "%d %d %d\n",
0842                    st->info->measurement_mode_freq,
0843                    st->info->measurement_mode_freq / 2,
0844                    st->info->measurement_mode_freq / 4);
0845         break;
0846     case SCA3000_REG_MODE_MEAS_MODE_OP_1:
0847         len += sprintf(buf + len, "%d %d %d\n",
0848                    st->info->option_mode_1_freq,
0849                    st->info->option_mode_1_freq / 2,
0850                    st->info->option_mode_1_freq / 4);
0851         break;
0852     case SCA3000_REG_MODE_MEAS_MODE_OP_2:
0853         len += sprintf(buf + len, "%d %d %d\n",
0854                    st->info->option_mode_2_freq,
0855                    st->info->option_mode_2_freq / 2,
0856                    st->info->option_mode_2_freq / 4);
0857         break;
0858     }
0859     return len;
0860 error_ret:
0861     return ret;
0862 }
0863 
0864 /*
0865  * Should only really be registered if ring buffer support is compiled in.
0866  * Does no harm however and doing it right would add a fair bit of complexity
0867  */
0868 static IIO_DEV_ATTR_SAMP_FREQ_AVAIL(sca3000_read_av_freq);
0869 
0870 /*
0871  * sca3000_read_event_value() - query of a threshold or period
0872  */
0873 static int sca3000_read_event_value(struct iio_dev *indio_dev,
0874                     const struct iio_chan_spec *chan,
0875                     enum iio_event_type type,
0876                     enum iio_event_direction dir,
0877                     enum iio_event_info info,
0878                     int *val, int *val2)
0879 {
0880     struct sca3000_state *st = iio_priv(indio_dev);
0881     long ret;
0882     int i;
0883 
0884     switch (info) {
0885     case IIO_EV_INFO_VALUE:
0886         mutex_lock(&st->lock);
0887         ret = sca3000_read_ctrl_reg(st,
0888                         sca3000_addresses[chan->address][1]);
0889         mutex_unlock(&st->lock);
0890         if (ret < 0)
0891             return ret;
0892         *val = 0;
0893         if (chan->channel2 == IIO_MOD_Y)
0894             for_each_set_bit(i, &ret,
0895                      ARRAY_SIZE(st->info->mot_det_mult_y))
0896                 *val += st->info->mot_det_mult_y[i];
0897         else
0898             for_each_set_bit(i, &ret,
0899                      ARRAY_SIZE(st->info->mot_det_mult_xz))
0900                 *val += st->info->mot_det_mult_xz[i];
0901 
0902         return IIO_VAL_INT;
0903     case IIO_EV_INFO_PERIOD:
0904         *val = 0;
0905         *val2 = 226000;
0906         return IIO_VAL_INT_PLUS_MICRO;
0907     default:
0908         return -EINVAL;
0909     }
0910 }
0911 
0912 /**
0913  * sca3000_write_event_value() - control of threshold and period
0914  * @indio_dev: Device instance specific IIO information.
0915  * @chan: Description of the channel for which the event is being
0916  * configured.
0917  * @type: The type of event being configured, here magnitude rising
0918  * as everything else is read only.
0919  * @dir: Direction of the event (here rising)
0920  * @info: What information about the event are we configuring.
0921  * Here the threshold only.
0922  * @val: Integer part of the value being written..
0923  * @val2: Non integer part of the value being written. Here always 0.
0924  */
0925 static int sca3000_write_event_value(struct iio_dev *indio_dev,
0926                      const struct iio_chan_spec *chan,
0927                      enum iio_event_type type,
0928                      enum iio_event_direction dir,
0929                      enum iio_event_info info,
0930                      int val, int val2)
0931 {
0932     struct sca3000_state *st = iio_priv(indio_dev);
0933     int ret;
0934     int i;
0935     u8 nonlinear = 0;
0936 
0937     if (chan->channel2 == IIO_MOD_Y) {
0938         i = ARRAY_SIZE(st->info->mot_det_mult_y);
0939         while (i > 0)
0940             if (val >= st->info->mot_det_mult_y[--i]) {
0941                 nonlinear |= (1 << i);
0942                 val -= st->info->mot_det_mult_y[i];
0943             }
0944     } else {
0945         i = ARRAY_SIZE(st->info->mot_det_mult_xz);
0946         while (i > 0)
0947             if (val >= st->info->mot_det_mult_xz[--i]) {
0948                 nonlinear |= (1 << i);
0949                 val -= st->info->mot_det_mult_xz[i];
0950             }
0951     }
0952 
0953     mutex_lock(&st->lock);
0954     ret = sca3000_write_ctrl_reg(st,
0955                      sca3000_addresses[chan->address][1],
0956                      nonlinear);
0957     mutex_unlock(&st->lock);
0958 
0959     return ret;
0960 }
0961 
0962 static struct attribute *sca3000_attributes[] = {
0963     &iio_dev_attr_in_accel_filter_low_pass_3db_frequency_available.dev_attr.attr,
0964     &iio_dev_attr_sampling_frequency_available.dev_attr.attr,
0965     NULL,
0966 };
0967 
0968 static const struct attribute_group sca3000_attribute_group = {
0969     .attrs = sca3000_attributes,
0970 };
0971 
0972 static int sca3000_read_data(struct sca3000_state *st,
0973                  u8 reg_address_high,
0974                  u8 *rx,
0975                  int len)
0976 {
0977     int ret;
0978     struct spi_transfer xfer[2] = {
0979         {
0980             .len = 1,
0981             .tx_buf = st->tx,
0982         }, {
0983             .len = len,
0984             .rx_buf = rx,
0985         }
0986     };
0987 
0988     st->tx[0] = SCA3000_READ_REG(reg_address_high);
0989     ret = spi_sync_transfer(st->us, xfer, ARRAY_SIZE(xfer));
0990     if (ret) {
0991         dev_err(&st->us->dev, "problem reading register\n");
0992         return ret;
0993     }
0994 
0995     return 0;
0996 }
0997 
0998 /**
0999  * sca3000_ring_int_process() - ring specific interrupt handling.
1000  * @val: Value of the interrupt status register.
1001  * @indio_dev: Device instance specific IIO device structure.
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 
1010     if (val & SCA3000_REG_INT_STATUS_HALF) {
1011         ret = sca3000_read_data_short(st, SCA3000_REG_BUF_COUNT_ADDR,
1012                           1);
1013         if (ret)
1014             goto error_ret;
1015         num_available = st->rx[0];
1016         /*
1017          * num_available is the total number of samples available
1018          * i.e. number of time points * number of channels.
1019          */
1020         ret = sca3000_read_data(st, SCA3000_REG_RING_OUT_ADDR, st->rx,
1021                     num_available * 2);
1022         if (ret)
1023             goto error_ret;
1024         for (i = 0; i < num_available / 3; i++) {
1025             /*
1026              * Dirty hack to cover for 11 bit in fifo, 13 bit
1027              * direct reading.
1028              *
1029              * In theory the bottom two bits are undefined.
1030              * In reality they appear to always be 0.
1031              */
1032             iio_push_to_buffers(indio_dev, st->rx + i * 3 * 2);
1033         }
1034     }
1035 error_ret:
1036     mutex_unlock(&st->lock);
1037 }
1038 
1039 /**
1040  * sca3000_event_handler() - handling ring and non ring events
1041  * @irq: The irq being handled.
1042  * @private: struct iio_device pointer for the device.
1043  *
1044  * Ring related interrupt handler. Depending on event, push to
1045  * the ring buffer event chrdev or the event one.
1046  *
1047  * This function is complicated by the fact that the devices can signify ring
1048  * and non ring events via the same interrupt line and they can only
1049  * be distinguished via a read of the relevant status register.
1050  */
1051 static irqreturn_t sca3000_event_handler(int irq, void *private)
1052 {
1053     struct iio_dev *indio_dev = private;
1054     struct sca3000_state *st = iio_priv(indio_dev);
1055     int ret, val;
1056     s64 last_timestamp = iio_get_time_ns(indio_dev);
1057 
1058     /*
1059      * Could lead if badly timed to an extra read of status reg,
1060      * but ensures no interrupt is missed.
1061      */
1062     mutex_lock(&st->lock);
1063     ret = sca3000_read_data_short(st, SCA3000_REG_INT_STATUS_ADDR, 1);
1064     val = st->rx[0];
1065     mutex_unlock(&st->lock);
1066     if (ret)
1067         goto done;
1068 
1069     sca3000_ring_int_process(val, indio_dev);
1070 
1071     if (val & SCA3000_INT_STATUS_FREE_FALL)
1072         iio_push_event(indio_dev,
1073                    IIO_MOD_EVENT_CODE(IIO_ACCEL,
1074                           0,
1075                           IIO_MOD_X_AND_Y_AND_Z,
1076                           IIO_EV_TYPE_MAG,
1077                           IIO_EV_DIR_FALLING),
1078                    last_timestamp);
1079 
1080     if (val & SCA3000_INT_STATUS_Y_TRIGGER)
1081         iio_push_event(indio_dev,
1082                    IIO_MOD_EVENT_CODE(IIO_ACCEL,
1083                           0,
1084                           IIO_MOD_Y,
1085                           IIO_EV_TYPE_MAG,
1086                           IIO_EV_DIR_RISING),
1087                    last_timestamp);
1088 
1089     if (val & SCA3000_INT_STATUS_X_TRIGGER)
1090         iio_push_event(indio_dev,
1091                    IIO_MOD_EVENT_CODE(IIO_ACCEL,
1092                           0,
1093                           IIO_MOD_X,
1094                           IIO_EV_TYPE_MAG,
1095                           IIO_EV_DIR_RISING),
1096                    last_timestamp);
1097 
1098     if (val & SCA3000_INT_STATUS_Z_TRIGGER)
1099         iio_push_event(indio_dev,
1100                    IIO_MOD_EVENT_CODE(IIO_ACCEL,
1101                           0,
1102                           IIO_MOD_Z,
1103                           IIO_EV_TYPE_MAG,
1104                           IIO_EV_DIR_RISING),
1105                    last_timestamp);
1106 
1107 done:
1108     return IRQ_HANDLED;
1109 }
1110 
1111 /*
1112  * sca3000_read_event_config() what events are enabled
1113  */
1114 static int sca3000_read_event_config(struct iio_dev *indio_dev,
1115                      const struct iio_chan_spec *chan,
1116                      enum iio_event_type type,
1117                      enum iio_event_direction dir)
1118 {
1119     struct sca3000_state *st = iio_priv(indio_dev);
1120     int ret;
1121     /* read current value of mode register */
1122     mutex_lock(&st->lock);
1123 
1124     ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 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_REG_MODE_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] & SCA3000_REG_MODE_MODE_MASK)
1140             != SCA3000_REG_MODE_MEAS_MODE_MOT_DET) {
1141             ret = 0;
1142         } else {
1143             ret = sca3000_read_ctrl_reg(st,
1144                         SCA3000_REG_CTRL_SEL_MD_CTRL);
1145             if (ret < 0)
1146                 goto error_ret;
1147             /* only supporting logical or's for now */
1148             ret = !!(ret & sca3000_addresses[chan->address][2]);
1149         }
1150         break;
1151     default:
1152         ret = -EINVAL;
1153     }
1154 
1155 error_ret:
1156     mutex_unlock(&st->lock);
1157 
1158     return ret;
1159 }
1160 
1161 static int sca3000_freefall_set_state(struct iio_dev *indio_dev, int state)
1162 {
1163     struct sca3000_state *st = iio_priv(indio_dev);
1164     int ret;
1165 
1166     /* read current value of mode register */
1167     ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
1168     if (ret)
1169         return ret;
1170 
1171     /* if off and should be on */
1172     if (state && !(st->rx[0] & SCA3000_REG_MODE_FREE_FALL_DETECT))
1173         return sca3000_write_reg(st, SCA3000_REG_MODE_ADDR,
1174                      st->rx[0] | SCA3000_REG_MODE_FREE_FALL_DETECT);
1175     /* if on and should be off */
1176     else if (!state && (st->rx[0] & SCA3000_REG_MODE_FREE_FALL_DETECT))
1177         return sca3000_write_reg(st, SCA3000_REG_MODE_ADDR,
1178                      st->rx[0] & ~SCA3000_REG_MODE_FREE_FALL_DETECT);
1179     else
1180         return 0;
1181 }
1182 
1183 static int sca3000_motion_detect_set_state(struct iio_dev *indio_dev, int axis,
1184                        int state)
1185 {
1186     struct sca3000_state *st = iio_priv(indio_dev);
1187     int ret, ctrlval;
1188 
1189     /*
1190      * First read the motion detector config to find out if
1191      * this axis is on
1192      */
1193     ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_MD_CTRL);
1194     if (ret < 0)
1195         return ret;
1196     ctrlval = ret;
1197     /* if off and should be on */
1198     if (state && !(ctrlval & sca3000_addresses[axis][2])) {
1199         ret = sca3000_write_ctrl_reg(st,
1200                          SCA3000_REG_CTRL_SEL_MD_CTRL,
1201                          ctrlval |
1202                          sca3000_addresses[axis][2]);
1203         if (ret)
1204             return ret;
1205         st->mo_det_use_count++;
1206     } else if (!state && (ctrlval & sca3000_addresses[axis][2])) {
1207         ret = sca3000_write_ctrl_reg(st,
1208                          SCA3000_REG_CTRL_SEL_MD_CTRL,
1209                          ctrlval &
1210                          ~(sca3000_addresses[axis][2]));
1211         if (ret)
1212             return ret;
1213         st->mo_det_use_count--;
1214     }
1215 
1216     /* read current value of mode register */
1217     ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
1218     if (ret)
1219         return ret;
1220     /* if off and should be on */
1221     if ((st->mo_det_use_count) &&
1222         ((st->rx[0] & SCA3000_REG_MODE_MODE_MASK)
1223          != SCA3000_REG_MODE_MEAS_MODE_MOT_DET))
1224         return sca3000_write_reg(st, SCA3000_REG_MODE_ADDR,
1225             (st->rx[0] & ~SCA3000_REG_MODE_MODE_MASK)
1226             | SCA3000_REG_MODE_MEAS_MODE_MOT_DET);
1227     /* if on and should be off */
1228     else if (!(st->mo_det_use_count) &&
1229          ((st->rx[0] & SCA3000_REG_MODE_MODE_MASK)
1230           == SCA3000_REG_MODE_MEAS_MODE_MOT_DET))
1231         return sca3000_write_reg(st, SCA3000_REG_MODE_ADDR,
1232             st->rx[0] & SCA3000_REG_MODE_MODE_MASK);
1233     else
1234         return 0;
1235 }
1236 
1237 /**
1238  * sca3000_write_event_config() - simple on off control for motion detector
1239  * @indio_dev: IIO device instance specific structure. Data specific to this
1240  * particular driver may be accessed via iio_priv(indio_dev).
1241  * @chan: Description of the channel whose event we are configuring.
1242  * @type: The type of event.
1243  * @dir: The direction of the event.
1244  * @state: Desired state of event being configured.
1245  *
1246  * This is a per axis control, but enabling any will result in the
1247  * motion detector unit being enabled.
1248  * N.B. enabling motion detector stops normal data acquisition.
1249  * There is a complexity in knowing which mode to return to when
1250  * this mode is disabled.  Currently normal mode is assumed.
1251  **/
1252 static int sca3000_write_event_config(struct iio_dev *indio_dev,
1253                       const struct iio_chan_spec *chan,
1254                       enum iio_event_type type,
1255                       enum iio_event_direction dir,
1256                       int state)
1257 {
1258     struct sca3000_state *st = iio_priv(indio_dev);
1259     int ret;
1260 
1261     mutex_lock(&st->lock);
1262     switch (chan->channel2) {
1263     case IIO_MOD_X_AND_Y_AND_Z:
1264         ret = sca3000_freefall_set_state(indio_dev, state);
1265         break;
1266 
1267     case IIO_MOD_X:
1268     case IIO_MOD_Y:
1269     case IIO_MOD_Z:
1270         ret = sca3000_motion_detect_set_state(indio_dev,
1271                               chan->address,
1272                               state);
1273         break;
1274     default:
1275         ret = -EINVAL;
1276         break;
1277     }
1278     mutex_unlock(&st->lock);
1279 
1280     return ret;
1281 }
1282 
1283 static inline
1284 int __sca3000_hw_ring_state_set(struct iio_dev *indio_dev, bool state)
1285 {
1286     struct sca3000_state *st = iio_priv(indio_dev);
1287     int ret;
1288 
1289     mutex_lock(&st->lock);
1290     ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
1291     if (ret)
1292         goto error_ret;
1293     if (state) {
1294         dev_info(&indio_dev->dev, "supposedly enabling ring buffer\n");
1295         ret = sca3000_write_reg(st,
1296             SCA3000_REG_MODE_ADDR,
1297             (st->rx[0] | SCA3000_REG_MODE_RING_BUF_ENABLE));
1298     } else
1299         ret = sca3000_write_reg(st,
1300             SCA3000_REG_MODE_ADDR,
1301             (st->rx[0] & ~SCA3000_REG_MODE_RING_BUF_ENABLE));
1302 error_ret:
1303     mutex_unlock(&st->lock);
1304 
1305     return ret;
1306 }
1307 
1308 /**
1309  * sca3000_hw_ring_preenable() - hw ring buffer preenable function
1310  * @indio_dev: structure representing the IIO device. Device instance
1311  * specific state can be accessed via iio_priv(indio_dev).
1312  *
1313  * Very simple enable function as the chip will allows normal reads
1314  * during ring buffer operation so as long as it is indeed running
1315  * before we notify the core, the precise ordering does not matter.
1316  */
1317 static int sca3000_hw_ring_preenable(struct iio_dev *indio_dev)
1318 {
1319     int ret;
1320     struct sca3000_state *st = iio_priv(indio_dev);
1321 
1322     mutex_lock(&st->lock);
1323 
1324     /* Enable the 50% full interrupt */
1325     ret = sca3000_read_data_short(st, SCA3000_REG_INT_MASK_ADDR, 1);
1326     if (ret)
1327         goto error_unlock;
1328     ret = sca3000_write_reg(st,
1329                 SCA3000_REG_INT_MASK_ADDR,
1330                 st->rx[0] | SCA3000_REG_INT_MASK_RING_HALF);
1331     if (ret)
1332         goto error_unlock;
1333 
1334     mutex_unlock(&st->lock);
1335 
1336     return __sca3000_hw_ring_state_set(indio_dev, 1);
1337 
1338 error_unlock:
1339     mutex_unlock(&st->lock);
1340 
1341     return ret;
1342 }
1343 
1344 static int sca3000_hw_ring_postdisable(struct iio_dev *indio_dev)
1345 {
1346     int ret;
1347     struct sca3000_state *st = iio_priv(indio_dev);
1348 
1349     ret = __sca3000_hw_ring_state_set(indio_dev, 0);
1350     if (ret)
1351         return ret;
1352 
1353     /* Disable the 50% full interrupt */
1354     mutex_lock(&st->lock);
1355 
1356     ret = sca3000_read_data_short(st, SCA3000_REG_INT_MASK_ADDR, 1);
1357     if (ret)
1358         goto unlock;
1359     ret = sca3000_write_reg(st,
1360                 SCA3000_REG_INT_MASK_ADDR,
1361                 st->rx[0] & ~SCA3000_REG_INT_MASK_RING_HALF);
1362 unlock:
1363     mutex_unlock(&st->lock);
1364     return ret;
1365 }
1366 
1367 static const struct iio_buffer_setup_ops sca3000_ring_setup_ops = {
1368     .preenable = &sca3000_hw_ring_preenable,
1369     .postdisable = &sca3000_hw_ring_postdisable,
1370 };
1371 
1372 /**
1373  * sca3000_clean_setup() - get the device into a predictable state
1374  * @st: Device instance specific private data structure
1375  *
1376  * Devices use flash memory to store many of the register values
1377  * and hence can come up in somewhat unpredictable states.
1378  * Hence reset everything on driver load.
1379  */
1380 static int sca3000_clean_setup(struct sca3000_state *st)
1381 {
1382     int ret;
1383 
1384     mutex_lock(&st->lock);
1385     /* Ensure all interrupts have been acknowledged */
1386     ret = sca3000_read_data_short(st, SCA3000_REG_INT_STATUS_ADDR, 1);
1387     if (ret)
1388         goto error_ret;
1389 
1390     /* Turn off all motion detection channels */
1391     ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_MD_CTRL);
1392     if (ret < 0)
1393         goto error_ret;
1394     ret = sca3000_write_ctrl_reg(st, SCA3000_REG_CTRL_SEL_MD_CTRL,
1395                      ret & SCA3000_MD_CTRL_PROT_MASK);
1396     if (ret)
1397         goto error_ret;
1398 
1399     /* Disable ring buffer */
1400     ret = sca3000_read_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL);
1401     if (ret < 0)
1402         goto error_ret;
1403     ret = sca3000_write_ctrl_reg(st, SCA3000_REG_CTRL_SEL_OUT_CTRL,
1404                      (ret & SCA3000_REG_OUT_CTRL_PROT_MASK)
1405                      | SCA3000_REG_OUT_CTRL_BUF_X_EN
1406                      | SCA3000_REG_OUT_CTRL_BUF_Y_EN
1407                      | SCA3000_REG_OUT_CTRL_BUF_Z_EN
1408                      | SCA3000_REG_OUT_CTRL_BUF_DIV_4);
1409     if (ret)
1410         goto error_ret;
1411     /* Enable interrupts, relevant to mode and set up as active low */
1412     ret = sca3000_read_data_short(st, SCA3000_REG_INT_MASK_ADDR, 1);
1413     if (ret)
1414         goto error_ret;
1415     ret = sca3000_write_reg(st,
1416                 SCA3000_REG_INT_MASK_ADDR,
1417                 (ret & SCA3000_REG_INT_MASK_PROT_MASK)
1418                 | SCA3000_REG_INT_MASK_ACTIVE_LOW);
1419     if (ret)
1420         goto error_ret;
1421     /*
1422      * Select normal measurement mode, free fall off, ring off
1423      * Ring in 12 bit mode - it is fine to overwrite reserved bits 3,5
1424      * as that occurs in one of the example on the datasheet
1425      */
1426     ret = sca3000_read_data_short(st, SCA3000_REG_MODE_ADDR, 1);
1427     if (ret)
1428         goto error_ret;
1429     ret = sca3000_write_reg(st, SCA3000_REG_MODE_ADDR,
1430                 (st->rx[0] & SCA3000_MODE_PROT_MASK));
1431 
1432 error_ret:
1433     mutex_unlock(&st->lock);
1434     return ret;
1435 }
1436 
1437 static const struct iio_info sca3000_info = {
1438     .attrs = &sca3000_attribute_group,
1439     .read_raw = &sca3000_read_raw,
1440     .write_raw = &sca3000_write_raw,
1441     .read_event_value = &sca3000_read_event_value,
1442     .write_event_value = &sca3000_write_event_value,
1443     .read_event_config = &sca3000_read_event_config,
1444     .write_event_config = &sca3000_write_event_config,
1445 };
1446 
1447 static int sca3000_probe(struct spi_device *spi)
1448 {
1449     int ret;
1450     struct sca3000_state *st;
1451     struct iio_dev *indio_dev;
1452 
1453     indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
1454     if (!indio_dev)
1455         return -ENOMEM;
1456 
1457     st = iio_priv(indio_dev);
1458     spi_set_drvdata(spi, indio_dev);
1459     st->us = spi;
1460     mutex_init(&st->lock);
1461     st->info = &sca3000_spi_chip_info_tbl[spi_get_device_id(spi)
1462                           ->driver_data];
1463 
1464     indio_dev->name = spi_get_device_id(spi)->name;
1465     indio_dev->info = &sca3000_info;
1466     if (st->info->temp_output) {
1467         indio_dev->channels = sca3000_channels_with_temp;
1468         indio_dev->num_channels =
1469             ARRAY_SIZE(sca3000_channels_with_temp);
1470     } else {
1471         indio_dev->channels = sca3000_channels;
1472         indio_dev->num_channels = ARRAY_SIZE(sca3000_channels);
1473     }
1474     indio_dev->modes = INDIO_DIRECT_MODE;
1475 
1476     ret = devm_iio_kfifo_buffer_setup(&spi->dev, indio_dev,
1477                       &sca3000_ring_setup_ops);
1478     if (ret)
1479         return ret;
1480 
1481     if (spi->irq) {
1482         ret = request_threaded_irq(spi->irq,
1483                        NULL,
1484                        &sca3000_event_handler,
1485                        IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
1486                        "sca3000",
1487                        indio_dev);
1488         if (ret)
1489             return ret;
1490     }
1491     ret = sca3000_clean_setup(st);
1492     if (ret)
1493         goto error_free_irq;
1494 
1495     ret = sca3000_print_rev(indio_dev);
1496     if (ret)
1497         goto error_free_irq;
1498 
1499     return iio_device_register(indio_dev);
1500 
1501 error_free_irq:
1502     if (spi->irq)
1503         free_irq(spi->irq, indio_dev);
1504 
1505     return ret;
1506 }
1507 
1508 static int sca3000_stop_all_interrupts(struct sca3000_state *st)
1509 {
1510     int ret;
1511 
1512     mutex_lock(&st->lock);
1513     ret = sca3000_read_data_short(st, SCA3000_REG_INT_MASK_ADDR, 1);
1514     if (ret)
1515         goto error_ret;
1516     ret = sca3000_write_reg(st, SCA3000_REG_INT_MASK_ADDR,
1517                 (st->rx[0] &
1518                  ~(SCA3000_REG_INT_MASK_RING_THREE_QUARTER |
1519                    SCA3000_REG_INT_MASK_RING_HALF |
1520                    SCA3000_REG_INT_MASK_ALL_INTS)));
1521 error_ret:
1522     mutex_unlock(&st->lock);
1523     return ret;
1524 }
1525 
1526 static void sca3000_remove(struct spi_device *spi)
1527 {
1528     struct iio_dev *indio_dev = spi_get_drvdata(spi);
1529     struct sca3000_state *st = iio_priv(indio_dev);
1530 
1531     iio_device_unregister(indio_dev);
1532 
1533     /* Must ensure no interrupts can be generated after this! */
1534     sca3000_stop_all_interrupts(st);
1535     if (spi->irq)
1536         free_irq(spi->irq, indio_dev);
1537 }
1538 
1539 static const struct spi_device_id sca3000_id[] = {
1540     {"sca3000_d01", d01},
1541     {"sca3000_e02", e02},
1542     {"sca3000_e04", e04},
1543     {"sca3000_e05", e05},
1544     {}
1545 };
1546 MODULE_DEVICE_TABLE(spi, sca3000_id);
1547 
1548 static struct spi_driver sca3000_driver = {
1549     .driver = {
1550         .name = "sca3000",
1551     },
1552     .probe = sca3000_probe,
1553     .remove = sca3000_remove,
1554     .id_table = sca3000_id,
1555 };
1556 module_spi_driver(sca3000_driver);
1557 
1558 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1559 MODULE_DESCRIPTION("VTI SCA3000 Series Accelerometers SPI driver");
1560 MODULE_LICENSE("GPL v2");