xref: /linux/drivers/iio/accel/msa311.c (revision 889600e21e3be388a6817c2a0dac0411df860751)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * MEMSensing digital 3-Axis accelerometer
4  *
5  * MSA311 is a tri-axial, low-g accelerometer with I2C digital output for
6  * sensitivity consumer applications. It has dynamic user-selectable full
7  * scales range of +-2g/+-4g/+-8g/+-16g and allows acceleration measurements
8  * with output data rates from 1Hz to 1000Hz.
9  *
10  * MSA311 is available in an ultra small (2mm x 2mm, height 0.95mm) LGA package
11  * and is guaranteed to operate over -40C to +85C.
12  *
13  * This driver supports following MSA311 features:
14  *     - IIO interface
15  *     - Different power modes: NORMAL, SUSPEND
16  *     - ODR (Output Data Rate) selection
17  *     - Scale selection
18  *     - IIO triggered buffer
19  *     - NEW_DATA interrupt + trigger
20  *
21  * Below features to be done:
22  *     - Motion Events: ACTIVE, TAP, ORIENT, FREEFALL
23  *     - Low Power mode
24  *
25  * Copyright (c) 2022, SberDevices. All Rights Reserved.
26  *
27  * Author: Dmitry Rokosov <ddrokosov@sberdevices.ru>
28  */
29 
30 #include <linux/i2c.h>
31 #include <linux/module.h>
32 #include <linux/pm.h>
33 #include <linux/pm_runtime.h>
34 #include <linux/regmap.h>
35 #include <linux/string_choices.h>
36 #include <linux/types.h>
37 #include <linux/units.h>
38 
39 #include <linux/iio/buffer.h>
40 #include <linux/iio/iio.h>
41 #include <linux/iio/sysfs.h>
42 #include <linux/iio/trigger.h>
43 #include <linux/iio/trigger_consumer.h>
44 #include <linux/iio/triggered_buffer.h>
45 
46 #define MSA311_SOFT_RESET_REG     0x00
47 #define MSA311_PARTID_REG         0x01
48 #define MSA311_ACC_X_REG          0x02
49 #define MSA311_ACC_Y_REG          0x04
50 #define MSA311_ACC_Z_REG          0x06
51 #define MSA311_MOTION_INT_REG     0x09
52 #define MSA311_DATA_INT_REG       0x0A
53 #define MSA311_TAP_ACTIVE_STS_REG 0x0B
54 #define MSA311_ORIENT_STS_REG     0x0C
55 #define MSA311_RANGE_REG          0x0F
56 #define MSA311_ODR_REG            0x10
57 #define MSA311_PWR_MODE_REG       0x11
58 #define MSA311_SWAP_POLARITY_REG  0x12
59 #define MSA311_INT_SET_0_REG      0x16
60 #define MSA311_INT_SET_1_REG      0x17
61 #define MSA311_INT_MAP_0_REG      0x19
62 #define MSA311_INT_MAP_1_REG      0x1A
63 #define MSA311_INT_CONFIG_REG     0x20
64 #define MSA311_INT_LATCH_REG      0x21
65 #define MSA311_FREEFALL_DUR_REG   0x22
66 #define MSA311_FREEFALL_TH_REG    0x23
67 #define MSA311_FREEFALL_HY_REG    0x24
68 #define MSA311_ACTIVE_DUR_REG     0x27
69 #define MSA311_ACTIVE_TH_REG      0x28
70 #define MSA311_TAP_DUR_REG        0x2A
71 #define MSA311_TAP_TH_REG         0x2B
72 #define MSA311_ORIENT_HY_REG      0x2C
73 #define MSA311_Z_BLOCK_REG        0x2D
74 #define MSA311_OFFSET_X_REG       0x38
75 #define MSA311_OFFSET_Y_REG       0x39
76 #define MSA311_OFFSET_Z_REG       0x3A
77 
78 enum msa311_fields {
79 	/* Soft_Reset */
80 	F_SOFT_RESET_I2C, F_SOFT_RESET_SPI,
81 	/* Motion_Interrupt */
82 	F_ORIENT_INT, F_S_TAP_INT, F_D_TAP_INT, F_ACTIVE_INT, F_FREEFALL_INT,
83 	/* Data_Interrupt */
84 	F_NEW_DATA_INT,
85 	/* Tap_Active_Status */
86 	F_TAP_SIGN, F_TAP_FIRST_X, F_TAP_FIRST_Y, F_TAP_FIRST_Z, F_ACTV_SIGN,
87 	F_ACTV_FIRST_X, F_ACTV_FIRST_Y, F_ACTV_FIRST_Z,
88 	/* Orientation_Status */
89 	F_ORIENT_Z, F_ORIENT_X_Y,
90 	/* Range */
91 	F_FS,
92 	/* ODR */
93 	F_X_AXIS_DIS, F_Y_AXIS_DIS, F_Z_AXIS_DIS, F_ODR,
94 	/* Power Mode/Bandwidth */
95 	F_PWR_MODE, F_LOW_POWER_BW,
96 	/* Swap_Polarity */
97 	F_X_POLARITY, F_Y_POLARITY, F_Z_POLARITY, F_X_Y_SWAP,
98 	/* Int_Set_0 */
99 	F_ORIENT_INT_EN, F_S_TAP_INT_EN, F_D_TAP_INT_EN, F_ACTIVE_INT_EN_Z,
100 	F_ACTIVE_INT_EN_Y, F_ACTIVE_INT_EN_X,
101 	/* Int_Set_1 */
102 	F_NEW_DATA_INT_EN, F_FREEFALL_INT_EN,
103 	/* Int_Map_0 */
104 	F_INT1_ORIENT, F_INT1_S_TAP, F_INT1_D_TAP, F_INT1_ACTIVE,
105 	F_INT1_FREEFALL,
106 	/* Int_Map_1 */
107 	F_INT1_NEW_DATA,
108 	/* Int_Config */
109 	F_INT1_OD, F_INT1_LVL,
110 	/* Int_Latch */
111 	F_RESET_INT, F_LATCH_INT,
112 	/* Freefall_Hy */
113 	F_FREEFALL_MODE, F_FREEFALL_HY,
114 	/* Active_Dur */
115 	F_ACTIVE_DUR,
116 	/* Tap_Dur */
117 	F_TAP_QUIET, F_TAP_SHOCK, F_TAP_DUR,
118 	/* Tap_Th */
119 	F_TAP_TH,
120 	/* Orient_Hy */
121 	F_ORIENT_HYST, F_ORIENT_BLOCKING, F_ORIENT_MODE,
122 	/* Z_Block */
123 	F_Z_BLOCKING,
124 	/* End of register map */
125 	F_MAX_FIELDS,
126 };
127 
128 static const struct reg_field msa311_reg_fields[] = {
129 	/* Soft_Reset */
130 	[F_SOFT_RESET_I2C] = REG_FIELD(MSA311_SOFT_RESET_REG, 2, 2),
131 	[F_SOFT_RESET_SPI] = REG_FIELD(MSA311_SOFT_RESET_REG, 5, 5),
132 	/* Motion_Interrupt */
133 	[F_ORIENT_INT] = REG_FIELD(MSA311_MOTION_INT_REG, 6, 6),
134 	[F_S_TAP_INT] = REG_FIELD(MSA311_MOTION_INT_REG, 5, 5),
135 	[F_D_TAP_INT] = REG_FIELD(MSA311_MOTION_INT_REG, 4, 4),
136 	[F_ACTIVE_INT] = REG_FIELD(MSA311_MOTION_INT_REG, 2, 2),
137 	[F_FREEFALL_INT] = REG_FIELD(MSA311_MOTION_INT_REG, 0, 0),
138 	/* Data_Interrupt */
139 	[F_NEW_DATA_INT] = REG_FIELD(MSA311_DATA_INT_REG, 0, 0),
140 	/* Tap_Active_Status */
141 	[F_TAP_SIGN] = REG_FIELD(MSA311_TAP_ACTIVE_STS_REG, 7, 7),
142 	[F_TAP_FIRST_X] = REG_FIELD(MSA311_TAP_ACTIVE_STS_REG, 6, 6),
143 	[F_TAP_FIRST_Y] = REG_FIELD(MSA311_TAP_ACTIVE_STS_REG, 5, 5),
144 	[F_TAP_FIRST_Z] = REG_FIELD(MSA311_TAP_ACTIVE_STS_REG, 4, 4),
145 	[F_ACTV_SIGN] = REG_FIELD(MSA311_TAP_ACTIVE_STS_REG, 3, 3),
146 	[F_ACTV_FIRST_X] = REG_FIELD(MSA311_TAP_ACTIVE_STS_REG, 2, 2),
147 	[F_ACTV_FIRST_Y] = REG_FIELD(MSA311_TAP_ACTIVE_STS_REG, 1, 1),
148 	[F_ACTV_FIRST_Z] = REG_FIELD(MSA311_TAP_ACTIVE_STS_REG, 0, 0),
149 	/* Orientation_Status */
150 	[F_ORIENT_Z] = REG_FIELD(MSA311_ORIENT_STS_REG, 6, 6),
151 	[F_ORIENT_X_Y] = REG_FIELD(MSA311_ORIENT_STS_REG, 4, 5),
152 	/* Range */
153 	[F_FS] = REG_FIELD(MSA311_RANGE_REG, 0, 1),
154 	/* ODR */
155 	[F_X_AXIS_DIS] = REG_FIELD(MSA311_ODR_REG, 7, 7),
156 	[F_Y_AXIS_DIS] = REG_FIELD(MSA311_ODR_REG, 6, 6),
157 	[F_Z_AXIS_DIS] = REG_FIELD(MSA311_ODR_REG, 5, 5),
158 	[F_ODR] = REG_FIELD(MSA311_ODR_REG, 0, 3),
159 	/* Power Mode/Bandwidth */
160 	[F_PWR_MODE] = REG_FIELD(MSA311_PWR_MODE_REG, 6, 7),
161 	[F_LOW_POWER_BW] = REG_FIELD(MSA311_PWR_MODE_REG, 1, 4),
162 	/* Swap_Polarity */
163 	[F_X_POLARITY] = REG_FIELD(MSA311_SWAP_POLARITY_REG, 3, 3),
164 	[F_Y_POLARITY] = REG_FIELD(MSA311_SWAP_POLARITY_REG, 2, 2),
165 	[F_Z_POLARITY] = REG_FIELD(MSA311_SWAP_POLARITY_REG, 1, 1),
166 	[F_X_Y_SWAP] = REG_FIELD(MSA311_SWAP_POLARITY_REG, 0, 0),
167 	/* Int_Set_0 */
168 	[F_ORIENT_INT_EN] = REG_FIELD(MSA311_INT_SET_0_REG, 6, 6),
169 	[F_S_TAP_INT_EN] = REG_FIELD(MSA311_INT_SET_0_REG, 5, 5),
170 	[F_D_TAP_INT_EN] = REG_FIELD(MSA311_INT_SET_0_REG, 4, 4),
171 	[F_ACTIVE_INT_EN_Z] = REG_FIELD(MSA311_INT_SET_0_REG, 2, 2),
172 	[F_ACTIVE_INT_EN_Y] = REG_FIELD(MSA311_INT_SET_0_REG, 1, 1),
173 	[F_ACTIVE_INT_EN_X] = REG_FIELD(MSA311_INT_SET_0_REG, 0, 0),
174 	/* Int_Set_1 */
175 	[F_NEW_DATA_INT_EN] = REG_FIELD(MSA311_INT_SET_1_REG, 4, 4),
176 	[F_FREEFALL_INT_EN] = REG_FIELD(MSA311_INT_SET_1_REG, 3, 3),
177 	/* Int_Map_0 */
178 	[F_INT1_ORIENT] = REG_FIELD(MSA311_INT_MAP_0_REG, 6, 6),
179 	[F_INT1_S_TAP] = REG_FIELD(MSA311_INT_MAP_0_REG, 5, 5),
180 	[F_INT1_D_TAP] = REG_FIELD(MSA311_INT_MAP_0_REG, 4, 4),
181 	[F_INT1_ACTIVE] = REG_FIELD(MSA311_INT_MAP_0_REG, 2, 2),
182 	[F_INT1_FREEFALL] = REG_FIELD(MSA311_INT_MAP_0_REG, 0, 0),
183 	/* Int_Map_1 */
184 	[F_INT1_NEW_DATA] = REG_FIELD(MSA311_INT_MAP_1_REG, 0, 0),
185 	/* Int_Config */
186 	[F_INT1_OD] = REG_FIELD(MSA311_INT_CONFIG_REG, 1, 1),
187 	[F_INT1_LVL] = REG_FIELD(MSA311_INT_CONFIG_REG, 0, 0),
188 	/* Int_Latch */
189 	[F_RESET_INT] = REG_FIELD(MSA311_INT_LATCH_REG, 7, 7),
190 	[F_LATCH_INT] = REG_FIELD(MSA311_INT_LATCH_REG, 0, 3),
191 	/* Freefall_Hy */
192 	[F_FREEFALL_MODE] = REG_FIELD(MSA311_FREEFALL_HY_REG, 2, 2),
193 	[F_FREEFALL_HY] = REG_FIELD(MSA311_FREEFALL_HY_REG, 0, 1),
194 	/* Active_Dur */
195 	[F_ACTIVE_DUR] = REG_FIELD(MSA311_ACTIVE_DUR_REG, 0, 1),
196 	/* Tap_Dur */
197 	[F_TAP_QUIET] = REG_FIELD(MSA311_TAP_DUR_REG, 7, 7),
198 	[F_TAP_SHOCK] = REG_FIELD(MSA311_TAP_DUR_REG, 6, 6),
199 	[F_TAP_DUR] = REG_FIELD(MSA311_TAP_DUR_REG, 0, 2),
200 	/* Tap_Th */
201 	[F_TAP_TH] = REG_FIELD(MSA311_TAP_TH_REG, 0, 4),
202 	/* Orient_Hy */
203 	[F_ORIENT_HYST] = REG_FIELD(MSA311_ORIENT_HY_REG, 4, 6),
204 	[F_ORIENT_BLOCKING] = REG_FIELD(MSA311_ORIENT_HY_REG, 2, 3),
205 	[F_ORIENT_MODE] = REG_FIELD(MSA311_ORIENT_HY_REG, 0, 1),
206 	/* Z_Block */
207 	[F_Z_BLOCKING] = REG_FIELD(MSA311_Z_BLOCK_REG, 0, 3),
208 };
209 
210 #define MSA311_WHO_AM_I 0x13
211 
212 /*
213  * Possible Full Scale ranges
214  *
215  * Axis data is 12-bit signed value, so
216  *
217  * fs0 = (2 + 2) * 9.81 / (2^11) = 0.009580
218  * fs1 = (4 + 4) * 9.81 / (2^11) = 0.019160
219  * fs2 = (8 + 8) * 9.81 / (2^11) = 0.038320
220  * fs3 = (16 + 16) * 9.81 / (2^11) = 0.076641
221  */
222 enum {
223 	MSA311_FS_2G,
224 	MSA311_FS_4G,
225 	MSA311_FS_8G,
226 	MSA311_FS_16G,
227 };
228 
229 struct iio_decimal_fract {
230 	int integral;
231 	int microfract;
232 };
233 
234 static const struct iio_decimal_fract msa311_fs_table[] = {
235 	{0, 9580}, {0, 19160}, {0, 38320}, {0, 76641},
236 };
237 
238 /* Possible Output Data Rate values */
239 enum {
240 	MSA311_ODR_1_HZ,
241 	MSA311_ODR_1_95_HZ,
242 	MSA311_ODR_3_9_HZ,
243 	MSA311_ODR_7_81_HZ,
244 	MSA311_ODR_15_63_HZ,
245 	MSA311_ODR_31_25_HZ,
246 	MSA311_ODR_62_5_HZ,
247 	MSA311_ODR_125_HZ,
248 	MSA311_ODR_250_HZ,
249 	MSA311_ODR_500_HZ,
250 	MSA311_ODR_1000_HZ,
251 };
252 
253 static const struct iio_decimal_fract msa311_odr_table[] = {
254 	{1, 0}, {1, 950000}, {3, 900000}, {7, 810000}, {15, 630000},
255 	{31, 250000}, {62, 500000}, {125, 0}, {250, 0}, {500, 0}, {1000, 0},
256 };
257 
258 /* All supported power modes */
259 #define MSA311_PWR_MODE_NORMAL  0b00
260 #define MSA311_PWR_MODE_LOW     0b01
261 #define MSA311_PWR_MODE_UNKNOWN 0b10
262 #define MSA311_PWR_MODE_SUSPEND 0b11
263 static const char * const msa311_pwr_modes[] = {
264 	[MSA311_PWR_MODE_NORMAL] = "normal",
265 	[MSA311_PWR_MODE_LOW] = "low",
266 	[MSA311_PWR_MODE_UNKNOWN] = "unknown",
267 	[MSA311_PWR_MODE_SUSPEND] = "suspend",
268 };
269 
270 /* Autosuspend delay */
271 #define MSA311_PWR_SLEEP_DELAY_MS 2000
272 
273 /* Possible INT1 types and levels */
274 enum {
275 	MSA311_INT1_OD_PUSH_PULL,
276 	MSA311_INT1_OD_OPEN_DRAIN,
277 };
278 
279 enum {
280 	MSA311_INT1_LVL_LOW,
281 	MSA311_INT1_LVL_HIGH,
282 };
283 
284 /* Latch INT modes */
285 #define MSA311_LATCH_INT_NOT_LATCHED 0b0000
286 #define MSA311_LATCH_INT_250MS       0b0001
287 #define MSA311_LATCH_INT_500MS       0b0010
288 #define MSA311_LATCH_INT_1S          0b0011
289 #define MSA311_LATCH_INT_2S          0b0100
290 #define MSA311_LATCH_INT_4S          0b0101
291 #define MSA311_LATCH_INT_8S          0b0110
292 #define MSA311_LATCH_INT_1MS         0b1010
293 #define MSA311_LATCH_INT_2MS         0b1011
294 #define MSA311_LATCH_INT_25MS        0b1100
295 #define MSA311_LATCH_INT_50MS        0b1101
296 #define MSA311_LATCH_INT_100MS       0b1110
297 #define MSA311_LATCH_INT_LATCHED     0b0111
298 
299 static const struct regmap_range msa311_readonly_registers[] = {
300 	regmap_reg_range(MSA311_PARTID_REG, MSA311_ORIENT_STS_REG),
301 };
302 
303 static const struct regmap_access_table msa311_writeable_table = {
304 	.no_ranges = msa311_readonly_registers,
305 	.n_no_ranges = ARRAY_SIZE(msa311_readonly_registers),
306 };
307 
308 static const struct regmap_range msa311_writeonly_registers[] = {
309 	regmap_reg_range(MSA311_SOFT_RESET_REG, MSA311_SOFT_RESET_REG),
310 };
311 
312 static const struct regmap_access_table msa311_readable_table = {
313 	.no_ranges = msa311_writeonly_registers,
314 	.n_no_ranges = ARRAY_SIZE(msa311_writeonly_registers),
315 };
316 
317 static const struct regmap_range msa311_volatile_registers[] = {
318 	regmap_reg_range(MSA311_ACC_X_REG, MSA311_ORIENT_STS_REG),
319 };
320 
321 static const struct regmap_access_table msa311_volatile_table = {
322 	.yes_ranges = msa311_volatile_registers,
323 	.n_yes_ranges = ARRAY_SIZE(msa311_volatile_registers),
324 };
325 
326 static const struct regmap_config msa311_regmap_config = {
327 	.name = "msa311",
328 	.reg_bits = 8,
329 	.val_bits = 8,
330 	.max_register = MSA311_OFFSET_Z_REG,
331 	.wr_table = &msa311_writeable_table,
332 	.rd_table = &msa311_readable_table,
333 	.volatile_table = &msa311_volatile_table,
334 	.cache_type = REGCACHE_MAPLE,
335 };
336 
337 #define MSA311_GENMASK(field) ({                \
338 	typeof(&(msa311_reg_fields)[0]) _field; \
339 	_field = &msa311_reg_fields[(field)];   \
340 	GENMASK(_field->msb, _field->lsb);      \
341 })
342 
343 /**
344  * struct msa311_priv - MSA311 internal private state
345  * @regs: Underlying I2C bus adapter used to abstract slave
346  *        register accesses
347  * @fields: Abstract objects for each registers fields access
348  * @dev: Device handler associated with appropriate bus client
349  * @lock: Protects msa311 device state between setup and data access routines
350  *        (power transitions, samp_freq/scale tune, retrieving axes data, etc)
351  * @chip_name: Chip name in the format "msa311-%02x" % partid
352  * @new_data_trig: Optional NEW_DATA interrupt driven trigger used
353  *                 to notify external consumers a new sample is ready
354  */
355 struct msa311_priv {
356 	struct regmap *regs;
357 	struct regmap_field *fields[F_MAX_FIELDS];
358 
359 	struct device *dev;
360 	struct mutex lock;
361 	char *chip_name;
362 
363 	struct iio_trigger *new_data_trig;
364 };
365 
366 enum msa311_si {
367 	MSA311_SI_X,
368 	MSA311_SI_Y,
369 	MSA311_SI_Z,
370 	MSA311_SI_TIMESTAMP,
371 };
372 
373 #define MSA311_ACCEL_CHANNEL(axis) {                                        \
374 	.type = IIO_ACCEL,                                                  \
375 	.modified = 1,                                                      \
376 	.channel2 = IIO_MOD_##axis,                                         \
377 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),                       \
378 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |              \
379 				    BIT(IIO_CHAN_INFO_SAMP_FREQ),           \
380 	.info_mask_shared_by_type_available = BIT(IIO_CHAN_INFO_SCALE) |    \
381 					      BIT(IIO_CHAN_INFO_SAMP_FREQ), \
382 	.scan_index = MSA311_SI_##axis,                                     \
383 	.scan_type = {                                                      \
384 		.sign = 's',                                                \
385 		.realbits = 12,                                             \
386 		.storagebits = 16,                                          \
387 		.shift = 4,                                                 \
388 		.endianness = IIO_LE,                                       \
389 	},                                                                  \
390 	.datasheet_name = "ACC_"#axis,                                      \
391 }
392 
393 static const struct iio_chan_spec msa311_channels[] = {
394 	MSA311_ACCEL_CHANNEL(X),
395 	MSA311_ACCEL_CHANNEL(Y),
396 	MSA311_ACCEL_CHANNEL(Z),
397 	IIO_CHAN_SOFT_TIMESTAMP(MSA311_SI_TIMESTAMP),
398 };
399 
400 /**
401  * msa311_get_odr() - Read Output Data Rate (ODR) value from MSA311 accel
402  * @msa311: MSA311 internal private state
403  * @odr: output ODR value
404  *
405  * This function should be called under msa311->lock.
406  *
407  * Return: 0 on success, -ERRNO in other failures
408  */
msa311_get_odr(struct msa311_priv * msa311,unsigned int * odr)409 static int msa311_get_odr(struct msa311_priv *msa311, unsigned int *odr)
410 {
411 	int err;
412 
413 	err = regmap_field_read(msa311->fields[F_ODR], odr);
414 	if (err)
415 		return err;
416 
417 	/*
418 	 * Filter the same 1000Hz ODR register values based on datasheet info.
419 	 * ODR can be equal to 1010-1111 for 1000Hz, but function returns 1010
420 	 * all the time.
421 	 */
422 	if (*odr > MSA311_ODR_1000_HZ)
423 		*odr = MSA311_ODR_1000_HZ;
424 
425 	return 0;
426 }
427 
428 /**
429  * msa311_set_odr() - Setup Output Data Rate (ODR) value for MSA311 accel
430  * @msa311: MSA311 internal private state
431  * @odr: requested ODR value
432  *
433  * This function should be called under msa311->lock. Possible ODR values:
434  *     - 1Hz (not available in normal mode)
435  *     - 1.95Hz (not available in normal mode)
436  *     - 3.9Hz
437  *     - 7.81Hz
438  *     - 15.63Hz
439  *     - 31.25Hz
440  *     - 62.5Hz
441  *     - 125Hz
442  *     - 250Hz
443  *     - 500Hz
444  *     - 1000Hz
445  *
446  * Return: 0 on success, -EINVAL for bad ODR value in the certain power mode,
447  *         -ERRNO in other failures
448  */
msa311_set_odr(struct msa311_priv * msa311,unsigned int odr)449 static int msa311_set_odr(struct msa311_priv *msa311, unsigned int odr)
450 {
451 	struct device *dev = msa311->dev;
452 	unsigned int pwr_mode;
453 	bool good_odr;
454 	int err;
455 
456 	err = regmap_field_read(msa311->fields[F_PWR_MODE], &pwr_mode);
457 	if (err)
458 		return err;
459 
460 	/* Filter bad ODR values */
461 	if (pwr_mode == MSA311_PWR_MODE_NORMAL)
462 		good_odr = (odr > MSA311_ODR_1_95_HZ);
463 	else
464 		good_odr = false;
465 
466 	if (!good_odr) {
467 		dev_err(dev,
468 			"can't set odr %u.%06uHz, not available in %s mode\n",
469 			msa311_odr_table[odr].integral,
470 			msa311_odr_table[odr].microfract,
471 			msa311_pwr_modes[pwr_mode]);
472 		return -EINVAL;
473 	}
474 
475 	return regmap_field_write(msa311->fields[F_ODR], odr);
476 }
477 
478 /**
479  * msa311_wait_for_next_data() - Wait next accel data available after resume
480  * @msa311: MSA311 internal private state
481  *
482  * Return: 0 on success, -EINTR if msleep() was interrupted,
483  *         -ERRNO in other failures
484  */
msa311_wait_for_next_data(struct msa311_priv * msa311)485 static int msa311_wait_for_next_data(struct msa311_priv *msa311)
486 {
487 	static const unsigned int unintr_thresh_ms = 20;
488 	struct device *dev = msa311->dev;
489 	unsigned long freq_uhz;
490 	unsigned long wait_ms;
491 	unsigned int odr;
492 	int err;
493 
494 	err = msa311_get_odr(msa311, &odr);
495 	if (err) {
496 		dev_err(dev, "can't get actual frequency (%pe)\n",
497 			ERR_PTR(err));
498 		return err;
499 	}
500 
501 	/*
502 	 * After msa311 resuming is done, we need to wait for data
503 	 * to be refreshed by accel logic.
504 	 * A certain timeout is calculated based on the current ODR value.
505 	 * If requested timeout isn't so long (let's assume 20ms),
506 	 * we can wait for next data in uninterruptible sleep.
507 	 */
508 	freq_uhz = msa311_odr_table[odr].integral * MICROHZ_PER_HZ +
509 		   msa311_odr_table[odr].microfract;
510 	wait_ms = (MICROHZ_PER_HZ / freq_uhz) * MSEC_PER_SEC;
511 
512 	if (wait_ms < unintr_thresh_ms)
513 		usleep_range(wait_ms * USEC_PER_MSEC,
514 			     unintr_thresh_ms * USEC_PER_MSEC);
515 	else if (msleep_interruptible(wait_ms))
516 		return -EINTR;
517 
518 	return 0;
519 }
520 
521 /**
522  * msa311_set_pwr_mode() - Install certain MSA311 power mode
523  * @msa311: MSA311 internal private state
524  * @mode: Power mode can be equal to NORMAL or SUSPEND
525  *
526  * This function should be called under msa311->lock.
527  *
528  * Return: 0 on success, -ERRNO on failure
529  */
msa311_set_pwr_mode(struct msa311_priv * msa311,unsigned int mode)530 static int msa311_set_pwr_mode(struct msa311_priv *msa311, unsigned int mode)
531 {
532 	struct device *dev = msa311->dev;
533 	unsigned int prev_mode;
534 	int err;
535 
536 	if (mode >= ARRAY_SIZE(msa311_pwr_modes))
537 		return -EINVAL;
538 
539 	dev_dbg(dev, "transition to %s mode\n", msa311_pwr_modes[mode]);
540 
541 	err = regmap_field_read(msa311->fields[F_PWR_MODE], &prev_mode);
542 	if (err)
543 		return err;
544 
545 	err = regmap_field_write(msa311->fields[F_PWR_MODE], mode);
546 	if (err)
547 		return err;
548 
549 	/* Wait actual data if we wake up */
550 	if (prev_mode == MSA311_PWR_MODE_SUSPEND &&
551 	    mode == MSA311_PWR_MODE_NORMAL)
552 		return msa311_wait_for_next_data(msa311);
553 
554 	return 0;
555 }
556 
557 /**
558  * msa311_get_axis() - Read MSA311 accel data for certain IIO channel axis spec
559  * @msa311: MSA311 internal private state
560  * @chan: IIO channel specification
561  * @axis: Output accel axis data for requested IIO channel spec
562  *
563  * This function should be called under msa311->lock.
564  *
565  * Return: 0 on success, -EINVAL for unknown IIO channel specification,
566  *         -ERRNO in other failures
567  */
msa311_get_axis(struct msa311_priv * msa311,const struct iio_chan_spec * const chan,__le16 * axis)568 static int msa311_get_axis(struct msa311_priv *msa311,
569 			   const struct iio_chan_spec * const chan,
570 			   __le16 *axis)
571 {
572 	struct device *dev = msa311->dev;
573 	unsigned int axis_reg;
574 
575 	if (chan->scan_index < MSA311_SI_X || chan->scan_index > MSA311_SI_Z) {
576 		dev_err(dev, "invalid scan_index value [%d]\n",
577 			chan->scan_index);
578 		return -EINVAL;
579 	}
580 
581 	/* Axes data layout has 2 byte gap for each axis starting from X axis */
582 	axis_reg = MSA311_ACC_X_REG + (chan->scan_index << 1);
583 
584 	return regmap_bulk_read(msa311->regs, axis_reg, axis, sizeof(*axis));
585 }
586 
msa311_read_raw_data(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2)587 static int msa311_read_raw_data(struct iio_dev *indio_dev,
588 				struct iio_chan_spec const *chan,
589 				int *val, int *val2)
590 {
591 	struct msa311_priv *msa311 = iio_priv(indio_dev);
592 	struct device *dev = msa311->dev;
593 	__le16 axis;
594 	int err;
595 
596 	if (!iio_device_claim_direct(indio_dev))
597 		return -EBUSY;
598 
599 	err = pm_runtime_resume_and_get(dev);
600 	if (err) {
601 		iio_device_release_direct(indio_dev);
602 		return err;
603 	}
604 
605 	mutex_lock(&msa311->lock);
606 	err = msa311_get_axis(msa311, chan, &axis);
607 	mutex_unlock(&msa311->lock);
608 
609 	pm_runtime_put_autosuspend(dev);
610 
611 	iio_device_release_direct(indio_dev);
612 
613 	if (err) {
614 		dev_err(dev, "can't get axis %s (%pe)\n",
615 			chan->datasheet_name, ERR_PTR(err));
616 		return err;
617 	}
618 
619 	/*
620 	 * Axis data format is:
621 	 * ACC_X = (ACC_X_MSB[7:0] << 4) | ACC_X_LSB[7:4]
622 	 */
623 	*val = sign_extend32(le16_to_cpu(axis) >> chan->scan_type.shift,
624 			     chan->scan_type.realbits - 1);
625 
626 	return IIO_VAL_INT;
627 }
628 
msa311_read_scale(struct iio_dev * indio_dev,int * val,int * val2)629 static int msa311_read_scale(struct iio_dev *indio_dev, int *val, int *val2)
630 {
631 	struct msa311_priv *msa311 = iio_priv(indio_dev);
632 	struct device *dev = msa311->dev;
633 	unsigned int fs;
634 	int err;
635 
636 	mutex_lock(&msa311->lock);
637 	err = regmap_field_read(msa311->fields[F_FS], &fs);
638 	mutex_unlock(&msa311->lock);
639 	if (err) {
640 		dev_err(dev, "can't get actual scale (%pe)\n", ERR_PTR(err));
641 		return err;
642 	}
643 
644 	*val = msa311_fs_table[fs].integral;
645 	*val2 = msa311_fs_table[fs].microfract;
646 
647 	return IIO_VAL_INT_PLUS_MICRO;
648 }
649 
msa311_read_samp_freq(struct iio_dev * indio_dev,int * val,int * val2)650 static int msa311_read_samp_freq(struct iio_dev *indio_dev,
651 				 int *val, int *val2)
652 {
653 	struct msa311_priv *msa311 = iio_priv(indio_dev);
654 	struct device *dev = msa311->dev;
655 	unsigned int odr;
656 	int err;
657 
658 	mutex_lock(&msa311->lock);
659 	err = msa311_get_odr(msa311, &odr);
660 	mutex_unlock(&msa311->lock);
661 	if (err) {
662 		dev_err(dev, "can't get actual frequency (%pe)\n",
663 			ERR_PTR(err));
664 		return err;
665 	}
666 
667 	*val = msa311_odr_table[odr].integral;
668 	*val2 = msa311_odr_table[odr].microfract;
669 
670 	return IIO_VAL_INT_PLUS_MICRO;
671 }
672 
msa311_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)673 static int msa311_read_raw(struct iio_dev *indio_dev,
674 			   struct iio_chan_spec const *chan,
675 			   int *val, int *val2, long mask)
676 {
677 	switch (mask) {
678 	case IIO_CHAN_INFO_RAW:
679 		return msa311_read_raw_data(indio_dev, chan, val, val2);
680 
681 	case IIO_CHAN_INFO_SCALE:
682 		return msa311_read_scale(indio_dev, val, val2);
683 
684 	case IIO_CHAN_INFO_SAMP_FREQ:
685 		return msa311_read_samp_freq(indio_dev, val, val2);
686 
687 	default:
688 		return -EINVAL;
689 	}
690 }
691 
msa311_read_avail(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,const int ** vals,int * type,int * length,long mask)692 static int msa311_read_avail(struct iio_dev *indio_dev,
693 			     struct iio_chan_spec const *chan,
694 			     const int **vals, int *type,
695 			     int *length, long mask)
696 {
697 	switch (mask) {
698 	case IIO_CHAN_INFO_SAMP_FREQ:
699 		*vals = (int *)msa311_odr_table;
700 		*type = IIO_VAL_INT_PLUS_MICRO;
701 		/* ODR value has 2 ints (integer and fractional parts) */
702 		*length = ARRAY_SIZE(msa311_odr_table) * 2;
703 		return IIO_AVAIL_LIST;
704 
705 	case IIO_CHAN_INFO_SCALE:
706 		*vals = (int *)msa311_fs_table;
707 		*type = IIO_VAL_INT_PLUS_MICRO;
708 		/* FS value has 2 ints (integer and fractional parts) */
709 		*length = ARRAY_SIZE(msa311_fs_table) * 2;
710 		return IIO_AVAIL_LIST;
711 
712 	default:
713 		return -EINVAL;
714 	}
715 }
716 
msa311_write_scale(struct iio_dev * indio_dev,int val,int val2)717 static int msa311_write_scale(struct iio_dev *indio_dev, int val, int val2)
718 {
719 	struct msa311_priv *msa311 = iio_priv(indio_dev);
720 	struct device *dev = msa311->dev;
721 	unsigned int fs;
722 	int err;
723 
724 	/* We do not have fs >= 1, so skip such values */
725 	if (val)
726 		return 0;
727 
728 	err = pm_runtime_resume_and_get(dev);
729 	if (err)
730 		return err;
731 
732 	err = -EINVAL;
733 	for (fs = 0; fs < ARRAY_SIZE(msa311_fs_table); fs++)
734 		/* Do not check msa311_fs_table[fs].integral, it's always 0 */
735 		if (val2 == msa311_fs_table[fs].microfract) {
736 			mutex_lock(&msa311->lock);
737 			err = regmap_field_write(msa311->fields[F_FS], fs);
738 			mutex_unlock(&msa311->lock);
739 			break;
740 		}
741 
742 	pm_runtime_put_autosuspend(dev);
743 
744 	if (err)
745 		dev_err(dev, "can't update scale (%pe)\n", ERR_PTR(err));
746 
747 	return err;
748 }
749 
msa311_write_samp_freq(struct iio_dev * indio_dev,int val,int val2)750 static int msa311_write_samp_freq(struct iio_dev *indio_dev, int val, int val2)
751 {
752 	struct msa311_priv *msa311 = iio_priv(indio_dev);
753 	struct device *dev = msa311->dev;
754 	unsigned int odr;
755 	int err;
756 
757 	/*
758 	 * Sampling frequency changing is prohibited when buffer mode is
759 	 * enabled, because sometimes MSA311 chip returns outliers during
760 	 * frequency values growing up in the read operation moment.
761 	 */
762 	if (!iio_device_claim_direct(indio_dev))
763 		return -EBUSY;
764 
765 	err = pm_runtime_resume_and_get(dev);
766 	if (err) {
767 		iio_device_release_direct(indio_dev);
768 		return err;
769 	}
770 
771 	err = -EINVAL;
772 	for (odr = 0; odr < ARRAY_SIZE(msa311_odr_table); odr++)
773 		if (val == msa311_odr_table[odr].integral &&
774 		    val2 == msa311_odr_table[odr].microfract) {
775 			mutex_lock(&msa311->lock);
776 			err = msa311_set_odr(msa311, odr);
777 			mutex_unlock(&msa311->lock);
778 			break;
779 		}
780 
781 	pm_runtime_put_autosuspend(dev);
782 
783 	iio_device_release_direct(indio_dev);
784 
785 	if (err)
786 		dev_err(dev, "can't update frequency (%pe)\n", ERR_PTR(err));
787 
788 	return err;
789 }
790 
msa311_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)791 static int msa311_write_raw(struct iio_dev *indio_dev,
792 			    struct iio_chan_spec const *chan,
793 			    int val, int val2, long mask)
794 {
795 	switch (mask) {
796 	case IIO_CHAN_INFO_SCALE:
797 		return msa311_write_scale(indio_dev, val, val2);
798 
799 	case IIO_CHAN_INFO_SAMP_FREQ:
800 		return msa311_write_samp_freq(indio_dev, val, val2);
801 
802 	default:
803 		return -EINVAL;
804 	}
805 }
806 
msa311_debugfs_reg_access(struct iio_dev * indio_dev,unsigned int reg,unsigned int writeval,unsigned int * readval)807 static int msa311_debugfs_reg_access(struct iio_dev *indio_dev,
808 				     unsigned int reg, unsigned int writeval,
809 				     unsigned int *readval)
810 {
811 	struct msa311_priv *msa311 = iio_priv(indio_dev);
812 	struct device *dev = msa311->dev;
813 	int err;
814 
815 	if (reg > regmap_get_max_register(msa311->regs))
816 		return -EINVAL;
817 
818 	err = pm_runtime_resume_and_get(dev);
819 	if (err)
820 		return err;
821 
822 	mutex_lock(&msa311->lock);
823 
824 	if (readval)
825 		err = regmap_read(msa311->regs, reg, readval);
826 	else
827 		err = regmap_write(msa311->regs, reg, writeval);
828 
829 	mutex_unlock(&msa311->lock);
830 
831 	pm_runtime_put_autosuspend(dev);
832 
833 	if (err)
834 		dev_err(dev, "can't %s register %u from debugfs (%pe)\n",
835 			str_read_write(readval), reg, ERR_PTR(err));
836 
837 	return err;
838 }
839 
msa311_buffer_preenable(struct iio_dev * indio_dev)840 static int msa311_buffer_preenable(struct iio_dev *indio_dev)
841 {
842 	struct msa311_priv *msa311 = iio_priv(indio_dev);
843 	struct device *dev = msa311->dev;
844 
845 	return pm_runtime_resume_and_get(dev);
846 }
847 
msa311_buffer_postdisable(struct iio_dev * indio_dev)848 static int msa311_buffer_postdisable(struct iio_dev *indio_dev)
849 {
850 	struct msa311_priv *msa311 = iio_priv(indio_dev);
851 	struct device *dev = msa311->dev;
852 
853 	pm_runtime_put_autosuspend(dev);
854 
855 	return 0;
856 }
857 
msa311_set_new_data_trig_state(struct iio_trigger * trig,bool state)858 static int msa311_set_new_data_trig_state(struct iio_trigger *trig, bool state)
859 {
860 	struct iio_dev *indio_dev = iio_trigger_get_drvdata(trig);
861 	struct msa311_priv *msa311 = iio_priv(indio_dev);
862 	struct device *dev = msa311->dev;
863 	int err;
864 
865 	mutex_lock(&msa311->lock);
866 	err = regmap_field_write(msa311->fields[F_NEW_DATA_INT_EN], state);
867 	mutex_unlock(&msa311->lock);
868 	if (err)
869 		dev_err(dev,
870 			"can't %s buffer due to new_data_int failure (%pe)\n",
871 			str_enable_disable(state), ERR_PTR(err));
872 
873 	return err;
874 }
875 
msa311_validate_device(struct iio_trigger * trig,struct iio_dev * indio_dev)876 static int msa311_validate_device(struct iio_trigger *trig,
877 				  struct iio_dev *indio_dev)
878 {
879 	return iio_trigger_get_drvdata(trig) == indio_dev ? 0 : -EINVAL;
880 }
881 
msa311_buffer_thread(int irq,void * p)882 static irqreturn_t msa311_buffer_thread(int irq, void *p)
883 {
884 	struct iio_poll_func *pf = p;
885 	struct msa311_priv *msa311 = iio_priv(pf->indio_dev);
886 	struct iio_dev *indio_dev = pf->indio_dev;
887 	const struct iio_chan_spec *chan;
888 	struct device *dev = msa311->dev;
889 	int bit, err, i = 0;
890 	__le16 axis;
891 	struct {
892 		__le16 channels[MSA311_SI_Z + 1];
893 		aligned_s64 ts;
894 	} buf = { };
895 
896 	mutex_lock(&msa311->lock);
897 
898 	iio_for_each_active_channel(indio_dev, bit) {
899 		chan = &msa311_channels[bit];
900 
901 		err = msa311_get_axis(msa311, chan, &axis);
902 		if (err) {
903 			mutex_unlock(&msa311->lock);
904 			dev_err(dev, "can't get axis %s (%pe)\n",
905 				chan->datasheet_name, ERR_PTR(err));
906 			goto notify_done;
907 		}
908 
909 		buf.channels[i++] = axis;
910 	}
911 
912 	mutex_unlock(&msa311->lock);
913 
914 	iio_push_to_buffers_with_ts(indio_dev, &buf, sizeof(buf),
915 				    iio_get_time_ns(indio_dev));
916 
917 notify_done:
918 	iio_trigger_notify_done(indio_dev->trig);
919 
920 	return IRQ_HANDLED;
921 }
922 
msa311_irq_thread(int irq,void * p)923 static irqreturn_t msa311_irq_thread(int irq, void *p)
924 {
925 	struct msa311_priv *msa311 = iio_priv(p);
926 	unsigned int new_data_int_enabled;
927 	struct device *dev = msa311->dev;
928 	int err;
929 
930 	mutex_lock(&msa311->lock);
931 
932 	/*
933 	 * We do not check NEW_DATA int status, because based on the
934 	 * specification it's cleared automatically after a fixed time.
935 	 * So just check that is enabled by driver logic.
936 	 */
937 	err = regmap_field_read(msa311->fields[F_NEW_DATA_INT_EN],
938 				&new_data_int_enabled);
939 
940 	mutex_unlock(&msa311->lock);
941 	if (err) {
942 		dev_err(dev, "can't read new_data interrupt state (%pe)\n",
943 			ERR_PTR(err));
944 		return IRQ_NONE;
945 	}
946 
947 	if (new_data_int_enabled)
948 		iio_trigger_poll_nested(msa311->new_data_trig);
949 
950 	return IRQ_HANDLED;
951 }
952 
953 static const struct iio_info msa311_info = {
954 	.read_raw = msa311_read_raw,
955 	.read_avail = msa311_read_avail,
956 	.write_raw = msa311_write_raw,
957 	.debugfs_reg_access = msa311_debugfs_reg_access,
958 };
959 
960 static const struct iio_buffer_setup_ops msa311_buffer_setup_ops = {
961 	.preenable = msa311_buffer_preenable,
962 	.postdisable = msa311_buffer_postdisable,
963 };
964 
965 static const struct iio_trigger_ops msa311_new_data_trig_ops = {
966 	.set_trigger_state = msa311_set_new_data_trig_state,
967 	.validate_device = msa311_validate_device,
968 };
969 
msa311_check_partid(struct msa311_priv * msa311)970 static int msa311_check_partid(struct msa311_priv *msa311)
971 {
972 	struct device *dev = msa311->dev;
973 	unsigned int partid;
974 	int err;
975 
976 	err = regmap_read(msa311->regs, MSA311_PARTID_REG, &partid);
977 	if (err)
978 		return dev_err_probe(dev, err, "failed to read partid\n");
979 
980 	if (partid != MSA311_WHO_AM_I)
981 		dev_warn(dev, "invalid partid (%#x), expected (%#x)\n",
982 			 partid, MSA311_WHO_AM_I);
983 
984 	msa311->chip_name = devm_kasprintf(dev, GFP_KERNEL,
985 					   "msa311-%02x", partid);
986 	if (!msa311->chip_name)
987 		return -ENOMEM;
988 
989 	return 0;
990 }
991 
msa311_soft_reset(struct msa311_priv * msa311)992 static int msa311_soft_reset(struct msa311_priv *msa311)
993 {
994 	struct device *dev = msa311->dev;
995 	int err;
996 
997 	err = regmap_write(msa311->regs, MSA311_SOFT_RESET_REG,
998 			   MSA311_GENMASK(F_SOFT_RESET_I2C) |
999 			   MSA311_GENMASK(F_SOFT_RESET_SPI));
1000 	if (err)
1001 		return dev_err_probe(dev, err, "can't soft reset all logic\n");
1002 
1003 	return 0;
1004 }
1005 
msa311_chip_init(struct msa311_priv * msa311)1006 static int msa311_chip_init(struct msa311_priv *msa311)
1007 {
1008 	struct device *dev = msa311->dev;
1009 	const char zero_bulk[2] = { };
1010 	int err;
1011 
1012 	err = regmap_write(msa311->regs, MSA311_RANGE_REG, MSA311_FS_16G);
1013 	if (err)
1014 		return dev_err_probe(dev, err, "failed to setup accel range\n");
1015 
1016 	/* Disable all interrupts by default */
1017 	err = regmap_bulk_write(msa311->regs, MSA311_INT_SET_0_REG,
1018 				zero_bulk, sizeof(zero_bulk));
1019 	if (err)
1020 		return dev_err_probe(dev, err,
1021 				     "can't disable set0/set1 interrupts\n");
1022 
1023 	/* Unmap all INT1 interrupts by default */
1024 	err = regmap_bulk_write(msa311->regs, MSA311_INT_MAP_0_REG,
1025 				zero_bulk, sizeof(zero_bulk));
1026 	if (err)
1027 		return dev_err_probe(dev, err,
1028 				     "failed to unmap map0/map1 interrupts\n");
1029 
1030 	/* Disable all axes by default */
1031 	err = regmap_clear_bits(msa311->regs, MSA311_ODR_REG,
1032 				MSA311_GENMASK(F_X_AXIS_DIS) |
1033 				MSA311_GENMASK(F_Y_AXIS_DIS) |
1034 				MSA311_GENMASK(F_Z_AXIS_DIS));
1035 	if (err)
1036 		return dev_err_probe(dev, err, "can't enable all axes\n");
1037 
1038 	err = msa311_set_odr(msa311, MSA311_ODR_125_HZ);
1039 	if (err)
1040 		return dev_err_probe(dev, err,
1041 				     "failed to set accel frequency\n");
1042 
1043 	return 0;
1044 }
1045 
msa311_setup_interrupts(struct msa311_priv * msa311)1046 static int msa311_setup_interrupts(struct msa311_priv *msa311)
1047 {
1048 	struct device *dev = msa311->dev;
1049 	struct i2c_client *i2c = to_i2c_client(dev);
1050 	struct iio_dev *indio_dev = i2c_get_clientdata(i2c);
1051 	struct iio_trigger *trig;
1052 	int err;
1053 
1054 	/* Keep going without interrupts if no initialized I2C IRQ */
1055 	if (i2c->irq <= 0)
1056 		return 0;
1057 
1058 	err = devm_request_threaded_irq(&i2c->dev, i2c->irq, NULL,
1059 					msa311_irq_thread, IRQF_ONESHOT,
1060 					msa311->chip_name, indio_dev);
1061 	if (err)
1062 		return err;
1063 
1064 	trig = devm_iio_trigger_alloc(dev, "%s-new-data", msa311->chip_name);
1065 	if (!trig)
1066 		return -ENOMEM;
1067 
1068 	msa311->new_data_trig = trig;
1069 	msa311->new_data_trig->ops = &msa311_new_data_trig_ops;
1070 	iio_trigger_set_drvdata(msa311->new_data_trig, indio_dev);
1071 
1072 	err = devm_iio_trigger_register(dev, msa311->new_data_trig);
1073 	if (err)
1074 		return dev_err_probe(dev, err,
1075 				     "can't register newdata trigger\n");
1076 
1077 	err = regmap_field_write(msa311->fields[F_INT1_OD],
1078 				 MSA311_INT1_OD_PUSH_PULL);
1079 	if (err)
1080 		return dev_err_probe(dev, err,
1081 				     "can't enable push-pull interrupt\n");
1082 
1083 	err = regmap_field_write(msa311->fields[F_INT1_LVL],
1084 				 MSA311_INT1_LVL_HIGH);
1085 	if (err)
1086 		return dev_err_probe(dev, err,
1087 				     "can't set active interrupt level\n");
1088 
1089 	err = regmap_field_write(msa311->fields[F_LATCH_INT],
1090 				 MSA311_LATCH_INT_LATCHED);
1091 	if (err)
1092 		return dev_err_probe(dev, err,
1093 				     "can't latch interrupt\n");
1094 
1095 	err = regmap_field_write(msa311->fields[F_RESET_INT], 1);
1096 	if (err)
1097 		return dev_err_probe(dev, err,
1098 				     "can't reset interrupt\n");
1099 
1100 	err = regmap_field_write(msa311->fields[F_INT1_NEW_DATA], 1);
1101 	if (err)
1102 		return dev_err_probe(dev, err,
1103 				     "can't map new data interrupt\n");
1104 
1105 	return 0;
1106 }
1107 
msa311_regmap_init(struct msa311_priv * msa311)1108 static int msa311_regmap_init(struct msa311_priv *msa311)
1109 {
1110 	struct regmap_field **fields = msa311->fields;
1111 	struct device *dev = msa311->dev;
1112 	struct i2c_client *i2c = to_i2c_client(dev);
1113 	struct regmap *regmap;
1114 	int i;
1115 
1116 	regmap = devm_regmap_init_i2c(i2c, &msa311_regmap_config);
1117 	if (IS_ERR(regmap))
1118 		return dev_err_probe(dev, PTR_ERR(regmap),
1119 				     "failed to register i2c regmap\n");
1120 
1121 	msa311->regs = regmap;
1122 
1123 	for (i = 0; i < F_MAX_FIELDS; i++) {
1124 		fields[i] = devm_regmap_field_alloc(dev,
1125 						    msa311->regs,
1126 						    msa311_reg_fields[i]);
1127 		if (IS_ERR(msa311->fields[i]))
1128 			return dev_err_probe(dev, PTR_ERR(msa311->fields[i]),
1129 					     "can't alloc field[%d]\n", i);
1130 	}
1131 
1132 	return 0;
1133 }
1134 
msa311_powerdown(void * msa311)1135 static void msa311_powerdown(void *msa311)
1136 {
1137 	msa311_set_pwr_mode(msa311, MSA311_PWR_MODE_SUSPEND);
1138 }
1139 
msa311_probe(struct i2c_client * i2c)1140 static int msa311_probe(struct i2c_client *i2c)
1141 {
1142 	struct device *dev = &i2c->dev;
1143 	struct msa311_priv *msa311;
1144 	struct iio_dev *indio_dev;
1145 	int err;
1146 
1147 	indio_dev = devm_iio_device_alloc(dev, sizeof(*msa311));
1148 	if (!indio_dev)
1149 		return -ENOMEM;
1150 
1151 	msa311 = iio_priv(indio_dev);
1152 	msa311->dev = dev;
1153 	i2c_set_clientdata(i2c, indio_dev);
1154 
1155 	err = msa311_regmap_init(msa311);
1156 	if (err)
1157 		return err;
1158 
1159 	mutex_init(&msa311->lock);
1160 
1161 	err = devm_regulator_get_enable(dev, "vdd");
1162 	if (err)
1163 		return dev_err_probe(dev, err, "can't get vdd supply\n");
1164 
1165 	err = msa311_check_partid(msa311);
1166 	if (err)
1167 		return err;
1168 
1169 	err = msa311_soft_reset(msa311);
1170 	if (err)
1171 		return err;
1172 
1173 	err = msa311_set_pwr_mode(msa311, MSA311_PWR_MODE_NORMAL);
1174 	if (err)
1175 		return dev_err_probe(dev, err, "failed to power on device\n");
1176 
1177 	/*
1178 	 * Register powerdown deferred callback which suspends the chip
1179 	 * after module unloaded.
1180 	 *
1181 	 * MSA311 should be in SUSPEND mode in the two cases:
1182 	 * 1) When driver is loaded, but we do not have any data or
1183 	 *    configuration requests to it (we are solving it using
1184 	 *    autosuspend feature).
1185 	 * 2) When driver is unloaded and device is not used (devm action is
1186 	 *    used in this case).
1187 	 */
1188 	err = devm_add_action_or_reset(dev, msa311_powerdown, msa311);
1189 	if (err)
1190 		return err;
1191 
1192 	err = pm_runtime_set_active(dev);
1193 	if (err)
1194 		return err;
1195 
1196 	err = devm_pm_runtime_enable(dev);
1197 	if (err)
1198 		return err;
1199 
1200 	pm_runtime_get_noresume(dev);
1201 	pm_runtime_set_autosuspend_delay(dev, MSA311_PWR_SLEEP_DELAY_MS);
1202 	pm_runtime_use_autosuspend(dev);
1203 
1204 	err = msa311_chip_init(msa311);
1205 	if (err)
1206 		return err;
1207 
1208 	indio_dev->modes = INDIO_DIRECT_MODE;
1209 	indio_dev->channels = msa311_channels;
1210 	indio_dev->num_channels = ARRAY_SIZE(msa311_channels);
1211 	indio_dev->name = msa311->chip_name;
1212 	indio_dev->info = &msa311_info;
1213 
1214 	err = devm_iio_triggered_buffer_setup(dev, indio_dev,
1215 					      iio_pollfunc_store_time,
1216 					      msa311_buffer_thread,
1217 					      &msa311_buffer_setup_ops);
1218 	if (err)
1219 		return dev_err_probe(dev, err,
1220 				     "can't setup IIO trigger buffer\n");
1221 
1222 	err = msa311_setup_interrupts(msa311);
1223 	if (err)
1224 		return err;
1225 
1226 	pm_runtime_put_autosuspend(dev);
1227 
1228 	err = devm_iio_device_register(dev, indio_dev);
1229 	if (err)
1230 		return dev_err_probe(dev, err, "IIO device register failed\n");
1231 
1232 	return 0;
1233 }
1234 
msa311_runtime_suspend(struct device * dev)1235 static int msa311_runtime_suspend(struct device *dev)
1236 {
1237 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
1238 	struct msa311_priv *msa311 = iio_priv(indio_dev);
1239 	int err;
1240 
1241 	mutex_lock(&msa311->lock);
1242 	err = msa311_set_pwr_mode(msa311, MSA311_PWR_MODE_SUSPEND);
1243 	mutex_unlock(&msa311->lock);
1244 	if (err)
1245 		dev_err(dev, "failed to power off device (%pe)\n",
1246 			ERR_PTR(err));
1247 
1248 	return err;
1249 }
1250 
msa311_runtime_resume(struct device * dev)1251 static int msa311_runtime_resume(struct device *dev)
1252 {
1253 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
1254 	struct msa311_priv *msa311 = iio_priv(indio_dev);
1255 	int err;
1256 
1257 	mutex_lock(&msa311->lock);
1258 	err = msa311_set_pwr_mode(msa311, MSA311_PWR_MODE_NORMAL);
1259 	mutex_unlock(&msa311->lock);
1260 	if (err)
1261 		dev_err(dev, "failed to power on device (%pe)\n",
1262 			ERR_PTR(err));
1263 
1264 	return err;
1265 }
1266 
1267 static DEFINE_RUNTIME_DEV_PM_OPS(msa311_pm_ops, msa311_runtime_suspend,
1268 				 msa311_runtime_resume, NULL);
1269 
1270 static const struct i2c_device_id msa311_i2c_id[] = {
1271 	{ .name = "msa311" },
1272 	{ }
1273 };
1274 MODULE_DEVICE_TABLE(i2c, msa311_i2c_id);
1275 
1276 static const struct of_device_id msa311_of_match[] = {
1277 	{ .compatible = "memsensing,msa311" },
1278 	{ }
1279 };
1280 MODULE_DEVICE_TABLE(of, msa311_of_match);
1281 
1282 static struct i2c_driver msa311_driver = {
1283 	.driver = {
1284 		.name = "msa311",
1285 		.of_match_table = msa311_of_match,
1286 		.pm = pm_ptr(&msa311_pm_ops),
1287 	},
1288 	.probe		= msa311_probe,
1289 	.id_table	= msa311_i2c_id,
1290 };
1291 module_i2c_driver(msa311_driver);
1292 
1293 MODULE_AUTHOR("Dmitry Rokosov <ddrokosov@sberdevices.ru>");
1294 MODULE_DESCRIPTION("MEMSensing MSA311 3-axis accelerometer driver");
1295 MODULE_LICENSE("GPL");
1296