Merge tag 'iio-fixes-for-5.2a' of git://git.kernel.org/pub/scm/linux/kernel/git/jic23...
[linux-2.6-microblaze.git] / drivers / iio / imu / inv_mpu6050 / inv_mpu_core.c
1 /*
2 * Copyright (C) 2012 Invensense, Inc.
3 *
4 * This software is licensed under the terms of the GNU General Public
5 * License version 2, as published by the Free Software Foundation, and
6 * may be copied, distributed, and modified under those terms.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 * GNU General Public License for more details.
12 */
13
14 #include <linux/module.h>
15 #include <linux/slab.h>
16 #include <linux/i2c.h>
17 #include <linux/err.h>
18 #include <linux/delay.h>
19 #include <linux/sysfs.h>
20 #include <linux/jiffies.h>
21 #include <linux/irq.h>
22 #include <linux/interrupt.h>
23 #include <linux/iio/iio.h>
24 #include <linux/acpi.h>
25 #include <linux/platform_device.h>
26 #include <linux/regulator/consumer.h>
27 #include "inv_mpu_iio.h"
28
29 /*
30  * this is the gyro scale translated from dynamic range plus/minus
31  * {250, 500, 1000, 2000} to rad/s
32  */
33 static const int gyro_scale_6050[] = {133090, 266181, 532362, 1064724};
34
35 /*
36  * this is the accel scale translated from dynamic range plus/minus
37  * {2, 4, 8, 16} to m/s^2
38  */
39 static const int accel_scale[] = {598, 1196, 2392, 4785};
40
41 static const struct inv_mpu6050_reg_map reg_set_icm20602 = {
42         .sample_rate_div        = INV_MPU6050_REG_SAMPLE_RATE_DIV,
43         .lpf                    = INV_MPU6050_REG_CONFIG,
44         .accel_lpf              = INV_MPU6500_REG_ACCEL_CONFIG_2,
45         .user_ctrl              = INV_MPU6050_REG_USER_CTRL,
46         .fifo_en                = INV_MPU6050_REG_FIFO_EN,
47         .gyro_config            = INV_MPU6050_REG_GYRO_CONFIG,
48         .accl_config            = INV_MPU6050_REG_ACCEL_CONFIG,
49         .fifo_count_h           = INV_MPU6050_REG_FIFO_COUNT_H,
50         .fifo_r_w               = INV_MPU6050_REG_FIFO_R_W,
51         .raw_gyro               = INV_MPU6050_REG_RAW_GYRO,
52         .raw_accl               = INV_MPU6050_REG_RAW_ACCEL,
53         .temperature            = INV_MPU6050_REG_TEMPERATURE,
54         .int_enable             = INV_MPU6050_REG_INT_ENABLE,
55         .int_status             = INV_MPU6050_REG_INT_STATUS,
56         .pwr_mgmt_1             = INV_MPU6050_REG_PWR_MGMT_1,
57         .pwr_mgmt_2             = INV_MPU6050_REG_PWR_MGMT_2,
58         .int_pin_cfg            = INV_MPU6050_REG_INT_PIN_CFG,
59         .accl_offset            = INV_MPU6500_REG_ACCEL_OFFSET,
60         .gyro_offset            = INV_MPU6050_REG_GYRO_OFFSET,
61         .i2c_if                 = INV_ICM20602_REG_I2C_IF,
62 };
63
64 static const struct inv_mpu6050_reg_map reg_set_6500 = {
65         .sample_rate_div        = INV_MPU6050_REG_SAMPLE_RATE_DIV,
66         .lpf                    = INV_MPU6050_REG_CONFIG,
67         .accel_lpf              = INV_MPU6500_REG_ACCEL_CONFIG_2,
68         .user_ctrl              = INV_MPU6050_REG_USER_CTRL,
69         .fifo_en                = INV_MPU6050_REG_FIFO_EN,
70         .gyro_config            = INV_MPU6050_REG_GYRO_CONFIG,
71         .accl_config            = INV_MPU6050_REG_ACCEL_CONFIG,
72         .fifo_count_h           = INV_MPU6050_REG_FIFO_COUNT_H,
73         .fifo_r_w               = INV_MPU6050_REG_FIFO_R_W,
74         .raw_gyro               = INV_MPU6050_REG_RAW_GYRO,
75         .raw_accl               = INV_MPU6050_REG_RAW_ACCEL,
76         .temperature            = INV_MPU6050_REG_TEMPERATURE,
77         .int_enable             = INV_MPU6050_REG_INT_ENABLE,
78         .int_status             = INV_MPU6050_REG_INT_STATUS,
79         .pwr_mgmt_1             = INV_MPU6050_REG_PWR_MGMT_1,
80         .pwr_mgmt_2             = INV_MPU6050_REG_PWR_MGMT_2,
81         .int_pin_cfg            = INV_MPU6050_REG_INT_PIN_CFG,
82         .accl_offset            = INV_MPU6500_REG_ACCEL_OFFSET,
83         .gyro_offset            = INV_MPU6050_REG_GYRO_OFFSET,
84         .i2c_if                 = 0,
85 };
86
87 static const struct inv_mpu6050_reg_map reg_set_6050 = {
88         .sample_rate_div        = INV_MPU6050_REG_SAMPLE_RATE_DIV,
89         .lpf                    = INV_MPU6050_REG_CONFIG,
90         .user_ctrl              = INV_MPU6050_REG_USER_CTRL,
91         .fifo_en                = INV_MPU6050_REG_FIFO_EN,
92         .gyro_config            = INV_MPU6050_REG_GYRO_CONFIG,
93         .accl_config            = INV_MPU6050_REG_ACCEL_CONFIG,
94         .fifo_count_h           = INV_MPU6050_REG_FIFO_COUNT_H,
95         .fifo_r_w               = INV_MPU6050_REG_FIFO_R_W,
96         .raw_gyro               = INV_MPU6050_REG_RAW_GYRO,
97         .raw_accl               = INV_MPU6050_REG_RAW_ACCEL,
98         .temperature            = INV_MPU6050_REG_TEMPERATURE,
99         .int_enable             = INV_MPU6050_REG_INT_ENABLE,
100         .pwr_mgmt_1             = INV_MPU6050_REG_PWR_MGMT_1,
101         .pwr_mgmt_2             = INV_MPU6050_REG_PWR_MGMT_2,
102         .int_pin_cfg            = INV_MPU6050_REG_INT_PIN_CFG,
103         .accl_offset            = INV_MPU6050_REG_ACCEL_OFFSET,
104         .gyro_offset            = INV_MPU6050_REG_GYRO_OFFSET,
105         .i2c_if                 = 0,
106 };
107
108 static const struct inv_mpu6050_chip_config chip_config_6050 = {
109         .fsr = INV_MPU6050_FSR_2000DPS,
110         .lpf = INV_MPU6050_FILTER_20HZ,
111         .divider = INV_MPU6050_FIFO_RATE_TO_DIVIDER(INV_MPU6050_INIT_FIFO_RATE),
112         .gyro_fifo_enable = false,
113         .accl_fifo_enable = false,
114         .accl_fs = INV_MPU6050_FS_02G,
115         .user_ctrl = 0,
116 };
117
118 /* Indexed by enum inv_devices */
119 static const struct inv_mpu6050_hw hw_info[] = {
120         {
121                 .whoami = INV_MPU6050_WHOAMI_VALUE,
122                 .name = "MPU6050",
123                 .reg = &reg_set_6050,
124                 .config = &chip_config_6050,
125         },
126         {
127                 .whoami = INV_MPU6500_WHOAMI_VALUE,
128                 .name = "MPU6500",
129                 .reg = &reg_set_6500,
130                 .config = &chip_config_6050,
131         },
132         {
133                 .whoami = INV_MPU6515_WHOAMI_VALUE,
134                 .name = "MPU6515",
135                 .reg = &reg_set_6500,
136                 .config = &chip_config_6050,
137         },
138         {
139                 .whoami = INV_MPU6000_WHOAMI_VALUE,
140                 .name = "MPU6000",
141                 .reg = &reg_set_6050,
142                 .config = &chip_config_6050,
143         },
144         {
145                 .whoami = INV_MPU9150_WHOAMI_VALUE,
146                 .name = "MPU9150",
147                 .reg = &reg_set_6050,
148                 .config = &chip_config_6050,
149         },
150         {
151                 .whoami = INV_MPU9250_WHOAMI_VALUE,
152                 .name = "MPU9250",
153                 .reg = &reg_set_6500,
154                 .config = &chip_config_6050,
155         },
156         {
157                 .whoami = INV_MPU9255_WHOAMI_VALUE,
158                 .name = "MPU9255",
159                 .reg = &reg_set_6500,
160                 .config = &chip_config_6050,
161         },
162         {
163                 .whoami = INV_ICM20608_WHOAMI_VALUE,
164                 .name = "ICM20608",
165                 .reg = &reg_set_6500,
166                 .config = &chip_config_6050,
167         },
168         {
169                 .whoami = INV_ICM20602_WHOAMI_VALUE,
170                 .name = "ICM20602",
171                 .reg = &reg_set_icm20602,
172                 .config = &chip_config_6050,
173         },
174 };
175
176 int inv_mpu6050_switch_engine(struct inv_mpu6050_state *st, bool en, u32 mask)
177 {
178         unsigned int d, mgmt_1;
179         int result;
180         /*
181          * switch clock needs to be careful. Only when gyro is on, can
182          * clock source be switched to gyro. Otherwise, it must be set to
183          * internal clock
184          */
185         if (mask == INV_MPU6050_BIT_PWR_GYRO_STBY) {
186                 result = regmap_read(st->map, st->reg->pwr_mgmt_1, &mgmt_1);
187                 if (result)
188                         return result;
189
190                 mgmt_1 &= ~INV_MPU6050_BIT_CLK_MASK;
191         }
192
193         if ((mask == INV_MPU6050_BIT_PWR_GYRO_STBY) && (!en)) {
194                 /*
195                  * turning off gyro requires switch to internal clock first.
196                  * Then turn off gyro engine
197                  */
198                 mgmt_1 |= INV_CLK_INTERNAL;
199                 result = regmap_write(st->map, st->reg->pwr_mgmt_1, mgmt_1);
200                 if (result)
201                         return result;
202         }
203
204         result = regmap_read(st->map, st->reg->pwr_mgmt_2, &d);
205         if (result)
206                 return result;
207         if (en)
208                 d &= ~mask;
209         else
210                 d |= mask;
211         result = regmap_write(st->map, st->reg->pwr_mgmt_2, d);
212         if (result)
213                 return result;
214
215         if (en) {
216                 /* Wait for output to stabilize */
217                 msleep(INV_MPU6050_TEMP_UP_TIME);
218                 if (mask == INV_MPU6050_BIT_PWR_GYRO_STBY) {
219                         /* switch internal clock to PLL */
220                         mgmt_1 |= INV_CLK_PLL;
221                         result = regmap_write(st->map,
222                                               st->reg->pwr_mgmt_1, mgmt_1);
223                         if (result)
224                                 return result;
225                 }
226         }
227
228         return 0;
229 }
230
231 int inv_mpu6050_set_power_itg(struct inv_mpu6050_state *st, bool power_on)
232 {
233         int result;
234
235         if (power_on) {
236                 if (!st->powerup_count) {
237                         result = regmap_write(st->map, st->reg->pwr_mgmt_1, 0);
238                         if (result)
239                                 return result;
240                         usleep_range(INV_MPU6050_REG_UP_TIME_MIN,
241                                      INV_MPU6050_REG_UP_TIME_MAX);
242                 }
243                 st->powerup_count++;
244         } else {
245                 if (st->powerup_count == 1) {
246                         result = regmap_write(st->map, st->reg->pwr_mgmt_1,
247                                               INV_MPU6050_BIT_SLEEP);
248                         if (result)
249                                 return result;
250                 }
251                 st->powerup_count--;
252         }
253
254         dev_dbg(regmap_get_device(st->map), "set power %d, count=%u\n",
255                 power_on, st->powerup_count);
256
257         return 0;
258 }
259 EXPORT_SYMBOL_GPL(inv_mpu6050_set_power_itg);
260
261 /**
262  *  inv_mpu6050_set_lpf_regs() - set low pass filter registers, chip dependent
263  *
264  *  MPU60xx/MPU9150 use only 1 register for accelerometer + gyroscope
265  *  MPU6500 and above have a dedicated register for accelerometer
266  */
267 static int inv_mpu6050_set_lpf_regs(struct inv_mpu6050_state *st,
268                                     enum inv_mpu6050_filter_e val)
269 {
270         int result;
271
272         result = regmap_write(st->map, st->reg->lpf, val);
273         if (result)
274                 return result;
275
276         switch (st->chip_type) {
277         case INV_MPU6050:
278         case INV_MPU6000:
279         case INV_MPU9150:
280                 /* old chips, nothing to do */
281                 result = 0;
282                 break;
283         default:
284                 /* set accel lpf */
285                 result = regmap_write(st->map, st->reg->accel_lpf, val);
286                 break;
287         }
288
289         return result;
290 }
291
292 /**
293  *  inv_mpu6050_init_config() - Initialize hardware, disable FIFO.
294  *
295  *  Initial configuration:
296  *  FSR: Â± 2000DPS
297  *  DLPF: 20Hz
298  *  FIFO rate: 50Hz
299  *  Clock source: Gyro PLL
300  */
301 static int inv_mpu6050_init_config(struct iio_dev *indio_dev)
302 {
303         int result;
304         u8 d;
305         struct inv_mpu6050_state *st = iio_priv(indio_dev);
306
307         result = inv_mpu6050_set_power_itg(st, true);
308         if (result)
309                 return result;
310         d = (INV_MPU6050_FSR_2000DPS << INV_MPU6050_GYRO_CONFIG_FSR_SHIFT);
311         result = regmap_write(st->map, st->reg->gyro_config, d);
312         if (result)
313                 goto error_power_off;
314
315         result = inv_mpu6050_set_lpf_regs(st, INV_MPU6050_FILTER_20HZ);
316         if (result)
317                 goto error_power_off;
318
319         d = INV_MPU6050_FIFO_RATE_TO_DIVIDER(INV_MPU6050_INIT_FIFO_RATE);
320         result = regmap_write(st->map, st->reg->sample_rate_div, d);
321         if (result)
322                 goto error_power_off;
323
324         d = (INV_MPU6050_FS_02G << INV_MPU6050_ACCL_CONFIG_FSR_SHIFT);
325         result = regmap_write(st->map, st->reg->accl_config, d);
326         if (result)
327                 goto error_power_off;
328
329         result = regmap_write(st->map, st->reg->int_pin_cfg, st->irq_mask);
330         if (result)
331                 return result;
332
333         memcpy(&st->chip_config, hw_info[st->chip_type].config,
334                sizeof(struct inv_mpu6050_chip_config));
335
336         /*
337          * Internal chip period is 1ms (1kHz).
338          * Let's use at the beginning the theorical value before measuring
339          * with interrupt timestamps.
340          */
341         st->chip_period = NSEC_PER_MSEC;
342
343         return inv_mpu6050_set_power_itg(st, false);
344
345 error_power_off:
346         inv_mpu6050_set_power_itg(st, false);
347         return result;
348 }
349
350 static int inv_mpu6050_sensor_set(struct inv_mpu6050_state  *st, int reg,
351                                 int axis, int val)
352 {
353         int ind, result;
354         __be16 d = cpu_to_be16(val);
355
356         ind = (axis - IIO_MOD_X) * 2;
357         result = regmap_bulk_write(st->map, reg + ind, (u8 *)&d, 2);
358         if (result)
359                 return -EINVAL;
360
361         return 0;
362 }
363
364 static int inv_mpu6050_sensor_show(struct inv_mpu6050_state  *st, int reg,
365                                    int axis, int *val)
366 {
367         int ind, result;
368         __be16 d;
369
370         ind = (axis - IIO_MOD_X) * 2;
371         result = regmap_bulk_read(st->map, reg + ind, (u8 *)&d, 2);
372         if (result)
373                 return -EINVAL;
374         *val = (short)be16_to_cpup(&d);
375
376         return IIO_VAL_INT;
377 }
378
379 static int inv_mpu6050_read_channel_data(struct iio_dev *indio_dev,
380                                          struct iio_chan_spec const *chan,
381                                          int *val)
382 {
383         struct inv_mpu6050_state *st = iio_priv(indio_dev);
384         int result;
385         int ret;
386
387         result = inv_mpu6050_set_power_itg(st, true);
388         if (result)
389                 return result;
390
391         switch (chan->type) {
392         case IIO_ANGL_VEL:
393                 result = inv_mpu6050_switch_engine(st, true,
394                                 INV_MPU6050_BIT_PWR_GYRO_STBY);
395                 if (result)
396                         goto error_power_off;
397                 ret = inv_mpu6050_sensor_show(st, st->reg->raw_gyro,
398                                               chan->channel2, val);
399                 result = inv_mpu6050_switch_engine(st, false,
400                                 INV_MPU6050_BIT_PWR_GYRO_STBY);
401                 if (result)
402                         goto error_power_off;
403                 break;
404         case IIO_ACCEL:
405                 result = inv_mpu6050_switch_engine(st, true,
406                                 INV_MPU6050_BIT_PWR_ACCL_STBY);
407                 if (result)
408                         goto error_power_off;
409                 ret = inv_mpu6050_sensor_show(st, st->reg->raw_accl,
410                                               chan->channel2, val);
411                 result = inv_mpu6050_switch_engine(st, false,
412                                 INV_MPU6050_BIT_PWR_ACCL_STBY);
413                 if (result)
414                         goto error_power_off;
415                 break;
416         case IIO_TEMP:
417                 /* wait for stablization */
418                 msleep(INV_MPU6050_SENSOR_UP_TIME);
419                 ret = inv_mpu6050_sensor_show(st, st->reg->temperature,
420                                               IIO_MOD_X, val);
421                 break;
422         default:
423                 ret = -EINVAL;
424                 break;
425         }
426
427         result = inv_mpu6050_set_power_itg(st, false);
428         if (result)
429                 goto error_power_off;
430
431         return ret;
432
433 error_power_off:
434         inv_mpu6050_set_power_itg(st, false);
435         return result;
436 }
437
438 static int
439 inv_mpu6050_read_raw(struct iio_dev *indio_dev,
440                      struct iio_chan_spec const *chan,
441                      int *val, int *val2, long mask)
442 {
443         struct inv_mpu6050_state  *st = iio_priv(indio_dev);
444         int ret = 0;
445
446         switch (mask) {
447         case IIO_CHAN_INFO_RAW:
448                 ret = iio_device_claim_direct_mode(indio_dev);
449                 if (ret)
450                         return ret;
451                 mutex_lock(&st->lock);
452                 ret = inv_mpu6050_read_channel_data(indio_dev, chan, val);
453                 mutex_unlock(&st->lock);
454                 iio_device_release_direct_mode(indio_dev);
455                 return ret;
456         case IIO_CHAN_INFO_SCALE:
457                 switch (chan->type) {
458                 case IIO_ANGL_VEL:
459                         mutex_lock(&st->lock);
460                         *val  = 0;
461                         *val2 = gyro_scale_6050[st->chip_config.fsr];
462                         mutex_unlock(&st->lock);
463
464                         return IIO_VAL_INT_PLUS_NANO;
465                 case IIO_ACCEL:
466                         mutex_lock(&st->lock);
467                         *val = 0;
468                         *val2 = accel_scale[st->chip_config.accl_fs];
469                         mutex_unlock(&st->lock);
470
471                         return IIO_VAL_INT_PLUS_MICRO;
472                 case IIO_TEMP:
473                         *val = 0;
474                         if (st->chip_type == INV_ICM20602)
475                                 *val2 = INV_ICM20602_TEMP_SCALE;
476                         else
477                                 *val2 = INV_MPU6050_TEMP_SCALE;
478
479                         return IIO_VAL_INT_PLUS_MICRO;
480                 default:
481                         return -EINVAL;
482                 }
483         case IIO_CHAN_INFO_OFFSET:
484                 switch (chan->type) {
485                 case IIO_TEMP:
486                         if (st->chip_type == INV_ICM20602)
487                                 *val = INV_ICM20602_TEMP_OFFSET;
488                         else
489                                 *val = INV_MPU6050_TEMP_OFFSET;
490
491                         return IIO_VAL_INT;
492                 default:
493                         return -EINVAL;
494                 }
495         case IIO_CHAN_INFO_CALIBBIAS:
496                 switch (chan->type) {
497                 case IIO_ANGL_VEL:
498                         mutex_lock(&st->lock);
499                         ret = inv_mpu6050_sensor_show(st, st->reg->gyro_offset,
500                                                 chan->channel2, val);
501                         mutex_unlock(&st->lock);
502                         return IIO_VAL_INT;
503                 case IIO_ACCEL:
504                         mutex_lock(&st->lock);
505                         ret = inv_mpu6050_sensor_show(st, st->reg->accl_offset,
506                                                 chan->channel2, val);
507                         mutex_unlock(&st->lock);
508                         return IIO_VAL_INT;
509
510                 default:
511                         return -EINVAL;
512                 }
513         default:
514                 return -EINVAL;
515         }
516 }
517
518 static int inv_mpu6050_write_gyro_scale(struct inv_mpu6050_state *st, int val)
519 {
520         int result, i;
521         u8 d;
522
523         for (i = 0; i < ARRAY_SIZE(gyro_scale_6050); ++i) {
524                 if (gyro_scale_6050[i] == val) {
525                         d = (i << INV_MPU6050_GYRO_CONFIG_FSR_SHIFT);
526                         result = regmap_write(st->map, st->reg->gyro_config, d);
527                         if (result)
528                                 return result;
529
530                         st->chip_config.fsr = i;
531                         return 0;
532                 }
533         }
534
535         return -EINVAL;
536 }
537
538 static int inv_write_raw_get_fmt(struct iio_dev *indio_dev,
539                                  struct iio_chan_spec const *chan, long mask)
540 {
541         switch (mask) {
542         case IIO_CHAN_INFO_SCALE:
543                 switch (chan->type) {
544                 case IIO_ANGL_VEL:
545                         return IIO_VAL_INT_PLUS_NANO;
546                 default:
547                         return IIO_VAL_INT_PLUS_MICRO;
548                 }
549         default:
550                 return IIO_VAL_INT_PLUS_MICRO;
551         }
552
553         return -EINVAL;
554 }
555
556 static int inv_mpu6050_write_accel_scale(struct inv_mpu6050_state *st, int val)
557 {
558         int result, i;
559         u8 d;
560
561         for (i = 0; i < ARRAY_SIZE(accel_scale); ++i) {
562                 if (accel_scale[i] == val) {
563                         d = (i << INV_MPU6050_ACCL_CONFIG_FSR_SHIFT);
564                         result = regmap_write(st->map, st->reg->accl_config, d);
565                         if (result)
566                                 return result;
567
568                         st->chip_config.accl_fs = i;
569                         return 0;
570                 }
571         }
572
573         return -EINVAL;
574 }
575
576 static int inv_mpu6050_write_raw(struct iio_dev *indio_dev,
577                                  struct iio_chan_spec const *chan,
578                                  int val, int val2, long mask)
579 {
580         struct inv_mpu6050_state  *st = iio_priv(indio_dev);
581         int result;
582
583         /*
584          * we should only update scale when the chip is disabled, i.e.
585          * not running
586          */
587         result = iio_device_claim_direct_mode(indio_dev);
588         if (result)
589                 return result;
590
591         mutex_lock(&st->lock);
592         result = inv_mpu6050_set_power_itg(st, true);
593         if (result)
594                 goto error_write_raw_unlock;
595
596         switch (mask) {
597         case IIO_CHAN_INFO_SCALE:
598                 switch (chan->type) {
599                 case IIO_ANGL_VEL:
600                         result = inv_mpu6050_write_gyro_scale(st, val2);
601                         break;
602                 case IIO_ACCEL:
603                         result = inv_mpu6050_write_accel_scale(st, val2);
604                         break;
605                 default:
606                         result = -EINVAL;
607                         break;
608                 }
609                 break;
610         case IIO_CHAN_INFO_CALIBBIAS:
611                 switch (chan->type) {
612                 case IIO_ANGL_VEL:
613                         result = inv_mpu6050_sensor_set(st,
614                                                         st->reg->gyro_offset,
615                                                         chan->channel2, val);
616                         break;
617                 case IIO_ACCEL:
618                         result = inv_mpu6050_sensor_set(st,
619                                                         st->reg->accl_offset,
620                                                         chan->channel2, val);
621                         break;
622                 default:
623                         result = -EINVAL;
624                         break;
625                 }
626                 break;
627         default:
628                 result = -EINVAL;
629                 break;
630         }
631
632         result |= inv_mpu6050_set_power_itg(st, false);
633 error_write_raw_unlock:
634         mutex_unlock(&st->lock);
635         iio_device_release_direct_mode(indio_dev);
636
637         return result;
638 }
639
640 /**
641  *  inv_mpu6050_set_lpf() - set low pass filer based on fifo rate.
642  *
643  *                  Based on the Nyquist principle, the sampling rate must
644  *                  exceed twice of the bandwidth of the signal, or there
645  *                  would be alising. This function basically search for the
646  *                  correct low pass parameters based on the fifo rate, e.g,
647  *                  sampling frequency.
648  *
649  *  lpf is set automatically when setting sampling rate to avoid any aliases.
650  */
651 static int inv_mpu6050_set_lpf(struct inv_mpu6050_state *st, int rate)
652 {
653         static const int hz[] = {188, 98, 42, 20, 10, 5};
654         static const int d[] = {
655                 INV_MPU6050_FILTER_188HZ, INV_MPU6050_FILTER_98HZ,
656                 INV_MPU6050_FILTER_42HZ, INV_MPU6050_FILTER_20HZ,
657                 INV_MPU6050_FILTER_10HZ, INV_MPU6050_FILTER_5HZ
658         };
659         int i, h, result;
660         u8 data;
661
662         h = (rate >> 1);
663         i = 0;
664         while ((h < hz[i]) && (i < ARRAY_SIZE(d) - 1))
665                 i++;
666         data = d[i];
667         result = inv_mpu6050_set_lpf_regs(st, data);
668         if (result)
669                 return result;
670         st->chip_config.lpf = data;
671
672         return 0;
673 }
674
675 /**
676  * inv_mpu6050_fifo_rate_store() - Set fifo rate.
677  */
678 static ssize_t
679 inv_mpu6050_fifo_rate_store(struct device *dev, struct device_attribute *attr,
680                             const char *buf, size_t count)
681 {
682         int fifo_rate;
683         u8 d;
684         int result;
685         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
686         struct inv_mpu6050_state *st = iio_priv(indio_dev);
687
688         if (kstrtoint(buf, 10, &fifo_rate))
689                 return -EINVAL;
690         if (fifo_rate < INV_MPU6050_MIN_FIFO_RATE ||
691             fifo_rate > INV_MPU6050_MAX_FIFO_RATE)
692                 return -EINVAL;
693
694         result = iio_device_claim_direct_mode(indio_dev);
695         if (result)
696                 return result;
697
698         /* compute the chip sample rate divider */
699         d = INV_MPU6050_FIFO_RATE_TO_DIVIDER(fifo_rate);
700         /* compute back the fifo rate to handle truncation cases */
701         fifo_rate = INV_MPU6050_DIVIDER_TO_FIFO_RATE(d);
702
703         mutex_lock(&st->lock);
704         if (d == st->chip_config.divider) {
705                 result = 0;
706                 goto fifo_rate_fail_unlock;
707         }
708         result = inv_mpu6050_set_power_itg(st, true);
709         if (result)
710                 goto fifo_rate_fail_unlock;
711
712         result = regmap_write(st->map, st->reg->sample_rate_div, d);
713         if (result)
714                 goto fifo_rate_fail_power_off;
715         st->chip_config.divider = d;
716
717         result = inv_mpu6050_set_lpf(st, fifo_rate);
718         if (result)
719                 goto fifo_rate_fail_power_off;
720
721 fifo_rate_fail_power_off:
722         result |= inv_mpu6050_set_power_itg(st, false);
723 fifo_rate_fail_unlock:
724         mutex_unlock(&st->lock);
725         iio_device_release_direct_mode(indio_dev);
726         if (result)
727                 return result;
728
729         return count;
730 }
731
732 /**
733  * inv_fifo_rate_show() - Get the current sampling rate.
734  */
735 static ssize_t
736 inv_fifo_rate_show(struct device *dev, struct device_attribute *attr,
737                    char *buf)
738 {
739         struct inv_mpu6050_state *st = iio_priv(dev_to_iio_dev(dev));
740         unsigned fifo_rate;
741
742         mutex_lock(&st->lock);
743         fifo_rate = INV_MPU6050_DIVIDER_TO_FIFO_RATE(st->chip_config.divider);
744         mutex_unlock(&st->lock);
745
746         return scnprintf(buf, PAGE_SIZE, "%u\n", fifo_rate);
747 }
748
749 /**
750  * inv_attr_show() - calling this function will show current
751  *                    parameters.
752  *
753  * Deprecated in favor of IIO mounting matrix API.
754  *
755  * See inv_get_mount_matrix()
756  */
757 static ssize_t inv_attr_show(struct device *dev, struct device_attribute *attr,
758                              char *buf)
759 {
760         struct inv_mpu6050_state *st = iio_priv(dev_to_iio_dev(dev));
761         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
762         s8 *m;
763
764         switch (this_attr->address) {
765         /*
766          * In MPU6050, the two matrix are the same because gyro and accel
767          * are integrated in one chip
768          */
769         case ATTR_GYRO_MATRIX:
770         case ATTR_ACCL_MATRIX:
771                 m = st->plat_data.orientation;
772
773                 return scnprintf(buf, PAGE_SIZE,
774                         "%d, %d, %d; %d, %d, %d; %d, %d, %d\n",
775                         m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8]);
776         default:
777                 return -EINVAL;
778         }
779 }
780
781 /**
782  * inv_mpu6050_validate_trigger() - validate_trigger callback for invensense
783  *                                  MPU6050 device.
784  * @indio_dev: The IIO device
785  * @trig: The new trigger
786  *
787  * Returns: 0 if the 'trig' matches the trigger registered by the MPU6050
788  * device, -EINVAL otherwise.
789  */
790 static int inv_mpu6050_validate_trigger(struct iio_dev *indio_dev,
791                                         struct iio_trigger *trig)
792 {
793         struct inv_mpu6050_state *st = iio_priv(indio_dev);
794
795         if (st->trig != trig)
796                 return -EINVAL;
797
798         return 0;
799 }
800
801 static const struct iio_mount_matrix *
802 inv_get_mount_matrix(const struct iio_dev *indio_dev,
803                      const struct iio_chan_spec *chan)
804 {
805         struct inv_mpu6050_state *data = iio_priv(indio_dev);
806
807         return &data->orientation;
808 }
809
810 static const struct iio_chan_spec_ext_info inv_ext_info[] = {
811         IIO_MOUNT_MATRIX(IIO_SHARED_BY_TYPE, inv_get_mount_matrix),
812         { }
813 };
814
815 #define INV_MPU6050_CHAN(_type, _channel2, _index)                    \
816         {                                                             \
817                 .type = _type,                                        \
818                 .modified = 1,                                        \
819                 .channel2 = _channel2,                                \
820                 .info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE), \
821                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |        \
822                                       BIT(IIO_CHAN_INFO_CALIBBIAS),   \
823                 .scan_index = _index,                                 \
824                 .scan_type = {                                        \
825                                 .sign = 's',                          \
826                                 .realbits = 16,                       \
827                                 .storagebits = 16,                    \
828                                 .shift = 0,                           \
829                                 .endianness = IIO_BE,                 \
830                              },                                       \
831                 .ext_info = inv_ext_info,                             \
832         }
833
834 static const struct iio_chan_spec inv_mpu_channels[] = {
835         IIO_CHAN_SOFT_TIMESTAMP(INV_MPU6050_SCAN_TIMESTAMP),
836         /*
837          * Note that temperature should only be via polled reading only,
838          * not the final scan elements output.
839          */
840         {
841                 .type = IIO_TEMP,
842                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW)
843                                 | BIT(IIO_CHAN_INFO_OFFSET)
844                                 | BIT(IIO_CHAN_INFO_SCALE),
845                 .scan_index = -1,
846         },
847         INV_MPU6050_CHAN(IIO_ANGL_VEL, IIO_MOD_X, INV_MPU6050_SCAN_GYRO_X),
848         INV_MPU6050_CHAN(IIO_ANGL_VEL, IIO_MOD_Y, INV_MPU6050_SCAN_GYRO_Y),
849         INV_MPU6050_CHAN(IIO_ANGL_VEL, IIO_MOD_Z, INV_MPU6050_SCAN_GYRO_Z),
850
851         INV_MPU6050_CHAN(IIO_ACCEL, IIO_MOD_X, INV_MPU6050_SCAN_ACCL_X),
852         INV_MPU6050_CHAN(IIO_ACCEL, IIO_MOD_Y, INV_MPU6050_SCAN_ACCL_Y),
853         INV_MPU6050_CHAN(IIO_ACCEL, IIO_MOD_Z, INV_MPU6050_SCAN_ACCL_Z),
854 };
855
856 static const struct iio_chan_spec inv_icm20602_channels[] = {
857         IIO_CHAN_SOFT_TIMESTAMP(INV_ICM20602_SCAN_TIMESTAMP),
858         {
859                 .type = IIO_TEMP,
860                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW)
861                                 | BIT(IIO_CHAN_INFO_OFFSET)
862                                 | BIT(IIO_CHAN_INFO_SCALE),
863                 .scan_index = INV_ICM20602_SCAN_TEMP,
864                 .scan_type = {
865                                 .sign = 's',
866                                 .realbits = 16,
867                                 .storagebits = 16,
868                                 .shift = 0,
869                                 .endianness = IIO_BE,
870                              },
871         },
872
873         INV_MPU6050_CHAN(IIO_ANGL_VEL, IIO_MOD_X, INV_ICM20602_SCAN_GYRO_X),
874         INV_MPU6050_CHAN(IIO_ANGL_VEL, IIO_MOD_Y, INV_ICM20602_SCAN_GYRO_Y),
875         INV_MPU6050_CHAN(IIO_ANGL_VEL, IIO_MOD_Z, INV_ICM20602_SCAN_GYRO_Z),
876
877         INV_MPU6050_CHAN(IIO_ACCEL, IIO_MOD_Y, INV_ICM20602_SCAN_ACCL_Y),
878         INV_MPU6050_CHAN(IIO_ACCEL, IIO_MOD_X, INV_ICM20602_SCAN_ACCL_X),
879         INV_MPU6050_CHAN(IIO_ACCEL, IIO_MOD_Z, INV_ICM20602_SCAN_ACCL_Z),
880 };
881
882 /*
883  * The user can choose any frequency between INV_MPU6050_MIN_FIFO_RATE and
884  * INV_MPU6050_MAX_FIFO_RATE, but only these frequencies are matched by the
885  * low-pass filter. Specifically, each of these sampling rates are about twice
886  * the bandwidth of a corresponding low-pass filter, which should eliminate
887  * aliasing following the Nyquist principle. By picking a frequency different
888  * from these, the user risks aliasing effects.
889  */
890 static IIO_CONST_ATTR_SAMP_FREQ_AVAIL("10 20 50 100 200 500");
891 static IIO_CONST_ATTR(in_anglvel_scale_available,
892                                           "0.000133090 0.000266181 0.000532362 0.001064724");
893 static IIO_CONST_ATTR(in_accel_scale_available,
894                                           "0.000598 0.001196 0.002392 0.004785");
895 static IIO_DEV_ATTR_SAMP_FREQ(S_IRUGO | S_IWUSR, inv_fifo_rate_show,
896         inv_mpu6050_fifo_rate_store);
897
898 /* Deprecated: kept for userspace backward compatibility. */
899 static IIO_DEVICE_ATTR(in_gyro_matrix, S_IRUGO, inv_attr_show, NULL,
900         ATTR_GYRO_MATRIX);
901 static IIO_DEVICE_ATTR(in_accel_matrix, S_IRUGO, inv_attr_show, NULL,
902         ATTR_ACCL_MATRIX);
903
904 static struct attribute *inv_attributes[] = {
905         &iio_dev_attr_in_gyro_matrix.dev_attr.attr,  /* deprecated */
906         &iio_dev_attr_in_accel_matrix.dev_attr.attr, /* deprecated */
907         &iio_dev_attr_sampling_frequency.dev_attr.attr,
908         &iio_const_attr_sampling_frequency_available.dev_attr.attr,
909         &iio_const_attr_in_accel_scale_available.dev_attr.attr,
910         &iio_const_attr_in_anglvel_scale_available.dev_attr.attr,
911         NULL,
912 };
913
914 static const struct attribute_group inv_attribute_group = {
915         .attrs = inv_attributes
916 };
917
918 static const struct iio_info mpu_info = {
919         .read_raw = &inv_mpu6050_read_raw,
920         .write_raw = &inv_mpu6050_write_raw,
921         .write_raw_get_fmt = &inv_write_raw_get_fmt,
922         .attrs = &inv_attribute_group,
923         .validate_trigger = inv_mpu6050_validate_trigger,
924 };
925
926 /**
927  *  inv_check_and_setup_chip() - check and setup chip.
928  */
929 static int inv_check_and_setup_chip(struct inv_mpu6050_state *st)
930 {
931         int result;
932         unsigned int regval;
933         int i;
934
935         st->hw  = &hw_info[st->chip_type];
936         st->reg = hw_info[st->chip_type].reg;
937
938         /* check chip self-identification */
939         result = regmap_read(st->map, INV_MPU6050_REG_WHOAMI, &regval);
940         if (result)
941                 return result;
942         if (regval != st->hw->whoami) {
943                 /* check whoami against all possible values */
944                 for (i = 0; i < INV_NUM_PARTS; ++i) {
945                         if (regval == hw_info[i].whoami) {
946                                 dev_warn(regmap_get_device(st->map),
947                                         "whoami mismatch got %#02x (%s)"
948                                         "expected %#02hhx (%s)\n",
949                                         regval, hw_info[i].name,
950                                         st->hw->whoami, st->hw->name);
951                                 break;
952                         }
953                 }
954                 if (i >= INV_NUM_PARTS) {
955                         dev_err(regmap_get_device(st->map),
956                                 "invalid whoami %#02x expected %#02hhx (%s)\n",
957                                 regval, st->hw->whoami, st->hw->name);
958                         return -ENODEV;
959                 }
960         }
961
962         /* reset to make sure previous state are not there */
963         result = regmap_write(st->map, st->reg->pwr_mgmt_1,
964                               INV_MPU6050_BIT_H_RESET);
965         if (result)
966                 return result;
967         msleep(INV_MPU6050_POWER_UP_TIME);
968
969         /*
970          * Turn power on. After reset, the sleep bit could be on
971          * or off depending on the OTP settings. Turning power on
972          * make it in a definite state as well as making the hardware
973          * state align with the software state
974          */
975         result = inv_mpu6050_set_power_itg(st, true);
976         if (result)
977                 return result;
978
979         result = inv_mpu6050_switch_engine(st, false,
980                                            INV_MPU6050_BIT_PWR_ACCL_STBY);
981         if (result)
982                 goto error_power_off;
983         result = inv_mpu6050_switch_engine(st, false,
984                                            INV_MPU6050_BIT_PWR_GYRO_STBY);
985         if (result)
986                 goto error_power_off;
987
988         return inv_mpu6050_set_power_itg(st, false);
989
990 error_power_off:
991         inv_mpu6050_set_power_itg(st, false);
992         return result;
993 }
994
995 static int inv_mpu_core_enable_regulator(struct inv_mpu6050_state *st)
996 {
997         int result;
998
999         result = regulator_enable(st->vddio_supply);
1000         if (result) {
1001                 dev_err(regmap_get_device(st->map),
1002                         "Failed to enable regulator: %d\n", result);
1003         } else {
1004                 /* Give the device a little bit of time to start up. */
1005                 usleep_range(35000, 70000);
1006         }
1007
1008         return result;
1009 }
1010
1011 static int inv_mpu_core_disable_regulator(struct inv_mpu6050_state *st)
1012 {
1013         int result;
1014
1015         result = regulator_disable(st->vddio_supply);
1016         if (result)
1017                 dev_err(regmap_get_device(st->map),
1018                         "Failed to disable regulator: %d\n", result);
1019
1020         return result;
1021 }
1022
1023 static void inv_mpu_core_disable_regulator_action(void *_data)
1024 {
1025         inv_mpu_core_disable_regulator(_data);
1026 }
1027
1028 int inv_mpu_core_probe(struct regmap *regmap, int irq, const char *name,
1029                 int (*inv_mpu_bus_setup)(struct iio_dev *), int chip_type)
1030 {
1031         struct inv_mpu6050_state *st;
1032         struct iio_dev *indio_dev;
1033         struct inv_mpu6050_platform_data *pdata;
1034         struct device *dev = regmap_get_device(regmap);
1035         int result;
1036         struct irq_data *desc;
1037         int irq_type;
1038
1039         indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
1040         if (!indio_dev)
1041                 return -ENOMEM;
1042
1043         BUILD_BUG_ON(ARRAY_SIZE(hw_info) != INV_NUM_PARTS);
1044         if (chip_type < 0 || chip_type >= INV_NUM_PARTS) {
1045                 dev_err(dev, "Bad invensense chip_type=%d name=%s\n",
1046                                 chip_type, name);
1047                 return -ENODEV;
1048         }
1049         st = iio_priv(indio_dev);
1050         mutex_init(&st->lock);
1051         st->chip_type = chip_type;
1052         st->powerup_count = 0;
1053         st->irq = irq;
1054         st->map = regmap;
1055
1056         pdata = dev_get_platdata(dev);
1057         if (!pdata) {
1058                 result = iio_read_mount_matrix(dev, "mount-matrix",
1059                                                &st->orientation);
1060                 if (result) {
1061                         dev_err(dev, "Failed to retrieve mounting matrix %d\n",
1062                                 result);
1063                         return result;
1064                 }
1065         } else {
1066                 st->plat_data = *pdata;
1067         }
1068
1069         desc = irq_get_irq_data(irq);
1070         if (!desc) {
1071                 dev_err(dev, "Could not find IRQ %d\n", irq);
1072                 return -EINVAL;
1073         }
1074
1075         irq_type = irqd_get_trigger_type(desc);
1076         if (!irq_type)
1077                 irq_type = IRQF_TRIGGER_RISING;
1078         if (irq_type == IRQF_TRIGGER_RISING)
1079                 st->irq_mask = INV_MPU6050_ACTIVE_HIGH;
1080         else if (irq_type == IRQF_TRIGGER_FALLING)
1081                 st->irq_mask = INV_MPU6050_ACTIVE_LOW;
1082         else if (irq_type == IRQF_TRIGGER_HIGH)
1083                 st->irq_mask = INV_MPU6050_ACTIVE_HIGH |
1084                         INV_MPU6050_LATCH_INT_EN;
1085         else if (irq_type == IRQF_TRIGGER_LOW)
1086                 st->irq_mask = INV_MPU6050_ACTIVE_LOW |
1087                         INV_MPU6050_LATCH_INT_EN;
1088         else {
1089                 dev_err(dev, "Invalid interrupt type 0x%x specified\n",
1090                         irq_type);
1091                 return -EINVAL;
1092         }
1093
1094         st->vddio_supply = devm_regulator_get(dev, "vddio");
1095         if (IS_ERR(st->vddio_supply)) {
1096                 if (PTR_ERR(st->vddio_supply) != -EPROBE_DEFER)
1097                         dev_err(dev, "Failed to get vddio regulator %d\n",
1098                                 (int)PTR_ERR(st->vddio_supply));
1099
1100                 return PTR_ERR(st->vddio_supply);
1101         }
1102
1103         result = inv_mpu_core_enable_regulator(st);
1104         if (result)
1105                 return result;
1106
1107         result = devm_add_action(dev, inv_mpu_core_disable_regulator_action,
1108                                  st);
1109         if (result) {
1110                 inv_mpu_core_disable_regulator_action(st);
1111                 dev_err(dev, "Failed to setup regulator cleanup action %d\n",
1112                         result);
1113                 return result;
1114         }
1115
1116         /* power is turned on inside check chip type*/
1117         result = inv_check_and_setup_chip(st);
1118         if (result)
1119                 return result;
1120
1121         result = inv_mpu6050_init_config(indio_dev);
1122         if (result) {
1123                 dev_err(dev, "Could not initialize device.\n");
1124                 return result;
1125         }
1126
1127         if (inv_mpu_bus_setup)
1128                 inv_mpu_bus_setup(indio_dev);
1129
1130         dev_set_drvdata(dev, indio_dev);
1131         indio_dev->dev.parent = dev;
1132         /* name will be NULL when enumerated via ACPI */
1133         if (name)
1134                 indio_dev->name = name;
1135         else
1136                 indio_dev->name = dev_name(dev);
1137
1138         if (chip_type == INV_ICM20602) {
1139                 indio_dev->channels = inv_icm20602_channels;
1140                 indio_dev->num_channels = ARRAY_SIZE(inv_icm20602_channels);
1141         } else {
1142                 indio_dev->channels = inv_mpu_channels;
1143                 indio_dev->num_channels = ARRAY_SIZE(inv_mpu_channels);
1144         }
1145
1146         indio_dev->info = &mpu_info;
1147         indio_dev->modes = INDIO_BUFFER_TRIGGERED;
1148
1149         result = devm_iio_triggered_buffer_setup(dev, indio_dev,
1150                                                  iio_pollfunc_store_time,
1151                                                  inv_mpu6050_read_fifo,
1152                                                  NULL);
1153         if (result) {
1154                 dev_err(dev, "configure buffer fail %d\n", result);
1155                 return result;
1156         }
1157         result = inv_mpu6050_probe_trigger(indio_dev, irq_type);
1158         if (result) {
1159                 dev_err(dev, "trigger probe fail %d\n", result);
1160                 return result;
1161         }
1162
1163         result = devm_iio_device_register(dev, indio_dev);
1164         if (result) {
1165                 dev_err(dev, "IIO register fail %d\n", result);
1166                 return result;
1167         }
1168
1169         return 0;
1170 }
1171 EXPORT_SYMBOL_GPL(inv_mpu_core_probe);
1172
1173 #ifdef CONFIG_PM_SLEEP
1174
1175 static int inv_mpu_resume(struct device *dev)
1176 {
1177         struct inv_mpu6050_state *st = iio_priv(dev_get_drvdata(dev));
1178         int result;
1179
1180         mutex_lock(&st->lock);
1181         result = inv_mpu_core_enable_regulator(st);
1182         if (result)
1183                 goto out_unlock;
1184
1185         result = inv_mpu6050_set_power_itg(st, true);
1186 out_unlock:
1187         mutex_unlock(&st->lock);
1188
1189         return result;
1190 }
1191
1192 static int inv_mpu_suspend(struct device *dev)
1193 {
1194         struct inv_mpu6050_state *st = iio_priv(dev_get_drvdata(dev));
1195         int result;
1196
1197         mutex_lock(&st->lock);
1198         result = inv_mpu6050_set_power_itg(st, false);
1199         inv_mpu_core_disable_regulator(st);
1200         mutex_unlock(&st->lock);
1201
1202         return result;
1203 }
1204 #endif /* CONFIG_PM_SLEEP */
1205
1206 SIMPLE_DEV_PM_OPS(inv_mpu_pmops, inv_mpu_suspend, inv_mpu_resume);
1207 EXPORT_SYMBOL_GPL(inv_mpu_pmops);
1208
1209 MODULE_AUTHOR("Invensense Corporation");
1210 MODULE_DESCRIPTION("Invensense device MPU6050 driver");
1211 MODULE_LICENSE("GPL");