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