Merge tag 'armsoc-soc' of git://git.kernel.org/pub/scm/linux/kernel/git/soc/soc
[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                         *val2 = INV_MPU6050_TEMP_SCALE;
475
476                         return IIO_VAL_INT_PLUS_MICRO;
477                 default:
478                         return -EINVAL;
479                 }
480         case IIO_CHAN_INFO_OFFSET:
481                 switch (chan->type) {
482                 case IIO_TEMP:
483                         *val = INV_MPU6050_TEMP_OFFSET;
484
485                         return IIO_VAL_INT;
486                 default:
487                         return -EINVAL;
488                 }
489         case IIO_CHAN_INFO_CALIBBIAS:
490                 switch (chan->type) {
491                 case IIO_ANGL_VEL:
492                         mutex_lock(&st->lock);
493                         ret = inv_mpu6050_sensor_show(st, st->reg->gyro_offset,
494                                                 chan->channel2, val);
495                         mutex_unlock(&st->lock);
496                         return IIO_VAL_INT;
497                 case IIO_ACCEL:
498                         mutex_lock(&st->lock);
499                         ret = inv_mpu6050_sensor_show(st, st->reg->accl_offset,
500                                                 chan->channel2, val);
501                         mutex_unlock(&st->lock);
502                         return IIO_VAL_INT;
503
504                 default:
505                         return -EINVAL;
506                 }
507         default:
508                 return -EINVAL;
509         }
510 }
511
512 static int inv_mpu6050_write_gyro_scale(struct inv_mpu6050_state *st, int val)
513 {
514         int result, i;
515         u8 d;
516
517         for (i = 0; i < ARRAY_SIZE(gyro_scale_6050); ++i) {
518                 if (gyro_scale_6050[i] == val) {
519                         d = (i << INV_MPU6050_GYRO_CONFIG_FSR_SHIFT);
520                         result = regmap_write(st->map, st->reg->gyro_config, d);
521                         if (result)
522                                 return result;
523
524                         st->chip_config.fsr = i;
525                         return 0;
526                 }
527         }
528
529         return -EINVAL;
530 }
531
532 static int inv_write_raw_get_fmt(struct iio_dev *indio_dev,
533                                  struct iio_chan_spec const *chan, long mask)
534 {
535         switch (mask) {
536         case IIO_CHAN_INFO_SCALE:
537                 switch (chan->type) {
538                 case IIO_ANGL_VEL:
539                         return IIO_VAL_INT_PLUS_NANO;
540                 default:
541                         return IIO_VAL_INT_PLUS_MICRO;
542                 }
543         default:
544                 return IIO_VAL_INT_PLUS_MICRO;
545         }
546
547         return -EINVAL;
548 }
549
550 static int inv_mpu6050_write_accel_scale(struct inv_mpu6050_state *st, int val)
551 {
552         int result, i;
553         u8 d;
554
555         for (i = 0; i < ARRAY_SIZE(accel_scale); ++i) {
556                 if (accel_scale[i] == val) {
557                         d = (i << INV_MPU6050_ACCL_CONFIG_FSR_SHIFT);
558                         result = regmap_write(st->map, st->reg->accl_config, d);
559                         if (result)
560                                 return result;
561
562                         st->chip_config.accl_fs = i;
563                         return 0;
564                 }
565         }
566
567         return -EINVAL;
568 }
569
570 static int inv_mpu6050_write_raw(struct iio_dev *indio_dev,
571                                  struct iio_chan_spec const *chan,
572                                  int val, int val2, long mask)
573 {
574         struct inv_mpu6050_state  *st = iio_priv(indio_dev);
575         int result;
576
577         /*
578          * we should only update scale when the chip is disabled, i.e.
579          * not running
580          */
581         result = iio_device_claim_direct_mode(indio_dev);
582         if (result)
583                 return result;
584
585         mutex_lock(&st->lock);
586         result = inv_mpu6050_set_power_itg(st, true);
587         if (result)
588                 goto error_write_raw_unlock;
589
590         switch (mask) {
591         case IIO_CHAN_INFO_SCALE:
592                 switch (chan->type) {
593                 case IIO_ANGL_VEL:
594                         result = inv_mpu6050_write_gyro_scale(st, val2);
595                         break;
596                 case IIO_ACCEL:
597                         result = inv_mpu6050_write_accel_scale(st, val2);
598                         break;
599                 default:
600                         result = -EINVAL;
601                         break;
602                 }
603                 break;
604         case IIO_CHAN_INFO_CALIBBIAS:
605                 switch (chan->type) {
606                 case IIO_ANGL_VEL:
607                         result = inv_mpu6050_sensor_set(st,
608                                                         st->reg->gyro_offset,
609                                                         chan->channel2, val);
610                         break;
611                 case IIO_ACCEL:
612                         result = inv_mpu6050_sensor_set(st,
613                                                         st->reg->accl_offset,
614                                                         chan->channel2, val);
615                         break;
616                 default:
617                         result = -EINVAL;
618                         break;
619                 }
620                 break;
621         default:
622                 result = -EINVAL;
623                 break;
624         }
625
626         result |= inv_mpu6050_set_power_itg(st, false);
627 error_write_raw_unlock:
628         mutex_unlock(&st->lock);
629         iio_device_release_direct_mode(indio_dev);
630
631         return result;
632 }
633
634 /**
635  *  inv_mpu6050_set_lpf() - set low pass filer based on fifo rate.
636  *
637  *                  Based on the Nyquist principle, the sampling rate must
638  *                  exceed twice of the bandwidth of the signal, or there
639  *                  would be alising. This function basically search for the
640  *                  correct low pass parameters based on the fifo rate, e.g,
641  *                  sampling frequency.
642  *
643  *  lpf is set automatically when setting sampling rate to avoid any aliases.
644  */
645 static int inv_mpu6050_set_lpf(struct inv_mpu6050_state *st, int rate)
646 {
647         static const int hz[] = {188, 98, 42, 20, 10, 5};
648         static const int d[] = {
649                 INV_MPU6050_FILTER_188HZ, INV_MPU6050_FILTER_98HZ,
650                 INV_MPU6050_FILTER_42HZ, INV_MPU6050_FILTER_20HZ,
651                 INV_MPU6050_FILTER_10HZ, INV_MPU6050_FILTER_5HZ
652         };
653         int i, h, result;
654         u8 data;
655
656         h = (rate >> 1);
657         i = 0;
658         while ((h < hz[i]) && (i < ARRAY_SIZE(d) - 1))
659                 i++;
660         data = d[i];
661         result = inv_mpu6050_set_lpf_regs(st, data);
662         if (result)
663                 return result;
664         st->chip_config.lpf = data;
665
666         return 0;
667 }
668
669 /**
670  * inv_mpu6050_fifo_rate_store() - Set fifo rate.
671  */
672 static ssize_t
673 inv_mpu6050_fifo_rate_store(struct device *dev, struct device_attribute *attr,
674                             const char *buf, size_t count)
675 {
676         int fifo_rate;
677         u8 d;
678         int result;
679         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
680         struct inv_mpu6050_state *st = iio_priv(indio_dev);
681
682         if (kstrtoint(buf, 10, &fifo_rate))
683                 return -EINVAL;
684         if (fifo_rate < INV_MPU6050_MIN_FIFO_RATE ||
685             fifo_rate > INV_MPU6050_MAX_FIFO_RATE)
686                 return -EINVAL;
687
688         result = iio_device_claim_direct_mode(indio_dev);
689         if (result)
690                 return result;
691
692         /* compute the chip sample rate divider */
693         d = INV_MPU6050_FIFO_RATE_TO_DIVIDER(fifo_rate);
694         /* compute back the fifo rate to handle truncation cases */
695         fifo_rate = INV_MPU6050_DIVIDER_TO_FIFO_RATE(d);
696
697         mutex_lock(&st->lock);
698         if (d == st->chip_config.divider) {
699                 result = 0;
700                 goto fifo_rate_fail_unlock;
701         }
702         result = inv_mpu6050_set_power_itg(st, true);
703         if (result)
704                 goto fifo_rate_fail_unlock;
705
706         result = regmap_write(st->map, st->reg->sample_rate_div, d);
707         if (result)
708                 goto fifo_rate_fail_power_off;
709         st->chip_config.divider = d;
710
711         result = inv_mpu6050_set_lpf(st, fifo_rate);
712         if (result)
713                 goto fifo_rate_fail_power_off;
714
715 fifo_rate_fail_power_off:
716         result |= inv_mpu6050_set_power_itg(st, false);
717 fifo_rate_fail_unlock:
718         mutex_unlock(&st->lock);
719         iio_device_release_direct_mode(indio_dev);
720         if (result)
721                 return result;
722
723         return count;
724 }
725
726 /**
727  * inv_fifo_rate_show() - Get the current sampling rate.
728  */
729 static ssize_t
730 inv_fifo_rate_show(struct device *dev, struct device_attribute *attr,
731                    char *buf)
732 {
733         struct inv_mpu6050_state *st = iio_priv(dev_to_iio_dev(dev));
734         unsigned fifo_rate;
735
736         mutex_lock(&st->lock);
737         fifo_rate = INV_MPU6050_DIVIDER_TO_FIFO_RATE(st->chip_config.divider);
738         mutex_unlock(&st->lock);
739
740         return scnprintf(buf, PAGE_SIZE, "%u\n", fifo_rate);
741 }
742
743 /**
744  * inv_attr_show() - calling this function will show current
745  *                    parameters.
746  *
747  * Deprecated in favor of IIO mounting matrix API.
748  *
749  * See inv_get_mount_matrix()
750  */
751 static ssize_t inv_attr_show(struct device *dev, struct device_attribute *attr,
752                              char *buf)
753 {
754         struct inv_mpu6050_state *st = iio_priv(dev_to_iio_dev(dev));
755         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
756         s8 *m;
757
758         switch (this_attr->address) {
759         /*
760          * In MPU6050, the two matrix are the same because gyro and accel
761          * are integrated in one chip
762          */
763         case ATTR_GYRO_MATRIX:
764         case ATTR_ACCL_MATRIX:
765                 m = st->plat_data.orientation;
766
767                 return scnprintf(buf, PAGE_SIZE,
768                         "%d, %d, %d; %d, %d, %d; %d, %d, %d\n",
769                         m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8]);
770         default:
771                 return -EINVAL;
772         }
773 }
774
775 /**
776  * inv_mpu6050_validate_trigger() - validate_trigger callback for invensense
777  *                                  MPU6050 device.
778  * @indio_dev: The IIO device
779  * @trig: The new trigger
780  *
781  * Returns: 0 if the 'trig' matches the trigger registered by the MPU6050
782  * device, -EINVAL otherwise.
783  */
784 static int inv_mpu6050_validate_trigger(struct iio_dev *indio_dev,
785                                         struct iio_trigger *trig)
786 {
787         struct inv_mpu6050_state *st = iio_priv(indio_dev);
788
789         if (st->trig != trig)
790                 return -EINVAL;
791
792         return 0;
793 }
794
795 static const struct iio_mount_matrix *
796 inv_get_mount_matrix(const struct iio_dev *indio_dev,
797                      const struct iio_chan_spec *chan)
798 {
799         struct inv_mpu6050_state *data = iio_priv(indio_dev);
800
801         return &data->orientation;
802 }
803
804 static const struct iio_chan_spec_ext_info inv_ext_info[] = {
805         IIO_MOUNT_MATRIX(IIO_SHARED_BY_TYPE, inv_get_mount_matrix),
806         { }
807 };
808
809 #define INV_MPU6050_CHAN(_type, _channel2, _index)                    \
810         {                                                             \
811                 .type = _type,                                        \
812                 .modified = 1,                                        \
813                 .channel2 = _channel2,                                \
814                 .info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE), \
815                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |        \
816                                       BIT(IIO_CHAN_INFO_CALIBBIAS),   \
817                 .scan_index = _index,                                 \
818                 .scan_type = {                                        \
819                                 .sign = 's',                          \
820                                 .realbits = 16,                       \
821                                 .storagebits = 16,                    \
822                                 .shift = 0,                           \
823                                 .endianness = IIO_BE,                 \
824                              },                                       \
825                 .ext_info = inv_ext_info,                             \
826         }
827
828 static const struct iio_chan_spec inv_mpu_channels[] = {
829         IIO_CHAN_SOFT_TIMESTAMP(INV_MPU6050_SCAN_TIMESTAMP),
830         /*
831          * Note that temperature should only be via polled reading only,
832          * not the final scan elements output.
833          */
834         {
835                 .type = IIO_TEMP,
836                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW)
837                                 | BIT(IIO_CHAN_INFO_OFFSET)
838                                 | BIT(IIO_CHAN_INFO_SCALE),
839                 .scan_index = -1,
840         },
841         INV_MPU6050_CHAN(IIO_ANGL_VEL, IIO_MOD_X, INV_MPU6050_SCAN_GYRO_X),
842         INV_MPU6050_CHAN(IIO_ANGL_VEL, IIO_MOD_Y, INV_MPU6050_SCAN_GYRO_Y),
843         INV_MPU6050_CHAN(IIO_ANGL_VEL, IIO_MOD_Z, INV_MPU6050_SCAN_GYRO_Z),
844
845         INV_MPU6050_CHAN(IIO_ACCEL, IIO_MOD_X, INV_MPU6050_SCAN_ACCL_X),
846         INV_MPU6050_CHAN(IIO_ACCEL, IIO_MOD_Y, INV_MPU6050_SCAN_ACCL_Y),
847         INV_MPU6050_CHAN(IIO_ACCEL, IIO_MOD_Z, INV_MPU6050_SCAN_ACCL_Z),
848 };
849
850 /*
851  * The user can choose any frequency between INV_MPU6050_MIN_FIFO_RATE and
852  * INV_MPU6050_MAX_FIFO_RATE, but only these frequencies are matched by the
853  * low-pass filter. Specifically, each of these sampling rates are about twice
854  * the bandwidth of a corresponding low-pass filter, which should eliminate
855  * aliasing following the Nyquist principle. By picking a frequency different
856  * from these, the user risks aliasing effects.
857  */
858 static IIO_CONST_ATTR_SAMP_FREQ_AVAIL("10 20 50 100 200 500");
859 static IIO_CONST_ATTR(in_anglvel_scale_available,
860                                           "0.000133090 0.000266181 0.000532362 0.001064724");
861 static IIO_CONST_ATTR(in_accel_scale_available,
862                                           "0.000598 0.001196 0.002392 0.004785");
863 static IIO_DEV_ATTR_SAMP_FREQ(S_IRUGO | S_IWUSR, inv_fifo_rate_show,
864         inv_mpu6050_fifo_rate_store);
865
866 /* Deprecated: kept for userspace backward compatibility. */
867 static IIO_DEVICE_ATTR(in_gyro_matrix, S_IRUGO, inv_attr_show, NULL,
868         ATTR_GYRO_MATRIX);
869 static IIO_DEVICE_ATTR(in_accel_matrix, S_IRUGO, inv_attr_show, NULL,
870         ATTR_ACCL_MATRIX);
871
872 static struct attribute *inv_attributes[] = {
873         &iio_dev_attr_in_gyro_matrix.dev_attr.attr,  /* deprecated */
874         &iio_dev_attr_in_accel_matrix.dev_attr.attr, /* deprecated */
875         &iio_dev_attr_sampling_frequency.dev_attr.attr,
876         &iio_const_attr_sampling_frequency_available.dev_attr.attr,
877         &iio_const_attr_in_accel_scale_available.dev_attr.attr,
878         &iio_const_attr_in_anglvel_scale_available.dev_attr.attr,
879         NULL,
880 };
881
882 static const struct attribute_group inv_attribute_group = {
883         .attrs = inv_attributes
884 };
885
886 static const struct iio_info mpu_info = {
887         .read_raw = &inv_mpu6050_read_raw,
888         .write_raw = &inv_mpu6050_write_raw,
889         .write_raw_get_fmt = &inv_write_raw_get_fmt,
890         .attrs = &inv_attribute_group,
891         .validate_trigger = inv_mpu6050_validate_trigger,
892 };
893
894 /**
895  *  inv_check_and_setup_chip() - check and setup chip.
896  */
897 static int inv_check_and_setup_chip(struct inv_mpu6050_state *st)
898 {
899         int result;
900         unsigned int regval;
901         int i;
902
903         st->hw  = &hw_info[st->chip_type];
904         st->reg = hw_info[st->chip_type].reg;
905
906         /* check chip self-identification */
907         result = regmap_read(st->map, INV_MPU6050_REG_WHOAMI, &regval);
908         if (result)
909                 return result;
910         if (regval != st->hw->whoami) {
911                 /* check whoami against all possible values */
912                 for (i = 0; i < INV_NUM_PARTS; ++i) {
913                         if (regval == hw_info[i].whoami) {
914                                 dev_warn(regmap_get_device(st->map),
915                                         "whoami mismatch got %#02x (%s)"
916                                         "expected %#02hhx (%s)\n",
917                                         regval, hw_info[i].name,
918                                         st->hw->whoami, st->hw->name);
919                                 break;
920                         }
921                 }
922                 if (i >= INV_NUM_PARTS) {
923                         dev_err(regmap_get_device(st->map),
924                                 "invalid whoami %#02x expected %#02hhx (%s)\n",
925                                 regval, st->hw->whoami, st->hw->name);
926                         return -ENODEV;
927                 }
928         }
929
930         /* reset to make sure previous state are not there */
931         result = regmap_write(st->map, st->reg->pwr_mgmt_1,
932                               INV_MPU6050_BIT_H_RESET);
933         if (result)
934                 return result;
935         msleep(INV_MPU6050_POWER_UP_TIME);
936
937         /*
938          * Turn power on. After reset, the sleep bit could be on
939          * or off depending on the OTP settings. Turning power on
940          * make it in a definite state as well as making the hardware
941          * state align with the software state
942          */
943         result = inv_mpu6050_set_power_itg(st, true);
944         if (result)
945                 return result;
946
947         result = inv_mpu6050_switch_engine(st, false,
948                                            INV_MPU6050_BIT_PWR_ACCL_STBY);
949         if (result)
950                 goto error_power_off;
951         result = inv_mpu6050_switch_engine(st, false,
952                                            INV_MPU6050_BIT_PWR_GYRO_STBY);
953         if (result)
954                 goto error_power_off;
955
956         return inv_mpu6050_set_power_itg(st, false);
957
958 error_power_off:
959         inv_mpu6050_set_power_itg(st, false);
960         return result;
961 }
962
963 static int inv_mpu_core_enable_regulator(struct inv_mpu6050_state *st)
964 {
965         int result;
966
967         result = regulator_enable(st->vddio_supply);
968         if (result) {
969                 dev_err(regmap_get_device(st->map),
970                         "Failed to enable regulator: %d\n", result);
971         } else {
972                 /* Give the device a little bit of time to start up. */
973                 usleep_range(35000, 70000);
974         }
975
976         return result;
977 }
978
979 static int inv_mpu_core_disable_regulator(struct inv_mpu6050_state *st)
980 {
981         int result;
982
983         result = regulator_disable(st->vddio_supply);
984         if (result)
985                 dev_err(regmap_get_device(st->map),
986                         "Failed to disable regulator: %d\n", result);
987
988         return result;
989 }
990
991 static void inv_mpu_core_disable_regulator_action(void *_data)
992 {
993         inv_mpu_core_disable_regulator(_data);
994 }
995
996 int inv_mpu_core_probe(struct regmap *regmap, int irq, const char *name,
997                 int (*inv_mpu_bus_setup)(struct iio_dev *), int chip_type)
998 {
999         struct inv_mpu6050_state *st;
1000         struct iio_dev *indio_dev;
1001         struct inv_mpu6050_platform_data *pdata;
1002         struct device *dev = regmap_get_device(regmap);
1003         int result;
1004         struct irq_data *desc;
1005         int irq_type;
1006
1007         indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
1008         if (!indio_dev)
1009                 return -ENOMEM;
1010
1011         BUILD_BUG_ON(ARRAY_SIZE(hw_info) != INV_NUM_PARTS);
1012         if (chip_type < 0 || chip_type >= INV_NUM_PARTS) {
1013                 dev_err(dev, "Bad invensense chip_type=%d name=%s\n",
1014                                 chip_type, name);
1015                 return -ENODEV;
1016         }
1017         st = iio_priv(indio_dev);
1018         mutex_init(&st->lock);
1019         st->chip_type = chip_type;
1020         st->powerup_count = 0;
1021         st->irq = irq;
1022         st->map = regmap;
1023
1024         pdata = dev_get_platdata(dev);
1025         if (!pdata) {
1026                 result = iio_read_mount_matrix(dev, "mount-matrix",
1027                                                &st->orientation);
1028                 if (result) {
1029                         dev_err(dev, "Failed to retrieve mounting matrix %d\n",
1030                                 result);
1031                         return result;
1032                 }
1033         } else {
1034                 st->plat_data = *pdata;
1035         }
1036
1037         desc = irq_get_irq_data(irq);
1038         if (!desc) {
1039                 dev_err(dev, "Could not find IRQ %d\n", irq);
1040                 return -EINVAL;
1041         }
1042
1043         irq_type = irqd_get_trigger_type(desc);
1044         if (!irq_type)
1045                 irq_type = IRQF_TRIGGER_RISING;
1046         if (irq_type == IRQF_TRIGGER_RISING)
1047                 st->irq_mask = INV_MPU6050_ACTIVE_HIGH;
1048         else if (irq_type == IRQF_TRIGGER_FALLING)
1049                 st->irq_mask = INV_MPU6050_ACTIVE_LOW;
1050         else if (irq_type == IRQF_TRIGGER_HIGH)
1051                 st->irq_mask = INV_MPU6050_ACTIVE_HIGH |
1052                         INV_MPU6050_LATCH_INT_EN;
1053         else if (irq_type == IRQF_TRIGGER_LOW)
1054                 st->irq_mask = INV_MPU6050_ACTIVE_LOW |
1055                         INV_MPU6050_LATCH_INT_EN;
1056         else {
1057                 dev_err(dev, "Invalid interrupt type 0x%x specified\n",
1058                         irq_type);
1059                 return -EINVAL;
1060         }
1061
1062         st->vddio_supply = devm_regulator_get(dev, "vddio");
1063         if (IS_ERR(st->vddio_supply)) {
1064                 if (PTR_ERR(st->vddio_supply) != -EPROBE_DEFER)
1065                         dev_err(dev, "Failed to get vddio regulator %d\n",
1066                                 (int)PTR_ERR(st->vddio_supply));
1067
1068                 return PTR_ERR(st->vddio_supply);
1069         }
1070
1071         result = inv_mpu_core_enable_regulator(st);
1072         if (result)
1073                 return result;
1074
1075         result = devm_add_action(dev, inv_mpu_core_disable_regulator_action,
1076                                  st);
1077         if (result) {
1078                 inv_mpu_core_disable_regulator_action(st);
1079                 dev_err(dev, "Failed to setup regulator cleanup action %d\n",
1080                         result);
1081                 return result;
1082         }
1083
1084         /* power is turned on inside check chip type*/
1085         result = inv_check_and_setup_chip(st);
1086         if (result)
1087                 return result;
1088
1089         result = inv_mpu6050_init_config(indio_dev);
1090         if (result) {
1091                 dev_err(dev, "Could not initialize device.\n");
1092                 return result;
1093         }
1094
1095         if (inv_mpu_bus_setup)
1096                 inv_mpu_bus_setup(indio_dev);
1097
1098         dev_set_drvdata(dev, indio_dev);
1099         indio_dev->dev.parent = dev;
1100         /* name will be NULL when enumerated via ACPI */
1101         if (name)
1102                 indio_dev->name = name;
1103         else
1104                 indio_dev->name = dev_name(dev);
1105         indio_dev->channels = inv_mpu_channels;
1106         indio_dev->num_channels = ARRAY_SIZE(inv_mpu_channels);
1107
1108         indio_dev->info = &mpu_info;
1109         indio_dev->modes = INDIO_BUFFER_TRIGGERED;
1110
1111         result = devm_iio_triggered_buffer_setup(dev, indio_dev,
1112                                                  iio_pollfunc_store_time,
1113                                                  inv_mpu6050_read_fifo,
1114                                                  NULL);
1115         if (result) {
1116                 dev_err(dev, "configure buffer fail %d\n", result);
1117                 return result;
1118         }
1119         result = inv_mpu6050_probe_trigger(indio_dev, irq_type);
1120         if (result) {
1121                 dev_err(dev, "trigger probe fail %d\n", result);
1122                 return result;
1123         }
1124
1125         result = devm_iio_device_register(dev, indio_dev);
1126         if (result) {
1127                 dev_err(dev, "IIO register fail %d\n", result);
1128                 return result;
1129         }
1130
1131         return 0;
1132 }
1133 EXPORT_SYMBOL_GPL(inv_mpu_core_probe);
1134
1135 #ifdef CONFIG_PM_SLEEP
1136
1137 static int inv_mpu_resume(struct device *dev)
1138 {
1139         struct inv_mpu6050_state *st = iio_priv(dev_get_drvdata(dev));
1140         int result;
1141
1142         mutex_lock(&st->lock);
1143         result = inv_mpu_core_enable_regulator(st);
1144         if (result)
1145                 goto out_unlock;
1146
1147         result = inv_mpu6050_set_power_itg(st, true);
1148 out_unlock:
1149         mutex_unlock(&st->lock);
1150
1151         return result;
1152 }
1153
1154 static int inv_mpu_suspend(struct device *dev)
1155 {
1156         struct inv_mpu6050_state *st = iio_priv(dev_get_drvdata(dev));
1157         int result;
1158
1159         mutex_lock(&st->lock);
1160         result = inv_mpu6050_set_power_itg(st, false);
1161         inv_mpu_core_disable_regulator(st);
1162         mutex_unlock(&st->lock);
1163
1164         return result;
1165 }
1166 #endif /* CONFIG_PM_SLEEP */
1167
1168 SIMPLE_DEV_PM_OPS(inv_mpu_pmops, inv_mpu_suspend, inv_mpu_resume);
1169 EXPORT_SYMBOL_GPL(inv_mpu_pmops);
1170
1171 MODULE_AUTHOR("Invensense Corporation");
1172 MODULE_DESCRIPTION("Invensense device MPU6050 driver");
1173 MODULE_LICENSE("GPL");