1 /*
2  * Copyright (c) 2023 Renesas Electronics Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define DT_DRV_COMPAT renesas_smartbond_adc
8 
9 #define ADC_CONTEXT_USES_KERNEL_TIMER
10 #include <DA1469xAB.h>
11 #include <da1469x_pd.h>
12 #include "adc_context.h"
13 #include <zephyr/dt-bindings/adc/smartbond-adc.h>
14 
15 #define LOG_LEVEL CONFIG_ADC_LOG_LEVEL
16 #include <zephyr/logging/log.h>
17 #include <zephyr/irq.h>
18 #include <zephyr/sys/math_extras.h>
19 #include <zephyr/drivers/clock_control.h>
20 #include <zephyr/drivers/clock_control/smartbond_clock_control.h>
21 #include <zephyr/drivers/gpio.h>
22 #include <zephyr/drivers/pinctrl.h>
23 #include <zephyr/pm/device.h>
24 #include <zephyr/pm/policy.h>
25 #include <zephyr/pm/device_runtime.h>
26 
27 LOG_MODULE_REGISTER(adc_smartbond_adc);
28 
29 struct adc_smartbond_cfg {
30 	const struct pinctrl_dev_config *pcfg;
31 };
32 
33 struct adc_smartbond_data {
34 	struct adc_context ctx;
35 
36 	/* Buffer to store channel data */
37 	uint16_t *buffer;
38 	/* Copy of channel mask from sequence */
39 	uint32_t channel_read_mask;
40 	/* Number of bits in sequence channels */
41 	uint8_t sequence_channel_count;
42 	/* Index in buffer to store current value to */
43 	uint8_t result_index;
44 };
45 
46 #define SMARTBOND_ADC_CHANNEL_COUNT	8
47 
48 /*
49  * Channels are handled by software this array holds individual
50  * settings for each channel that must be applied before conversion.
51  */
52 struct adc_smartbond_channel_cfg {
53 	uint32_t gp_adc_ctrl_reg;
54 	uint32_t gp_adc_ctrl2_reg;
55 } m_channels[SMARTBOND_ADC_CHANNEL_COUNT];
56 
57 /* Implementation of the ADC driver API function: adc_channel_setup. */
adc_smartbond_channel_setup(const struct device * dev,const struct adc_channel_cfg * channel_cfg)58 static int adc_smartbond_channel_setup(const struct device *dev,
59 				       const struct adc_channel_cfg *channel_cfg)
60 {
61 	uint8_t channel_id = channel_cfg->channel_id;
62 	struct adc_smartbond_channel_cfg *config = &m_channels[channel_id];
63 
64 	if (channel_id >= SMARTBOND_ADC_CHANNEL_COUNT) {
65 		return -EINVAL;
66 	}
67 
68 	if (channel_cfg->acquisition_time != ADC_ACQ_TIME_DEFAULT) {
69 		LOG_ERR("Selected ADC acquisition time is not valid");
70 		return -EINVAL;
71 	}
72 
73 	if (channel_cfg->differential) {
74 		if (channel_cfg->input_positive != SMARTBOND_GPADC_P1_09 &&
75 		    channel_cfg->input_positive != SMARTBOND_GPADC_P0_08) {
76 			LOG_ERR("Differential channels supported only for P1_09 and P0_08");
77 			return -EINVAL;
78 		}
79 	}
80 
81 	switch (channel_cfg->gain) {
82 	case ADC_GAIN_1_3:
83 		/* Turn on attenuator and increase sample time to 32 cycles */
84 		config->gp_adc_ctrl2_reg = 0x101;
85 		break;
86 	case ADC_GAIN_1:
87 		config->gp_adc_ctrl2_reg = 0;
88 		break;
89 	default:
90 		LOG_ERR("Selected ADC gain is not valid");
91 		return -EINVAL;
92 	}
93 
94 	switch (channel_cfg->reference) {
95 	case ADC_REF_INTERNAL:
96 		break;
97 	default:
98 		LOG_ERR("Selected ADC reference is not valid");
99 		return -EINVAL;
100 	}
101 
102 	config->gp_adc_ctrl_reg =
103 		channel_cfg->input_positive << GPADC_GP_ADC_CTRL_REG_GP_ADC_SEL_Pos;
104 	if (!channel_cfg->differential) {
105 		config->gp_adc_ctrl_reg |= GPADC_GP_ADC_CTRL_REG_GP_ADC_SE_Msk;
106 	}
107 
108 	return 0;
109 }
110 
gpadc_smartbond_pm_policy_state_lock_get(const struct device * dev,struct adc_smartbond_data * data)111 static inline void gpadc_smartbond_pm_policy_state_lock_get(const struct device *dev,
112 					      struct adc_smartbond_data *data)
113 {
114 #if defined(CONFIG_PM_DEVICE)
115 	pm_device_runtime_get(dev);
116 	/*
117 	 * Prevent the SoC from entering the normal sleep state.
118 	 */
119 	pm_policy_state_lock_get(PM_STATE_STANDBY, PM_ALL_SUBSTATES);
120 #endif
121 }
122 
gpadc_smartbond_pm_policy_state_lock_put(const struct device * dev,struct adc_smartbond_data * data)123 static inline void gpadc_smartbond_pm_policy_state_lock_put(const struct device *dev,
124 					      struct adc_smartbond_data *data)
125 {
126 #if defined(CONFIG_PM_DEVICE)
127 	/*
128 	 * Allow the SoC to enter the normal sleep state once GPADC is done.
129 	 */
130 	pm_policy_state_lock_put(PM_STATE_STANDBY, PM_ALL_SUBSTATES);
131 	pm_device_runtime_put(dev);
132 #endif
133 }
134 
135 #define PER_CHANNEL_ADC_CONFIG_MASK (GPADC_GP_ADC_CTRL_REG_GP_ADC_SEL_Msk |	\
136 				     GPADC_GP_ADC_CTRL_REG_GP_ADC_SE_Msk)
137 
pop_count(uint32_t n)138 static int pop_count(uint32_t n)
139 {
140 	return __builtin_popcount(n);
141 }
142 
adc_context_start_sampling(struct adc_context * ctx)143 static void adc_context_start_sampling(struct adc_context *ctx)
144 {
145 	uint32_t val;
146 	struct adc_smartbond_data *data =
147 		CONTAINER_OF(ctx, struct adc_smartbond_data, ctx);
148 	/* Extract lower channel from sequence mask */
149 	int current_channel = u32_count_trailing_zeros(data->channel_read_mask);
150 
151 	if (ctx->sequence.calibrate) {
152 		/* TODO: Add calibration code */
153 	} else {
154 		val = GPADC->GP_ADC_CTRL_REG & ~PER_CHANNEL_ADC_CONFIG_MASK;
155 		val |= m_channels[current_channel].gp_adc_ctrl_reg;
156 		val |= GPADC_GP_ADC_CTRL_REG_GP_ADC_START_Msk |
157 		       GPADC_GP_ADC_CTRL_REG_GP_ADC_MINT_Msk;
158 
159 		GPADC->GP_ADC_CTRL2_REG = m_channels[current_channel].gp_adc_ctrl2_reg;
160 		GPADC->GP_ADC_CTRL_REG = val;
161 	}
162 }
163 
adc_context_update_buffer_pointer(struct adc_context * ctx,bool repeat)164 static void adc_context_update_buffer_pointer(struct adc_context *ctx,
165 					      bool repeat)
166 {
167 	struct adc_smartbond_data *data =
168 		CONTAINER_OF(ctx, struct adc_smartbond_data, ctx);
169 
170 	if (!repeat) {
171 		data->buffer += data->sequence_channel_count;
172 	}
173 }
174 
check_buffer_size(const struct adc_sequence * sequence,uint8_t active_channels)175 static int check_buffer_size(const struct adc_sequence *sequence,
176 			     uint8_t active_channels)
177 {
178 	size_t needed_buffer_size;
179 
180 	needed_buffer_size = active_channels * sizeof(uint16_t);
181 	if (sequence->options) {
182 		needed_buffer_size *= (1 + sequence->options->extra_samplings);
183 	}
184 
185 	if (sequence->buffer_size < needed_buffer_size) {
186 		LOG_ERR("Provided buffer is too small (%u/%u)",
187 			sequence->buffer_size, needed_buffer_size);
188 		return -ENOMEM;
189 	}
190 
191 	return 0;
192 }
193 
start_read(const struct device * dev,const struct adc_sequence * sequence)194 static int start_read(const struct device *dev,
195 		      const struct adc_sequence *sequence)
196 {
197 	int error;
198 	struct adc_smartbond_data *data = dev->data;
199 
200 	if (sequence->oversampling > 7U) {
201 		LOG_ERR("Invalid oversampling");
202 		return -EINVAL;
203 	}
204 
205 	if ((sequence->channels == 0) ||
206 	    ((sequence->channels & ~BIT_MASK(SMARTBOND_ADC_CHANNEL_COUNT)) != 0)) {
207 		LOG_ERR("Channel scanning is not supported");
208 		return -EINVAL;
209 	}
210 
211 	if (sequence->resolution < 8 || sequence->resolution > 15) {
212 		LOG_ERR("ADC resolution value %d is not valid",
213 			sequence->resolution);
214 		return -EINVAL;
215 	}
216 
217 	error = check_buffer_size(sequence, 1);
218 	if (error) {
219 		return error;
220 	}
221 
222 	data->buffer = sequence->buffer;
223 	data->channel_read_mask = sequence->channels;
224 	data->sequence_channel_count = pop_count(sequence->channels);
225 	data->result_index = 0;
226 
227 	adc_context_start_read(&data->ctx, sequence);
228 
229 	error = adc_context_wait_for_completion(&data->ctx);
230 	return error;
231 }
232 
adc_smartbond_isr(const struct device * dev)233 static void adc_smartbond_isr(const struct device *dev)
234 {
235 	struct adc_smartbond_data *data = dev->data;
236 	int current_channel = u32_count_trailing_zeros(data->channel_read_mask);
237 
238 	GPADC->GP_ADC_CLEAR_INT_REG = 0;
239 	/* Store current channel value, result is left justified, move bits right */
240 	data->buffer[data->result_index++] = ((uint16_t)GPADC->GP_ADC_RESULT_REG) >>
241 		(16 - data->ctx.sequence.resolution);
242 	/* Exclude channel from mask for further reading */
243 	data->channel_read_mask ^= 1 << current_channel;
244 
245 	if (data->channel_read_mask == 0) {
246 		gpadc_smartbond_pm_policy_state_lock_put(dev, data);
247 		adc_context_on_sampling_done(&data->ctx, dev);
248 	} else {
249 		adc_context_start_sampling(&data->ctx);
250 	}
251 
252 	LOG_DBG("%s ISR triggered.", dev->name);
253 }
254 
255 /* Implementation of the ADC driver API function: adc_read. */
adc_smartbond_read(const struct device * dev,const struct adc_sequence * sequence)256 static int adc_smartbond_read(const struct device *dev,
257 			      const struct adc_sequence *sequence)
258 {
259 	int error;
260 	struct adc_smartbond_data *data = dev->data;
261 
262 	adc_context_lock(&data->ctx, false, NULL);
263 	gpadc_smartbond_pm_policy_state_lock_get(dev, data);
264 	error = start_read(dev, sequence);
265 	adc_context_release(&data->ctx, error);
266 
267 	return error;
268 }
269 
270 #if defined(CONFIG_ADC_ASYNC)
271 /* Implementation of the ADC driver API function: adc_read_sync. */
adc_smartbond_read_async(const struct device * dev,const struct adc_sequence * sequence,struct k_poll_signal * async)272 static int adc_smartbond_read_async(const struct device *dev,
273 				    const struct adc_sequence *sequence,
274 				    struct k_poll_signal *async)
275 {
276 	struct adc_smartbond_data *data = dev->data;
277 	int error;
278 
279 	adc_context_lock(&data->ctx, true, async);
280 	gpadc_smartbond_pm_policy_state_lock_get(dev, data);
281 	error = start_read(dev, sequence);
282 	adc_context_release(&data->ctx, error);
283 
284 	return error;
285 }
286 #endif /* CONFIG_ADC_ASYNC */
287 
gpadc_smartbond_resume(const struct device * dev)288 static int gpadc_smartbond_resume(const struct device *dev)
289 {
290 	int ret, rate;
291 	const struct adc_smartbond_cfg *config = dev->config;
292 	const struct device *clock_dev = DEVICE_DT_GET(DT_NODELABEL(osc));
293 
294 	da1469x_pd_acquire(MCU_PD_DOMAIN_PER);
295 
296 	/* Get current clock to determine GP_ADC_EN_DEL */
297 	clock_control_get_rate(clock_dev, (clock_control_subsys_t)SMARTBOND_CLK_SYS_CLK, &rate);
298 	GPADC->GP_ADC_CTRL3_REG = (rate/1600000)&0xff;
299 
300 	GPADC->GP_ADC_CTRL_REG = GPADC_GP_ADC_CTRL_REG_GP_ADC_EN_Msk;
301 
302 	/*
303 	 * Configure dt provided device signals when available.
304 	 * pinctrl is optional so ENOENT is not setup failure.
305 	 */
306 	ret = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
307 	if (ret < 0 && ret != -ENOENT) {
308 		/* Disable the GPADC LDO */
309 		GPADC->GP_ADC_CTRL_REG = 0;
310 
311 		/* Release the peripheral domain */
312 		da1469x_pd_release(MCU_PD_DOMAIN_PER);
313 
314 		LOG_ERR("ADC pinctrl setup failed (%d)", ret);
315 		return ret;
316 	}
317 
318 	return 0;
319 }
320 
321 #ifdef CONFIG_PM_DEVICE
gpadc_smartbond_suspend(const struct device * dev)322 static int gpadc_smartbond_suspend(const struct device *dev)
323 {
324 	int ret;
325 	const struct adc_smartbond_cfg *config = dev->config;
326 
327 	/* Disable the GPADC LDO */
328 	GPADC->GP_ADC_CTRL_REG = 0;
329 
330 	/* Release the peripheral domain */
331 	da1469x_pd_release(MCU_PD_DOMAIN_PER);
332 
333 	/*
334 	 * Configure dt provided device signals for sleep.
335 	 * pinctrl is optional so ENOENT is not setup failure.
336 	 */
337 	ret = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_SLEEP);
338 	if (ret < 0 && ret != -ENOENT) {
339 		LOG_WRN("Failed to configure the GPADC pins to inactive state");
340 		return ret;
341 	}
342 
343 	return 0;
344 }
345 
gpadc_smartbond_pm_action(const struct device * dev,enum pm_device_action action)346 static int gpadc_smartbond_pm_action(const struct device *dev,
347 				   enum pm_device_action action)
348 {
349 	int ret;
350 
351 	switch (action) {
352 	case PM_DEVICE_ACTION_RESUME:
353 		ret = gpadc_smartbond_resume(dev);
354 		break;
355 	case PM_DEVICE_ACTION_SUSPEND:
356 		ret = gpadc_smartbond_suspend(dev);
357 		break;
358 	default:
359 		return -ENOTSUP;
360 	}
361 	return ret;
362 }
363 #endif /* CONFIG_PM_DEVICE */
364 
adc_smartbond_init(const struct device * dev)365 static int adc_smartbond_init(const struct device *dev)
366 {
367 	int ret;
368 	struct adc_smartbond_data *data = dev->data;
369 
370 #ifdef CONFIG_PM_DEVICE_RUNTIME
371 	/* Make sure device state is marked as suspended */
372 	pm_device_init_suspended(dev);
373 
374 	ret = pm_device_runtime_enable(dev);
375 
376 #else
377 	ret = gpadc_smartbond_resume(dev);
378 
379 #endif
380 
381 	IRQ_CONNECT(DT_INST_IRQN(0), DT_INST_IRQ(0, priority),
382 		    adc_smartbond_isr, DEVICE_DT_INST_GET(0), 0);
383 
384 	NVIC_ClearPendingIRQ(DT_INST_IRQN(0));
385 	NVIC_EnableIRQ(DT_INST_IRQN(0));
386 
387 	adc_context_unlock_unconditionally(&data->ctx);
388 
389 	return ret;
390 }
391 
392 static DEVICE_API(adc, adc_smartbond_driver_api) = {
393 	.channel_setup = adc_smartbond_channel_setup,
394 	.read          = adc_smartbond_read,
395 #ifdef CONFIG_ADC_ASYNC
396 	.read_async    = adc_smartbond_read_async,
397 #endif
398 	.ref_internal  = 1200,
399 };
400 
401 /*
402  * There is only one instance on supported SoCs, so inst is guaranteed
403  * to be 0 if any instance is okay. (We use adc_0 above, so the driver
404  * is relying on the numeric instance value in a way that happens to
405  * be safe.)
406  *
407  * Just in case that assumption becomes invalid in the future, we use
408  * a BUILD_ASSERT().
409  */
410 #define ADC_INIT(inst)							\
411 	BUILD_ASSERT((inst) == 0,					\
412 		     "multiple instances not supported");		\
413 	PINCTRL_DT_INST_DEFINE(inst);					\
414 	static const struct adc_smartbond_cfg adc_smartbond_cfg_##inst = {\
415 		.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(inst),		\
416 	};								\
417 	static struct adc_smartbond_data adc_smartbond_data_##inst = {	\
418 		ADC_CONTEXT_INIT_TIMER(adc_smartbond_data_##inst, ctx),	\
419 		ADC_CONTEXT_INIT_LOCK(adc_smartbond_data_##inst, ctx),	\
420 		ADC_CONTEXT_INIT_SYNC(adc_smartbond_data_##inst, ctx),	\
421 	};								\
422 	PM_DEVICE_DT_INST_DEFINE(inst, gpadc_smartbond_pm_action);	\
423 	DEVICE_DT_INST_DEFINE(inst,					\
424 			      adc_smartbond_init,  \
425 				  PM_DEVICE_DT_INST_GET(inst),			\
426 			      &adc_smartbond_data_##inst,		\
427 			      &adc_smartbond_cfg_##inst,		\
428 			      POST_KERNEL,				\
429 			      CONFIG_ADC_INIT_PRIORITY,			\
430 			      &adc_smartbond_driver_api);
431 
432 DT_INST_FOREACH_STATUS_OKAY(ADC_INIT)
433