xref: /linux/drivers/iio/adc/pac1921.c (revision 2cc699b3c2fe5ea84081059c88c46373cbebe630)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * IIO driver for PAC1921 High-Side Power/Current Monitor
4  *
5  * Copyright (C) 2024 Matteo Martelli <matteomartelli3@gmail.com>
6  */
7 
8 #include <linux/unaligned.h>
9 #include <linux/bitfield.h>
10 #include <linux/i2c.h>
11 #include <linux/iio/events.h>
12 #include <linux/iio/iio.h>
13 #include <linux/iio/trigger_consumer.h>
14 #include <linux/iio/triggered_buffer.h>
15 #include <linux/limits.h>
16 #include <linux/regmap.h>
17 #include <linux/units.h>
18 
19 /* pac1921 registers */
20 #define PAC1921_REG_GAIN_CFG		0x00
21 #define PAC1921_REG_INT_CFG		0x01
22 #define PAC1921_REG_CONTROL		0x02
23 #define PAC1921_REG_VBUS		0x10
24 #define PAC1921_REG_VSENSE		0x12
25 #define PAC1921_REG_OVERFLOW_STS	0x1C
26 #define PAC1921_REG_VPOWER		0x1D
27 
28 /* pac1921 gain configuration bits */
29 #define PAC1921_GAIN_DI_GAIN_MASK	GENMASK(5, 3)
30 #define PAC1921_GAIN_DV_GAIN_MASK	GENMASK(2, 0)
31 
32 /* pac1921 integration configuration bits */
33 #define PAC1921_INT_CFG_SMPL_MASK	GENMASK(7, 4)
34 #define PAC1921_INT_CFG_VSFEN		BIT(3)
35 #define PAC1921_INT_CFG_VBFEN		BIT(2)
36 #define PAC1921_INT_CFG_RIOV		BIT(1)
37 #define PAC1921_INT_CFG_INTEN		BIT(0)
38 
39 /* pac1921 control bits */
40 #define PAC1921_CONTROL_MXSL_MASK	GENMASK(7, 6)
41 enum pac1921_mxsl {
42 	PAC1921_MXSL_VPOWER_PIN = 0,
43 	PAC1921_MXSL_VSENSE_FREE_RUN = 1,
44 	PAC1921_MXSL_VBUS_FREE_RUN = 2,
45 	PAC1921_MXSL_VPOWER_FREE_RUN = 3,
46 };
47 #define PAC1921_CONTROL_SLEEP		BIT(2)
48 
49 /* pac1921 result registers mask and resolution */
50 #define PAC1921_RES_MASK		GENMASK(15, 6)
51 #define PAC1921_RES_RESOLUTION		1023
52 
53 /* pac1921 overflow status bits */
54 #define PAC1921_OVERFLOW_VSOV		BIT(2)
55 #define PAC1921_OVERFLOW_VBOV		BIT(1)
56 #define PAC1921_OVERFLOW_VPOV		BIT(0)
57 
58 /* pac1921 constants */
59 #define PAC1921_MAX_VSENSE_MV		100
60 #define PAC1921_MAX_VBUS_V		32
61 /* Time to first communication after power up (tINT_T) */
62 #define PAC1921_POWERUP_TIME_MS		20
63 /* Time from Sleep State to Start of Integration Period (tSLEEP_TO_INT) */
64 #define PAC1921_SLEEP_TO_INT_TIME_US	86
65 
66 /* pac1921 defaults */
67 #define PAC1921_DEFAULT_DV_GAIN		0 /* 2^(value): 1x gain (HW default) */
68 #define PAC1921_DEFAULT_DI_GAIN		0 /* 2^(value): 1x gain (HW default) */
69 #define PAC1921_DEFAULT_NUM_SAMPLES	0 /* 2^(value): 1 sample (HW default) */
70 
71 #define PAC1921_ACPI_GET_uOHMS_VALS             0
72 #define PAC1921_ACPI_GET_LABEL			1
73 
74 /* f7bb9932-86ee-4516-a236-7a7a742e55cb */
75 static const guid_t pac1921_guid =
76 			GUID_INIT(0xf7bb9932, 0x86ee, 0x4516, 0xa2,
77 				  0x36, 0x7a, 0x7a, 0x74, 0x2e, 0x55, 0xcb);
78 
79 /*
80  * Pre-computed scale factors for BUS voltage
81  * format: IIO_VAL_INT_PLUS_NANO
82  * unit: mV
83  *
84  * Vbus scale (mV) = max_vbus (mV) / dv_gain / resolution
85  */
86 static const int pac1921_vbus_scales[][2] = {
87 	{ 31, 280547409 },	/* dv_gain x1 */
88 	{ 15, 640273704 },	/* dv_gain x2 */
89 	{ 7, 820136852 },	/* dv_gain x4 */
90 	{ 3, 910068426 },	/* dv_gain x8 */
91 	{ 1, 955034213 },	/* dv_gain x16 */
92 	{ 0, 977517106 },	/* dv_gain x32 */
93 };
94 
95 /*
96  * Pre-computed scales for SENSE voltage
97  * format: IIO_VAL_INT_PLUS_NANO
98  * unit: mV
99  *
100  * Vsense scale (mV) = max_vsense (mV) / di_gain / resolution
101  */
102 static const int pac1921_vsense_scales[][2] = {
103 	{ 0, 97751710 },	/* di_gain x1 */
104 	{ 0, 48875855 },	/* di_gain x2 */
105 	{ 0, 24437927 },	/* di_gain x4 */
106 	{ 0, 12218963 },	/* di_gain x8 */
107 	{ 0, 6109481 },		/* di_gain x16 */
108 	{ 0, 3054740 },		/* di_gain x32 */
109 	{ 0, 1527370 },		/* di_gain x64 */
110 	{ 0, 763685 },		/* di_gain x128 */
111 };
112 
113 /*
114  * Numbers of samples used to integrate measurements at the end of an
115  * integration period.
116  *
117  * Changing the number of samples affects the integration period: higher the
118  * number of samples, longer the integration period.
119  *
120  * These correspond to the oversampling ratios available exposed to userspace.
121  */
122 static const int pac1921_int_num_samples[] = {
123 	1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048
124 };
125 
126 /*
127  * The integration period depends on the configuration of number of integration
128  * samples, measurement resolution and post filters. The following array
129  * contains integration periods, in microsecs unit, based on table 4-5 from
130  * datasheet considering power integration mode, 14-Bit resolution and post
131  * filters on. Each index corresponds to a specific number of samples from 1
132  * to 2048.
133  */
134 static const unsigned int pac1921_int_periods_usecs[] = {
135 	2720,		/* 1 sample */
136 	4050,		/* 2 samples */
137 	6790,		/* 4 samples */
138 	12200,		/* 8 samples */
139 	23000,		/* 16 samples */
140 	46000,		/* 32 samples */
141 	92000,		/* 64 samples */
142 	184000,		/* 128 samples */
143 	368000,		/* 256 samples */
144 	736000,		/* 512 samples */
145 	1471000,	/* 1024 samples */
146 	2941000		/* 2048 samples */
147 };
148 
149 /* pac1921 regmap configuration */
150 static const struct regmap_range pac1921_regmap_wr_ranges[] = {
151 	regmap_reg_range(PAC1921_REG_GAIN_CFG, PAC1921_REG_CONTROL),
152 };
153 
154 static const struct regmap_access_table pac1921_regmap_wr_table = {
155 	.yes_ranges = pac1921_regmap_wr_ranges,
156 	.n_yes_ranges = ARRAY_SIZE(pac1921_regmap_wr_ranges),
157 };
158 
159 static const struct regmap_range pac1921_regmap_rd_ranges[] = {
160 	regmap_reg_range(PAC1921_REG_GAIN_CFG, PAC1921_REG_CONTROL),
161 	regmap_reg_range(PAC1921_REG_VBUS, PAC1921_REG_VPOWER + 1),
162 };
163 
164 static const struct regmap_access_table pac1921_regmap_rd_table = {
165 	.yes_ranges = pac1921_regmap_rd_ranges,
166 	.n_yes_ranges = ARRAY_SIZE(pac1921_regmap_rd_ranges),
167 };
168 
169 static const struct regmap_config pac1921_regmap_config = {
170 	.reg_bits = 8,
171 	.val_bits = 8,
172 	.rd_table = &pac1921_regmap_rd_table,
173 	.wr_table = &pac1921_regmap_wr_table,
174 };
175 
176 enum pac1921_channels {
177 	PAC1921_CHAN_VBUS = 0,
178 	PAC1921_CHAN_VSENSE = 1,
179 	PAC1921_CHAN_CURRENT = 2,
180 	PAC1921_CHAN_POWER = 3,
181 };
182 #define PAC1921_NUM_MEAS_CHANS 4
183 
184 struct pac1921_priv {
185 	struct i2c_client *client;
186 	struct regmap *regmap;
187 	struct regulator *vdd;
188 	struct iio_info iio_info;
189 
190 	/*
191 	 * Synchronize access to private members, and ensure atomicity of
192 	 * consecutive regmap operations.
193 	 */
194 	struct mutex lock;
195 
196 	u32 rshunt_uohm; /* uOhm */
197 	u8 dv_gain;
198 	u8 di_gain;
199 	u8 n_samples;
200 	u8 prev_ovf_flags;
201 	u8 ovf_enabled_events;
202 
203 	bool first_integr_started;
204 	bool first_integr_done;
205 	unsigned long integr_started_time_jiffies;
206 	unsigned int integr_period_usecs;
207 
208 	int current_scales[ARRAY_SIZE(pac1921_vsense_scales)][2];
209 
210 	struct {
211 		u16 chan[PAC1921_NUM_MEAS_CHANS];
212 		aligned_s64 timestamp;
213 	} scan;
214 };
215 
216 /*
217  * Check if first integration after configuration update has completed.
218  *
219  * Must be called with lock held.
220  */
pac1921_data_ready(struct pac1921_priv * priv)221 static bool pac1921_data_ready(struct pac1921_priv *priv)
222 {
223 	if (!priv->first_integr_started)
224 		return false;
225 
226 	if (!priv->first_integr_done) {
227 		unsigned long t_ready;
228 
229 		/*
230 		 * Data valid after the device entered into integration state,
231 		 * considering worst case where the device was in sleep state,
232 		 * and completed the first integration period.
233 		 */
234 		t_ready = priv->integr_started_time_jiffies +
235 			  usecs_to_jiffies(PAC1921_SLEEP_TO_INT_TIME_US) +
236 			  usecs_to_jiffies(priv->integr_period_usecs);
237 
238 		if (time_before(jiffies, t_ready))
239 			return false;
240 
241 		priv->first_integr_done = true;
242 	}
243 
244 	return true;
245 }
246 
pac1921_calc_scale(int dividend,int divisor,int * val,int * val2)247 static inline void pac1921_calc_scale(int dividend, int divisor, int *val,
248 				      int *val2)
249 {
250 	s64 tmp;
251 
252 	tmp = div_s64(dividend * (s64)NANO, divisor);
253 	*val = div_s64_rem(tmp, NANO, val2);
254 }
255 
256 /*
257  * Fill the table of scale factors for current
258  * format: IIO_VAL_INT_PLUS_NANO
259  * unit: mA
260  *
261  * Vsense LSB (nV) = max_vsense (nV) * di_gain / resolution
262  * Current scale (mA) = Vsense LSB (nV) / shunt (uOhm)
263  *
264  * Must be called with held lock when updating after first initialization.
265  */
pac1921_calc_current_scales(struct pac1921_priv * priv)266 static void pac1921_calc_current_scales(struct pac1921_priv *priv)
267 {
268 	for (unsigned int i = 0; i < ARRAY_SIZE(priv->current_scales); i++) {
269 		int max = (PAC1921_MAX_VSENSE_MV * MICRO) >> i;
270 		int vsense_lsb = DIV_ROUND_CLOSEST(max, PAC1921_RES_RESOLUTION);
271 
272 		pac1921_calc_scale(vsense_lsb, priv->rshunt_uohm,
273 				   &priv->current_scales[i][0],
274 				   &priv->current_scales[i][1]);
275 	}
276 }
277 
278 /*
279  * Check if overflow occurred and if so, push the corresponding events.
280  *
281  * Must be called with lock held.
282  */
pac1921_check_push_overflow(struct iio_dev * indio_dev,s64 timestamp)283 static int pac1921_check_push_overflow(struct iio_dev *indio_dev, s64 timestamp)
284 {
285 	struct pac1921_priv *priv = iio_priv(indio_dev);
286 	unsigned int flags;
287 	int ret;
288 
289 	ret = regmap_read(priv->regmap, PAC1921_REG_OVERFLOW_STS, &flags);
290 	if (ret)
291 		return ret;
292 
293 	if (flags & PAC1921_OVERFLOW_VBOV &&
294 	    !(priv->prev_ovf_flags & PAC1921_OVERFLOW_VBOV) &&
295 	    priv->ovf_enabled_events & PAC1921_OVERFLOW_VBOV) {
296 		iio_push_event(indio_dev,
297 			       IIO_UNMOD_EVENT_CODE(
298 				       IIO_VOLTAGE, PAC1921_CHAN_VBUS,
299 				       IIO_EV_TYPE_THRESH, IIO_EV_DIR_RISING),
300 			       timestamp);
301 	}
302 	if (flags & PAC1921_OVERFLOW_VSOV &&
303 	    !(priv->prev_ovf_flags & PAC1921_OVERFLOW_VSOV) &&
304 	    priv->ovf_enabled_events & PAC1921_OVERFLOW_VSOV) {
305 		iio_push_event(indio_dev,
306 			       IIO_UNMOD_EVENT_CODE(
307 				       IIO_VOLTAGE, PAC1921_CHAN_VSENSE,
308 				       IIO_EV_TYPE_THRESH, IIO_EV_DIR_RISING),
309 			       timestamp);
310 		iio_push_event(indio_dev,
311 			       IIO_UNMOD_EVENT_CODE(
312 				       IIO_CURRENT, PAC1921_CHAN_CURRENT,
313 				       IIO_EV_TYPE_THRESH, IIO_EV_DIR_RISING),
314 			       timestamp);
315 	}
316 	if (flags & PAC1921_OVERFLOW_VPOV &&
317 	    !(priv->prev_ovf_flags & PAC1921_OVERFLOW_VPOV) &&
318 	    priv->ovf_enabled_events & PAC1921_OVERFLOW_VPOV) {
319 		iio_push_event(indio_dev,
320 			       IIO_UNMOD_EVENT_CODE(
321 				       IIO_POWER, PAC1921_CHAN_POWER,
322 				       IIO_EV_TYPE_THRESH, IIO_EV_DIR_RISING),
323 			       timestamp);
324 	}
325 
326 	priv->prev_ovf_flags = flags;
327 
328 	return 0;
329 }
330 
331 /*
332  * Read the value from a result register
333  *
334  * Result registers contain the most recent averaged values of Vbus, Vsense and
335  * Vpower. Each value is 10 bits wide and spread across two consecutive 8 bit
336  * registers, with 6 bit LSB zero padding.
337  */
pac1921_read_res(struct pac1921_priv * priv,unsigned long reg,u16 * val)338 static int pac1921_read_res(struct pac1921_priv *priv, unsigned long reg,
339 			    u16 *val)
340 {
341 	int ret = regmap_bulk_read(priv->regmap, reg, val, sizeof(*val));
342 	if (ret)
343 		return ret;
344 
345 	*val = FIELD_GET(PAC1921_RES_MASK, get_unaligned_be16(val));
346 
347 	return 0;
348 }
349 
pac1921_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)350 static int pac1921_read_raw(struct iio_dev *indio_dev,
351 			    struct iio_chan_spec const *chan, int *val,
352 			    int *val2, long mask)
353 {
354 	struct pac1921_priv *priv = iio_priv(indio_dev);
355 
356 	guard(mutex)(&priv->lock);
357 
358 	switch (mask) {
359 	case IIO_CHAN_INFO_RAW: {
360 		s64 ts;
361 		u16 res_val;
362 		int ret;
363 
364 		if (!pac1921_data_ready(priv))
365 			return -EBUSY;
366 
367 		ts = iio_get_time_ns(indio_dev);
368 
369 		ret = pac1921_check_push_overflow(indio_dev, ts);
370 		if (ret)
371 			return ret;
372 
373 		ret = pac1921_read_res(priv, chan->address, &res_val);
374 		if (ret)
375 			return ret;
376 
377 		*val = res_val;
378 
379 		return IIO_VAL_INT;
380 	}
381 	case IIO_CHAN_INFO_SCALE:
382 		switch (chan->channel) {
383 		case PAC1921_CHAN_VBUS:
384 			*val = pac1921_vbus_scales[priv->dv_gain][0];
385 			*val2 = pac1921_vbus_scales[priv->dv_gain][1];
386 			return IIO_VAL_INT_PLUS_NANO;
387 
388 		case PAC1921_CHAN_VSENSE:
389 			*val = pac1921_vsense_scales[priv->di_gain][0];
390 			*val2 = pac1921_vsense_scales[priv->di_gain][1];
391 			return IIO_VAL_INT_PLUS_NANO;
392 
393 		case PAC1921_CHAN_CURRENT:
394 			*val = priv->current_scales[priv->di_gain][0];
395 			*val2 = priv->current_scales[priv->di_gain][1];
396 			return IIO_VAL_INT_PLUS_NANO;
397 
398 		case PAC1921_CHAN_POWER: {
399 			/*
400 			 * Power scale factor in mW:
401 			 * Current scale (mA) * max_vbus (V) / dv_gain
402 			 */
403 
404 			/* Get current scale based on di_gain */
405 			int *curr_scale = priv->current_scales[priv->di_gain];
406 
407 			/* Convert current_scale from INT_PLUS_NANO to INT */
408 			s64 tmp = curr_scale[0] * (s64)NANO + curr_scale[1];
409 
410 			/* Multiply by max_vbus (V) / dv_gain */
411 			tmp *= PAC1921_MAX_VBUS_V >> priv->dv_gain;
412 
413 			/* Convert back to INT_PLUS_NANO */
414 			*val = div_s64_rem(tmp, NANO, val2);
415 
416 			return IIO_VAL_INT_PLUS_NANO;
417 		}
418 		default:
419 			return -EINVAL;
420 		}
421 
422 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
423 		*val = pac1921_int_num_samples[priv->n_samples];
424 		return IIO_VAL_INT;
425 
426 	case IIO_CHAN_INFO_SAMP_FREQ:
427 		/*
428 		 * The sampling frequency (Hz) is read-only and corresponds to
429 		 * how often the device provides integrated measurements into
430 		 * the result registers, thus it's 1/integration_period.
431 		 * The integration period depends on the number of integration
432 		 * samples, measurement resolution and post filters.
433 		 *
434 		 * 1/(integr_period_usecs/MICRO) = MICRO/integr_period_usecs
435 		 */
436 		*val = MICRO;
437 		*val2 = priv->integr_period_usecs;
438 		return IIO_VAL_FRACTIONAL;
439 
440 	default:
441 		return -EINVAL;
442 	}
443 }
444 
pac1921_read_avail(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,const int ** vals,int * type,int * length,long mask)445 static int pac1921_read_avail(struct iio_dev *indio_dev,
446 			      struct iio_chan_spec const *chan,
447 			      const int **vals, int *type, int *length,
448 			      long mask)
449 {
450 	switch (mask) {
451 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
452 		*type = IIO_VAL_INT;
453 		*vals = pac1921_int_num_samples;
454 		*length = ARRAY_SIZE(pac1921_int_num_samples);
455 		return IIO_AVAIL_LIST;
456 	default:
457 		return -EINVAL;
458 	}
459 }
460 
461 /*
462  * Perform configuration update sequence: set the device into read state, then
463  * write the config register and set the device back into integration state.
464  * Also reset integration start time and mark first integration to be yet
465  * completed.
466  *
467  * Must be called with lock held.
468  */
pac1921_update_cfg_reg(struct pac1921_priv * priv,unsigned int reg,unsigned int mask,unsigned int val)469 static int pac1921_update_cfg_reg(struct pac1921_priv *priv, unsigned int reg,
470 				  unsigned int mask, unsigned int val)
471 {
472 	/* Enter READ state before configuration */
473 	int ret = regmap_update_bits(priv->regmap, PAC1921_REG_INT_CFG,
474 				     PAC1921_INT_CFG_INTEN, 0);
475 	if (ret)
476 		return ret;
477 
478 	/* Update configuration value */
479 	ret = regmap_update_bits(priv->regmap, reg, mask, val);
480 	if (ret)
481 		return ret;
482 
483 	/* Re-enable integration */
484 	ret = regmap_update_bits(priv->regmap, PAC1921_REG_INT_CFG,
485 				 PAC1921_INT_CFG_INTEN, PAC1921_INT_CFG_INTEN);
486 	if (ret)
487 		return ret;
488 
489 	/*
490 	 * Reset integration started time and mark this integration period as
491 	 * the first one so that new measurements will be considered as valid
492 	 * only at the end of this integration period.
493 	 */
494 	priv->integr_started_time_jiffies = jiffies;
495 	priv->first_integr_done = false;
496 
497 	return 0;
498 }
499 
500 /*
501  * Retrieve the index of the given scale (represented by scale_val and
502  * scale_val2) from scales_tbl. The returned index (if found) is the log2 of
503  * the gain corresponding to the given scale.
504  *
505  * Must be called with lock held if the scales_tbl can change runtime (e.g. for
506  * the current scales table)
507  */
pac1921_lookup_scale(const int (* const scales_tbl)[2],size_t size,int scale_val,int scale_val2)508 static int pac1921_lookup_scale(const int (*const scales_tbl)[2], size_t size,
509 				int scale_val, int scale_val2)
510 {
511 	for (unsigned int i = 0; i < size; i++)
512 		if (scales_tbl[i][0] == scale_val &&
513 		    scales_tbl[i][1] == scale_val2)
514 			return i;
515 
516 	return -EINVAL;
517 }
518 
519 /*
520  * Configure device with the given gain (only if changed)
521  *
522  * Must be called with lock held.
523  */
pac1921_update_gain(struct pac1921_priv * priv,u8 * priv_val,u8 gain,unsigned int mask)524 static int pac1921_update_gain(struct pac1921_priv *priv, u8 *priv_val, u8 gain,
525 			       unsigned int mask)
526 {
527 	unsigned int reg_val;
528 	int ret;
529 
530 	if (*priv_val == gain)
531 		return 0;
532 
533 	reg_val = (gain << __ffs(mask)) & mask;
534 	ret = pac1921_update_cfg_reg(priv, PAC1921_REG_GAIN_CFG, mask, reg_val);
535 	if (ret)
536 		return ret;
537 
538 	*priv_val = gain;
539 
540 	return 0;
541 }
542 
543 /*
544  * Given a scale factor represented by scale_val and scale_val2 with format
545  * IIO_VAL_INT_PLUS_NANO, find the corresponding gain value and write it to the
546  * device.
547  *
548  * Must be called with lock held.
549  */
pac1921_update_gain_from_scale(struct pac1921_priv * priv,struct iio_chan_spec const * chan,int scale_val,int scale_val2)550 static int pac1921_update_gain_from_scale(struct pac1921_priv *priv,
551 					  struct iio_chan_spec const *chan,
552 					  int scale_val, int scale_val2)
553 {
554 	int ret;
555 
556 	switch (chan->channel) {
557 	case PAC1921_CHAN_VBUS:
558 		ret = pac1921_lookup_scale(pac1921_vbus_scales,
559 					   ARRAY_SIZE(pac1921_vbus_scales),
560 					   scale_val, scale_val2);
561 		if (ret < 0)
562 			return ret;
563 
564 		return pac1921_update_gain(priv, &priv->dv_gain, ret,
565 					   PAC1921_GAIN_DV_GAIN_MASK);
566 	case PAC1921_CHAN_VSENSE:
567 		ret = pac1921_lookup_scale(pac1921_vsense_scales,
568 					   ARRAY_SIZE(pac1921_vsense_scales),
569 					   scale_val, scale_val2);
570 		if (ret < 0)
571 			return ret;
572 
573 		return pac1921_update_gain(priv, &priv->di_gain, ret,
574 					   PAC1921_GAIN_DI_GAIN_MASK);
575 	case PAC1921_CHAN_CURRENT:
576 		ret = pac1921_lookup_scale(priv->current_scales,
577 					   ARRAY_SIZE(priv->current_scales),
578 					   scale_val, scale_val2);
579 		if (ret < 0)
580 			return ret;
581 
582 		return pac1921_update_gain(priv, &priv->di_gain, ret,
583 					   PAC1921_GAIN_DI_GAIN_MASK);
584 	default:
585 		return -EINVAL;
586 	}
587 }
588 
589 /*
590  * Retrieve the index of the given number of samples from the constant table.
591  * The returned index (if found) is the log2 of the given num_samples.
592  */
pac1921_lookup_int_num_samples(int num_samples)593 static int pac1921_lookup_int_num_samples(int num_samples)
594 {
595 	for (unsigned int i = 0; i < ARRAY_SIZE(pac1921_int_num_samples); i++)
596 		if (pac1921_int_num_samples[i] == num_samples)
597 			return i;
598 
599 	return -EINVAL;
600 }
601 
602 /*
603  * Update the device with the given number of integration samples.
604  *
605  * Must be called with lock held.
606  */
pac1921_update_int_num_samples(struct pac1921_priv * priv,int num_samples)607 static int pac1921_update_int_num_samples(struct pac1921_priv *priv,
608 					  int num_samples)
609 {
610 	unsigned int reg_val;
611 	u8 n_samples;
612 	int ret;
613 
614 	ret = pac1921_lookup_int_num_samples(num_samples);
615 	if (ret < 0)
616 		return ret;
617 
618 	n_samples = ret;
619 
620 	if (priv->n_samples == n_samples)
621 		return 0;
622 
623 	reg_val = FIELD_PREP(PAC1921_INT_CFG_SMPL_MASK, n_samples);
624 
625 	ret = pac1921_update_cfg_reg(priv, PAC1921_REG_INT_CFG,
626 				     PAC1921_INT_CFG_SMPL_MASK, reg_val);
627 	if (ret)
628 		return ret;
629 
630 	priv->n_samples = n_samples;
631 
632 	priv->integr_period_usecs = pac1921_int_periods_usecs[priv->n_samples];
633 
634 	return 0;
635 }
636 
pac1921_write_raw_get_fmt(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,long info)637 static int pac1921_write_raw_get_fmt(struct iio_dev *indio_dev,
638 				     struct iio_chan_spec const *chan,
639 				     long info)
640 {
641 	switch (info) {
642 	case IIO_CHAN_INFO_SCALE:
643 		return IIO_VAL_INT_PLUS_NANO;
644 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
645 		return IIO_VAL_INT;
646 	default:
647 		return -EINVAL;
648 	}
649 }
650 
pac1921_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)651 static int pac1921_write_raw(struct iio_dev *indio_dev,
652 			     struct iio_chan_spec const *chan, int val,
653 			     int val2, long mask)
654 {
655 	struct pac1921_priv *priv = iio_priv(indio_dev);
656 
657 	guard(mutex)(&priv->lock);
658 
659 	switch (mask) {
660 	case IIO_CHAN_INFO_SCALE:
661 		return pac1921_update_gain_from_scale(priv, chan, val, val2);
662 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
663 		return pac1921_update_int_num_samples(priv, val);
664 	default:
665 		return -EINVAL;
666 	}
667 }
668 
pac1921_read_label(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,char * label)669 static int pac1921_read_label(struct iio_dev *indio_dev,
670 			      struct iio_chan_spec const *chan, char *label)
671 {
672 	switch (chan->channel) {
673 	case PAC1921_CHAN_VBUS:
674 		return sprintf(label, "vbus\n");
675 	case PAC1921_CHAN_VSENSE:
676 		return sprintf(label, "vsense\n");
677 	case PAC1921_CHAN_CURRENT:
678 		return sprintf(label, "current\n");
679 	case PAC1921_CHAN_POWER:
680 		return sprintf(label, "power\n");
681 	default:
682 		return -EINVAL;
683 	}
684 }
685 
pac1921_read_event_config(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir)686 static int pac1921_read_event_config(struct iio_dev *indio_dev,
687 				     const struct iio_chan_spec *chan,
688 				     enum iio_event_type type,
689 				     enum iio_event_direction dir)
690 {
691 	struct pac1921_priv *priv = iio_priv(indio_dev);
692 
693 	guard(mutex)(&priv->lock);
694 
695 	switch (chan->channel) {
696 	case PAC1921_CHAN_VBUS:
697 		return !!(priv->ovf_enabled_events & PAC1921_OVERFLOW_VBOV);
698 	case PAC1921_CHAN_VSENSE:
699 	case PAC1921_CHAN_CURRENT:
700 		return !!(priv->ovf_enabled_events & PAC1921_OVERFLOW_VSOV);
701 	case PAC1921_CHAN_POWER:
702 		return !!(priv->ovf_enabled_events & PAC1921_OVERFLOW_VPOV);
703 	default:
704 		return -EINVAL;
705 	}
706 }
707 
pac1921_write_event_config(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir,bool state)708 static int pac1921_write_event_config(struct iio_dev *indio_dev,
709 				      const struct iio_chan_spec *chan,
710 				      enum iio_event_type type,
711 				      enum iio_event_direction dir,
712 				      bool state)
713 {
714 	struct pac1921_priv *priv = iio_priv(indio_dev);
715 	u8 ovf_bit;
716 
717 	guard(mutex)(&priv->lock);
718 
719 	switch (chan->channel) {
720 	case PAC1921_CHAN_VBUS:
721 		ovf_bit = PAC1921_OVERFLOW_VBOV;
722 		break;
723 	case PAC1921_CHAN_VSENSE:
724 	case PAC1921_CHAN_CURRENT:
725 		ovf_bit = PAC1921_OVERFLOW_VSOV;
726 		break;
727 	case PAC1921_CHAN_POWER:
728 		ovf_bit = PAC1921_OVERFLOW_VPOV;
729 		break;
730 	default:
731 		return -EINVAL;
732 	}
733 
734 	if (state)
735 		priv->ovf_enabled_events |= ovf_bit;
736 	else
737 		priv->ovf_enabled_events &= ~ovf_bit;
738 
739 	return 0;
740 }
741 
pac1921_read_event_value(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir,enum iio_event_info info,int * val,int * val2)742 static int pac1921_read_event_value(struct iio_dev *indio_dev,
743 				    const struct iio_chan_spec *chan,
744 				    enum iio_event_type type,
745 				    enum iio_event_direction dir,
746 				    enum iio_event_info info, int *val,
747 				    int *val2)
748 {
749 	switch (info) {
750 	case IIO_EV_INFO_VALUE:
751 		*val = PAC1921_RES_RESOLUTION;
752 		return IIO_VAL_INT;
753 	default:
754 		return -EINVAL;
755 	}
756 }
757 
758 static const struct iio_info pac1921_iio = {
759 	.read_raw = pac1921_read_raw,
760 	.read_avail = pac1921_read_avail,
761 	.write_raw = pac1921_write_raw,
762 	.write_raw_get_fmt = pac1921_write_raw_get_fmt,
763 	.read_label = pac1921_read_label,
764 	.read_event_config = pac1921_read_event_config,
765 	.write_event_config = pac1921_write_event_config,
766 	.read_event_value = pac1921_read_event_value,
767 };
768 
pac1921_read_shunt_resistor(struct iio_dev * indio_dev,uintptr_t private,const struct iio_chan_spec * chan,char * buf)769 static ssize_t pac1921_read_shunt_resistor(struct iio_dev *indio_dev,
770 					    uintptr_t private,
771 					    const struct iio_chan_spec *chan,
772 					    char *buf)
773 {
774 	struct pac1921_priv *priv = iio_priv(indio_dev);
775 	int vals[2];
776 
777 	if (chan->channel != PAC1921_CHAN_CURRENT)
778 		return -EINVAL;
779 
780 	guard(mutex)(&priv->lock);
781 
782 	vals[0] = priv->rshunt_uohm;
783 	vals[1] = MICRO;
784 
785 	return iio_format_value(buf, IIO_VAL_FRACTIONAL, 1, vals);
786 }
787 
pac1921_write_shunt_resistor(struct iio_dev * indio_dev,uintptr_t private,const struct iio_chan_spec * chan,const char * buf,size_t len)788 static ssize_t pac1921_write_shunt_resistor(struct iio_dev *indio_dev,
789 					    uintptr_t private,
790 					    const struct iio_chan_spec *chan,
791 					    const char *buf, size_t len)
792 {
793 	struct pac1921_priv *priv = iio_priv(indio_dev);
794 	u32 rshunt_uohm;
795 	int val, val_fract;
796 	int ret;
797 
798 	if (chan->channel != PAC1921_CHAN_CURRENT)
799 		return -EINVAL;
800 
801 	ret = iio_str_to_fixpoint(buf, 100000, &val, &val_fract);
802 	if (ret)
803 		return ret;
804 
805 	/*
806 	 * This check validates the shunt is not zero and does not surpass
807 	 * INT_MAX. The check is done before calculating in order to avoid
808 	 * val * MICRO overflowing.
809 	 */
810 	if ((!val && !val_fract) || val > INT_MAX / MICRO ||
811 	    (val == INT_MAX / MICRO && val_fract > INT_MAX % MICRO))
812 		return -EINVAL;
813 
814 	rshunt_uohm = val * MICRO + val_fract;
815 
816 	guard(mutex)(&priv->lock);
817 
818 	priv->rshunt_uohm = rshunt_uohm;
819 
820 	pac1921_calc_current_scales(priv);
821 
822 	return len;
823 }
824 
825 /*
826  * Emit on sysfs the list of available scales contained in scales_tbl
827  *
828  * TODO:: this function can be replaced with iio_format_avail_list() if the
829  * latter will ever be exported.
830  *
831  * Must be called with lock held if the scales_tbl can change runtime (e.g. for
832  * the current scales table)
833  */
pac1921_format_scale_avail(const int (* const scales_tbl)[2],size_t size,char * buf)834 static ssize_t pac1921_format_scale_avail(const int (*const scales_tbl)[2],
835 					  size_t size, char *buf)
836 {
837 	ssize_t len = 0;
838 
839 	for (unsigned int i = 0; i < size; i++) {
840 		if (i != 0) {
841 			len += sysfs_emit_at(buf, len, " ");
842 			if (len >= PAGE_SIZE)
843 				return -EFBIG;
844 		}
845 		len += sysfs_emit_at(buf, len, "%d.%09d", scales_tbl[i][0],
846 				     scales_tbl[i][1]);
847 		if (len >= PAGE_SIZE)
848 			return -EFBIG;
849 	}
850 
851 	len += sysfs_emit_at(buf, len, "\n");
852 	return len;
853 }
854 
855 /*
856  * Read available scales for a specific channel
857  *
858  * NOTE: using extended info insted of iio.read_avail() because access to
859  * current scales must be locked as they depend on shunt resistor which may
860  * change runtime. Caller of iio.read_avail() would access the table unlocked
861  * instead.
862  */
pac1921_read_scale_avail(struct iio_dev * indio_dev,uintptr_t private,const struct iio_chan_spec * chan,char * buf)863 static ssize_t pac1921_read_scale_avail(struct iio_dev *indio_dev,
864 					uintptr_t private,
865 					const struct iio_chan_spec *chan,
866 					char *buf)
867 {
868 	struct pac1921_priv *priv = iio_priv(indio_dev);
869 	const int (*scales_tbl)[2];
870 	size_t size;
871 
872 	switch (chan->channel) {
873 	case PAC1921_CHAN_VBUS:
874 		scales_tbl = pac1921_vbus_scales;
875 		size = ARRAY_SIZE(pac1921_vbus_scales);
876 		return pac1921_format_scale_avail(scales_tbl, size, buf);
877 
878 	case PAC1921_CHAN_VSENSE:
879 		scales_tbl = pac1921_vsense_scales;
880 		size = ARRAY_SIZE(pac1921_vsense_scales);
881 		return pac1921_format_scale_avail(scales_tbl, size, buf);
882 
883 	case PAC1921_CHAN_CURRENT: {
884 		guard(mutex)(&priv->lock);
885 		scales_tbl = priv->current_scales;
886 		size = ARRAY_SIZE(priv->current_scales);
887 		return pac1921_format_scale_avail(scales_tbl, size, buf);
888 	}
889 	default:
890 		return -EINVAL;
891 	}
892 }
893 
894 #define PAC1921_EXT_INFO_SCALE_AVAIL {					\
895 	.name = "scale_available",					\
896 	.read = pac1921_read_scale_avail,				\
897 	.shared = IIO_SEPARATE,						\
898 }
899 
900 static const struct iio_chan_spec_ext_info pac1921_ext_info_voltage[] = {
901 	PAC1921_EXT_INFO_SCALE_AVAIL,
902 	{}
903 };
904 
905 static const struct iio_chan_spec_ext_info pac1921_ext_info_current[] = {
906 	PAC1921_EXT_INFO_SCALE_AVAIL,
907 	{
908 		.name = "shunt_resistor",
909 		.read = pac1921_read_shunt_resistor,
910 		.write = pac1921_write_shunt_resistor,
911 		.shared = IIO_SEPARATE,
912 	},
913 	{}
914 };
915 
916 static const struct iio_event_spec pac1921_overflow_event[] = {
917 	{
918 		.type = IIO_EV_TYPE_THRESH,
919 		.dir = IIO_EV_DIR_RISING,
920 		.mask_shared_by_all = BIT(IIO_EV_INFO_VALUE),
921 		.mask_separate = BIT(IIO_EV_INFO_ENABLE),
922 	},
923 };
924 
925 static const struct iio_chan_spec pac1921_channels[] = {
926 	{
927 		.type = IIO_VOLTAGE,
928 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
929 				      BIT(IIO_CHAN_INFO_SCALE),
930 		.info_mask_shared_by_all =
931 			BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO) |
932 			BIT(IIO_CHAN_INFO_SAMP_FREQ),
933 		.info_mask_shared_by_all_available =
934 			BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),
935 		.channel = PAC1921_CHAN_VBUS,
936 		.address = PAC1921_REG_VBUS,
937 		.scan_index = PAC1921_CHAN_VBUS,
938 		.scan_type = {
939 			.sign = 'u',
940 			.realbits = 10,
941 			.storagebits = 16,
942 			.endianness = IIO_CPU
943 		},
944 		.indexed = 1,
945 		.event_spec = pac1921_overflow_event,
946 		.num_event_specs = ARRAY_SIZE(pac1921_overflow_event),
947 		.ext_info = pac1921_ext_info_voltage,
948 	},
949 	{
950 		.type = IIO_VOLTAGE,
951 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
952 				      BIT(IIO_CHAN_INFO_SCALE),
953 		.info_mask_shared_by_all =
954 			BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO) |
955 			BIT(IIO_CHAN_INFO_SAMP_FREQ),
956 		.info_mask_shared_by_all_available =
957 			BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),
958 		.channel = PAC1921_CHAN_VSENSE,
959 		.address = PAC1921_REG_VSENSE,
960 		.scan_index = PAC1921_CHAN_VSENSE,
961 		.scan_type = {
962 			.sign = 'u',
963 			.realbits = 10,
964 			.storagebits = 16,
965 			.endianness = IIO_CPU
966 		},
967 		.indexed = 1,
968 		.event_spec = pac1921_overflow_event,
969 		.num_event_specs = ARRAY_SIZE(pac1921_overflow_event),
970 		.ext_info = pac1921_ext_info_voltage,
971 	},
972 	{
973 		.type = IIO_CURRENT,
974 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
975 				      BIT(IIO_CHAN_INFO_SCALE),
976 		.info_mask_shared_by_all =
977 			BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO) |
978 			BIT(IIO_CHAN_INFO_SAMP_FREQ),
979 		.info_mask_shared_by_all_available =
980 			BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),
981 		.channel = PAC1921_CHAN_CURRENT,
982 		.address = PAC1921_REG_VSENSE,
983 		.scan_index = PAC1921_CHAN_CURRENT,
984 		.scan_type = {
985 			.sign = 'u',
986 			.realbits = 10,
987 			.storagebits = 16,
988 			.endianness = IIO_CPU
989 		},
990 		.event_spec = pac1921_overflow_event,
991 		.num_event_specs = ARRAY_SIZE(pac1921_overflow_event),
992 		.ext_info = pac1921_ext_info_current,
993 	},
994 	{
995 		.type = IIO_POWER,
996 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
997 				      BIT(IIO_CHAN_INFO_SCALE),
998 		.info_mask_shared_by_all =
999 			BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO) |
1000 			BIT(IIO_CHAN_INFO_SAMP_FREQ),
1001 		.info_mask_shared_by_all_available =
1002 			BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),
1003 		.channel = PAC1921_CHAN_POWER,
1004 		.address = PAC1921_REG_VPOWER,
1005 		.scan_index = PAC1921_CHAN_POWER,
1006 		.scan_type = {
1007 			.sign = 'u',
1008 			.realbits = 10,
1009 			.storagebits = 16,
1010 			.endianness = IIO_CPU
1011 		},
1012 		.event_spec = pac1921_overflow_event,
1013 		.num_event_specs = ARRAY_SIZE(pac1921_overflow_event),
1014 	},
1015 	IIO_CHAN_SOFT_TIMESTAMP(PAC1921_NUM_MEAS_CHANS),
1016 };
1017 
pac1921_trigger_handler(int irq,void * p)1018 static irqreturn_t pac1921_trigger_handler(int irq, void *p)
1019 {
1020 	struct iio_poll_func *pf = p;
1021 	struct iio_dev *idev = pf->indio_dev;
1022 	struct pac1921_priv *priv = iio_priv(idev);
1023 	int ret;
1024 	int bit;
1025 	int ch = 0;
1026 
1027 	guard(mutex)(&priv->lock);
1028 
1029 	if (!pac1921_data_ready(priv))
1030 		goto done;
1031 
1032 	ret = pac1921_check_push_overflow(idev, pf->timestamp);
1033 	if (ret)
1034 		goto done;
1035 
1036 	iio_for_each_active_channel(idev, bit) {
1037 		u16 val;
1038 
1039 		ret = pac1921_read_res(priv, idev->channels[ch].address, &val);
1040 		if (ret)
1041 			goto done;
1042 
1043 		priv->scan.chan[ch++] = val;
1044 	}
1045 
1046 	iio_push_to_buffers_with_timestamp(idev, &priv->scan, pf->timestamp);
1047 
1048 done:
1049 	iio_trigger_notify_done(idev->trig);
1050 
1051 	return IRQ_HANDLED;
1052 }
1053 
1054 /*
1055  * Initialize device by writing initial configuration and putting it into
1056  * integration state.
1057  *
1058  * Must be called with lock held when called after first initialization
1059  * (e.g. from pm resume)
1060  */
pac1921_init(struct pac1921_priv * priv)1061 static int pac1921_init(struct pac1921_priv *priv)
1062 {
1063 	unsigned int val;
1064 	int ret;
1065 
1066 	/* Enter READ state before configuration */
1067 	ret = regmap_update_bits(priv->regmap, PAC1921_REG_INT_CFG,
1068 				 PAC1921_INT_CFG_INTEN, 0);
1069 	if (ret)
1070 		return ret;
1071 
1072 	/* Configure gains, use 14-bits measurement resolution (HW default) */
1073 	val = FIELD_PREP(PAC1921_GAIN_DI_GAIN_MASK, priv->di_gain) |
1074 	      FIELD_PREP(PAC1921_GAIN_DV_GAIN_MASK, priv->dv_gain);
1075 	ret = regmap_write(priv->regmap, PAC1921_REG_GAIN_CFG, val);
1076 	if (ret)
1077 		return ret;
1078 
1079 	/*
1080 	 * Configure integration:
1081 	 * - num of integration samples
1082 	 * - filters enabled (HW default)
1083 	 * - set READ/INT pin override (RIOV) to control operation mode via
1084 	 *   register instead of pin
1085 	 */
1086 	val = FIELD_PREP(PAC1921_INT_CFG_SMPL_MASK, priv->n_samples) |
1087 	      PAC1921_INT_CFG_VSFEN | PAC1921_INT_CFG_VBFEN |
1088 	      PAC1921_INT_CFG_RIOV;
1089 	ret = regmap_write(priv->regmap, PAC1921_REG_INT_CFG, val);
1090 	if (ret)
1091 		return ret;
1092 
1093 	/*
1094 	 * Init control register:
1095 	 * - VPower free run integration mode
1096 	 * - OUT pin full scale range: 3V (HW default)
1097 	 * - no timeout, no sleep, no sleep override, no recalc (HW defaults)
1098 	 */
1099 	val = FIELD_PREP(PAC1921_CONTROL_MXSL_MASK,
1100 			 PAC1921_MXSL_VPOWER_FREE_RUN);
1101 	ret = regmap_write(priv->regmap, PAC1921_REG_CONTROL, val);
1102 	if (ret)
1103 		return ret;
1104 
1105 	/* Enable integration */
1106 	ret = regmap_update_bits(priv->regmap, PAC1921_REG_INT_CFG,
1107 				 PAC1921_INT_CFG_INTEN, PAC1921_INT_CFG_INTEN);
1108 	if (ret)
1109 		return ret;
1110 
1111 	priv->first_integr_started = true;
1112 	priv->integr_started_time_jiffies = jiffies;
1113 	priv->integr_period_usecs = pac1921_int_periods_usecs[priv->n_samples];
1114 
1115 	return 0;
1116 }
1117 
pac1921_suspend(struct device * dev)1118 static int pac1921_suspend(struct device *dev)
1119 {
1120 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
1121 	struct pac1921_priv *priv = iio_priv(indio_dev);
1122 	int ret;
1123 
1124 	guard(mutex)(&priv->lock);
1125 
1126 	priv->first_integr_started = false;
1127 	priv->first_integr_done = false;
1128 
1129 	ret = regmap_update_bits(priv->regmap, PAC1921_REG_INT_CFG,
1130 				     PAC1921_INT_CFG_INTEN, 0);
1131 	if (ret)
1132 		return ret;
1133 
1134 	ret = regmap_update_bits(priv->regmap, PAC1921_REG_CONTROL,
1135 				 PAC1921_CONTROL_SLEEP, PAC1921_CONTROL_SLEEP);
1136 	if (ret)
1137 		return ret;
1138 
1139 	return regulator_disable(priv->vdd);
1140 
1141 }
1142 
pac1921_resume(struct device * dev)1143 static int pac1921_resume(struct device *dev)
1144 {
1145 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
1146 	struct pac1921_priv *priv = iio_priv(indio_dev);
1147 	int ret;
1148 
1149 	guard(mutex)(&priv->lock);
1150 
1151 	ret = regulator_enable(priv->vdd);
1152 	if (ret)
1153 		return ret;
1154 
1155 	msleep(PAC1921_POWERUP_TIME_MS);
1156 
1157 	return pac1921_init(priv);
1158 }
1159 
1160 static DEFINE_SIMPLE_DEV_PM_OPS(pac1921_pm_ops, pac1921_suspend,
1161 				pac1921_resume);
1162 
pac1921_regulator_disable(void * data)1163 static void pac1921_regulator_disable(void *data)
1164 {
1165 	struct regulator *regulator = data;
1166 
1167 	regulator_disable(regulator);
1168 }
1169 
1170 /*
1171  * Documentation related to the ACPI device definition
1172  * https://ww1.microchip.com/downloads/aemDocuments/documents/OTH/ApplicationNotes/ApplicationNotes/PAC193X-Integration-Notes-for-Microsoft-Windows-10-and-Windows-11-Driver-Support-DS00002534.pdf
1173  */
pac1921_match_acpi_device(struct iio_dev * indio_dev)1174 static int pac1921_match_acpi_device(struct iio_dev *indio_dev)
1175 {
1176 	acpi_handle handle;
1177 	union acpi_object *status;
1178 	char *label;
1179 	struct pac1921_priv *priv = iio_priv(indio_dev);
1180 	struct device *dev = &priv->client->dev;
1181 
1182 	handle = ACPI_HANDLE(dev);
1183 
1184 	status = acpi_evaluate_dsm(handle, &pac1921_guid, 1,
1185 				   PAC1921_ACPI_GET_uOHMS_VALS, NULL);
1186 	if (!status)
1187 		return dev_err_probe(dev, -EINVAL,
1188 				     "Could not read shunt from ACPI table\n");
1189 
1190 	priv->rshunt_uohm = status->package.elements[0].integer.value;
1191 	ACPI_FREE(status);
1192 
1193 	status = acpi_evaluate_dsm(handle, &pac1921_guid, 1,
1194 				   PAC1921_ACPI_GET_LABEL, NULL);
1195 	if (!status)
1196 		return dev_err_probe(dev, -EINVAL,
1197 				     "Could not read label from ACPI table\n");
1198 
1199 	label = devm_kstrdup(dev, status->package.elements[0].string.pointer,
1200 			     GFP_KERNEL);
1201 	ACPI_FREE(status);
1202 	if (!label)
1203 		return -ENOMEM;
1204 
1205 	indio_dev->label = label;
1206 
1207 	return 0;
1208 }
1209 
pac1921_parse_of_fw(struct iio_dev * indio_dev)1210 static int pac1921_parse_of_fw(struct iio_dev *indio_dev)
1211 {
1212 	int ret;
1213 	struct pac1921_priv *priv = iio_priv(indio_dev);
1214 	struct device *dev = &priv->client->dev;
1215 
1216 	ret = device_property_read_u32(dev, "shunt-resistor-micro-ohms",
1217 				       &priv->rshunt_uohm);
1218 	if (ret)
1219 		return dev_err_probe(dev, ret,
1220 				     "Cannot read shunt resistor property\n");
1221 
1222 	return 0;
1223 }
1224 
pac1921_probe(struct i2c_client * client)1225 static int pac1921_probe(struct i2c_client *client)
1226 {
1227 	struct device *dev = &client->dev;
1228 	struct pac1921_priv *priv;
1229 	struct iio_dev *indio_dev;
1230 	int ret;
1231 
1232 	indio_dev = devm_iio_device_alloc(dev, sizeof(*priv));
1233 	if (!indio_dev)
1234 		return -ENOMEM;
1235 
1236 	priv = iio_priv(indio_dev);
1237 	priv->client = client;
1238 	i2c_set_clientdata(client, indio_dev);
1239 
1240 	priv->regmap = devm_regmap_init_i2c(client, &pac1921_regmap_config);
1241 	if (IS_ERR(priv->regmap))
1242 		return dev_err_probe(dev, PTR_ERR(priv->regmap),
1243 				     "Cannot initialize register map\n");
1244 
1245 	ret = devm_mutex_init(dev, &priv->lock);
1246 	if (ret)
1247 		return ret;
1248 
1249 	priv->dv_gain = PAC1921_DEFAULT_DV_GAIN;
1250 	priv->di_gain = PAC1921_DEFAULT_DI_GAIN;
1251 	priv->n_samples = PAC1921_DEFAULT_NUM_SAMPLES;
1252 
1253 	if (is_acpi_device_node(dev->fwnode))
1254 		ret = pac1921_match_acpi_device(indio_dev);
1255 	else
1256 		ret = pac1921_parse_of_fw(indio_dev);
1257 	if (ret)
1258 		return dev_err_probe(dev, ret,
1259 				     "Parameter parsing error\n");
1260 
1261 	if (priv->rshunt_uohm == 0 || priv->rshunt_uohm > INT_MAX)
1262 		return dev_err_probe(dev, -EINVAL,
1263 				     "Invalid shunt resistor: %u\n",
1264 				     priv->rshunt_uohm);
1265 
1266 	pac1921_calc_current_scales(priv);
1267 
1268 	priv->vdd = devm_regulator_get(dev, "vdd");
1269 	if (IS_ERR(priv->vdd))
1270 		return dev_err_probe(dev, PTR_ERR(priv->vdd),
1271 				     "Cannot get vdd regulator\n");
1272 
1273 	ret = regulator_enable(priv->vdd);
1274 	if (ret)
1275 		return dev_err_probe(dev, ret, "Cannot enable vdd regulator\n");
1276 
1277 	ret = devm_add_action_or_reset(dev, pac1921_regulator_disable,
1278 				       priv->vdd);
1279 	if (ret)
1280 		return dev_err_probe(dev, ret,
1281 			"Cannot add action for vdd regulator disposal\n");
1282 
1283 	msleep(PAC1921_POWERUP_TIME_MS);
1284 
1285 	ret = pac1921_init(priv);
1286 	if (ret)
1287 		return dev_err_probe(dev, ret, "Cannot initialize device\n");
1288 
1289 	priv->iio_info = pac1921_iio;
1290 
1291 	indio_dev->name = "pac1921";
1292 	indio_dev->info = &priv->iio_info;
1293 	indio_dev->modes = INDIO_DIRECT_MODE;
1294 	indio_dev->channels = pac1921_channels;
1295 	indio_dev->num_channels = ARRAY_SIZE(pac1921_channels);
1296 
1297 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev,
1298 					      &iio_pollfunc_store_time,
1299 					      &pac1921_trigger_handler, NULL);
1300 	if (ret)
1301 		return dev_err_probe(dev, ret,
1302 				     "Cannot setup IIO triggered buffer\n");
1303 
1304 	ret = devm_iio_device_register(dev, indio_dev);
1305 	if (ret)
1306 		return dev_err_probe(dev, ret, "Cannot register IIO device\n");
1307 
1308 	return 0;
1309 }
1310 
1311 static const struct i2c_device_id pac1921_id[] = {
1312 	{ .name = "pac1921", 0 },
1313 	{ }
1314 };
1315 MODULE_DEVICE_TABLE(i2c, pac1921_id);
1316 
1317 static const struct of_device_id pac1921_of_match[] = {
1318 	{ .compatible = "microchip,pac1921" },
1319 	{ }
1320 };
1321 MODULE_DEVICE_TABLE(of, pac1921_of_match);
1322 
1323 static const struct acpi_device_id pac1921_acpi_match[] = {
1324 	{ "MCHP1921" },
1325 	{ }
1326 };
1327 MODULE_DEVICE_TABLE(acpi, pac1921_acpi_match);
1328 
1329 static struct i2c_driver pac1921_driver = {
1330 	.driver	 = {
1331 		.name = "pac1921",
1332 		.pm = pm_sleep_ptr(&pac1921_pm_ops),
1333 		.of_match_table = pac1921_of_match,
1334 		.acpi_match_table = pac1921_acpi_match,
1335 	},
1336 	.probe = pac1921_probe,
1337 	.id_table = pac1921_id,
1338 };
1339 
1340 module_i2c_driver(pac1921_driver);
1341 
1342 MODULE_AUTHOR("Matteo Martelli <matteomartelli3@gmail.com>");
1343 MODULE_DESCRIPTION("IIO driver for PAC1921 High-Side Power/Current Monitor");
1344 MODULE_LICENSE("GPL");
1345