1 /*
2  * Copyright (c) 2017 - 2018, Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #include <zephyr/drivers/counter.h>
7 #include <hal/nrf_timer.h>
8 #include <zephyr/sys/atomic.h>
9 
10 #define LOG_LEVEL CONFIG_COUNTER_LOG_LEVEL
11 #define LOG_MODULE_NAME counter_timer
12 #include <zephyr/logging/log.h>
13 #include <zephyr/irq.h>
14 LOG_MODULE_REGISTER(LOG_MODULE_NAME, LOG_LEVEL);
15 
16 #define DT_DRV_COMPAT nordic_nrf_timer
17 
18 #define CC_TO_ID(cc_num) (cc_num - 2)
19 
20 #define ID_TO_CC(idx) (nrf_timer_cc_channel_t)(idx + 2)
21 
22 #define TOP_CH NRF_TIMER_CC_CHANNEL0
23 #define COUNTER_TOP_EVT NRF_TIMER_EVENT_COMPARE0
24 #define COUNTER_TOP_INT_MASK NRF_TIMER_INT_COMPARE0_MASK
25 
26 #define COUNTER_OVERFLOW_SHORT NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK
27 #define COUNTER_READ_CC NRF_TIMER_CC_CHANNEL1
28 
29 #if defined(CONFIG_SOC_SERIES_BSIM_NRFXX)
30 #define MAYBE_CONST_CONFIG
31 #else
32 #define MAYBE_CONST_CONFIG const
33 #endif
34 
35 struct counter_nrfx_data {
36 	counter_top_callback_t top_cb;
37 	void *top_user_data;
38 	uint32_t guard_period;
39 	atomic_t cc_int_pending;
40 };
41 
42 struct counter_nrfx_ch_data {
43 	counter_alarm_callback_t callback;
44 	void *user_data;
45 };
46 
47 struct counter_nrfx_config {
48 	struct counter_config_info info;
49 	struct counter_nrfx_ch_data *ch_data;
50 	NRF_TIMER_Type *timer;
51 	LOG_INSTANCE_PTR_DECLARE(log);
52 };
53 
54 struct counter_timer_config {
55 	nrf_timer_bit_width_t bit_width;
56 	nrf_timer_mode_t mode;
57 	uint32_t prescaler;
58 };
59 
start(const struct device * dev)60 static int start(const struct device *dev)
61 {
62 	const struct counter_nrfx_config *config = dev->config;
63 
64 	nrf_timer_task_trigger(config->timer, NRF_TIMER_TASK_START);
65 
66 	return 0;
67 }
68 
stop(const struct device * dev)69 static int stop(const struct device *dev)
70 {
71 	const struct counter_nrfx_config *config = dev->config;
72 
73 	nrf_timer_task_trigger(config->timer, NRF_TIMER_TASK_STOP);
74 
75 	return 0;
76 }
77 
get_top_value(const struct device * dev)78 static uint32_t get_top_value(const struct device *dev)
79 {
80 	const struct counter_nrfx_config *config = dev->config;
81 
82 	return nrf_timer_cc_get(config->timer, TOP_CH);
83 }
84 
read(const struct device * dev)85 static uint32_t read(const struct device *dev)
86 {
87 	const struct counter_nrfx_config *config = dev->config;
88 	NRF_TIMER_Type *timer = config->timer;
89 
90 	nrf_timer_task_trigger(timer,
91 			       nrf_timer_capture_task_get(COUNTER_READ_CC));
92 	nrf_barrier_w();
93 
94 	return nrf_timer_cc_get(timer, COUNTER_READ_CC);
95 }
96 
get_value(const struct device * dev,uint32_t * ticks)97 static int get_value(const struct device *dev, uint32_t *ticks)
98 {
99 	*ticks = read(dev);
100 	return 0;
101 }
102 
ticks_add(uint32_t val1,uint32_t val2,uint32_t top)103 static uint32_t ticks_add(uint32_t val1, uint32_t val2, uint32_t top)
104 {
105 	uint32_t to_top;
106 
107 	if (likely(IS_BIT_MASK(top))) {
108 		return (val1 + val2) & top;
109 	}
110 
111 	to_top = top - val1;
112 
113 	return (val2 <= to_top) ? val1 + val2 : val2 - to_top;
114 }
115 
ticks_sub(uint32_t val,uint32_t old,uint32_t top)116 static uint32_t ticks_sub(uint32_t val, uint32_t old, uint32_t top)
117 {
118 	if (likely(IS_BIT_MASK(top))) {
119 		return (val - old) & top;
120 	}
121 
122 	/* if top is not 2^n-1 */
123 	return (val >= old) ? (val - old) : val + top + 1 - old;
124 }
125 
set_cc_int_pending(const struct device * dev,uint8_t chan)126 static void set_cc_int_pending(const struct device *dev, uint8_t chan)
127 {
128 	const struct counter_nrfx_config *config = dev->config;
129 	struct counter_nrfx_data *data = dev->data;
130 
131 	atomic_or(&data->cc_int_pending, BIT(chan));
132 	NRFX_IRQ_PENDING_SET(NRFX_IRQ_NUMBER_GET(config->timer));
133 }
134 
set_cc(const struct device * dev,uint8_t id,uint32_t val,uint32_t flags)135 static int set_cc(const struct device *dev, uint8_t id, uint32_t val,
136 		  uint32_t flags)
137 {
138 	const struct counter_nrfx_config *config = dev->config;
139 	struct counter_nrfx_data *data = dev->data;
140 
141 	__ASSERT_NO_MSG(data->guard_period < get_top_value(dev));
142 	bool absolute = flags & COUNTER_ALARM_CFG_ABSOLUTE;
143 	bool irq_on_late;
144 	NRF_TIMER_Type  *reg = config->timer;
145 	uint8_t chan = ID_TO_CC(id);
146 	nrf_timer_event_t evt = nrf_timer_compare_event_get(chan);
147 	uint32_t top = get_top_value(dev);
148 	int err = 0;
149 	uint32_t prev_val;
150 	uint32_t now;
151 	uint32_t diff;
152 	uint32_t max_rel_val;
153 
154 	__ASSERT(nrf_timer_int_enable_check(reg,
155 				nrf_timer_compare_int_get(chan)) == 0,
156 				"Expected that CC interrupt is disabled.");
157 
158 	/* First take care of a risk of an event coming from CC being set to
159 	 * next tick. Reconfigure CC to future (now tick is the furthest
160 	 * future).
161 	 */
162 	now = read(dev);
163 	prev_val = nrf_timer_cc_get(reg, chan);
164 	nrf_barrier_r();
165 	nrf_timer_cc_set(reg, chan, now);
166 	nrf_timer_event_clear(reg, evt);
167 
168 	if (absolute) {
169 		max_rel_val = top - data->guard_period;
170 		irq_on_late = flags & COUNTER_ALARM_CFG_EXPIRE_WHEN_LATE;
171 	} else {
172 		/* If relative value is smaller than half of the counter range
173 		 * it is assumed that there is a risk of setting value too late
174 		 * and late detection algorithm must be applied. When late
175 		 * setting is detected, interrupt shall be triggered for
176 		 * immediate expiration of the timer. Detection is performed
177 		 * by limiting relative distance between CC and counter.
178 		 *
179 		 * Note that half of counter range is an arbitrary value.
180 		 */
181 		irq_on_late = val < (top / 2);
182 		/* limit max to detect short relative being set too late. */
183 		max_rel_val = irq_on_late ? top / 2 : top;
184 		val = ticks_add(now, val, top);
185 	}
186 
187 	nrf_timer_cc_set(reg, chan, val);
188 
189 	/* decrement value to detect also case when val == read(dev). Otherwise,
190 	 * condition would need to include comparing diff against 0.
191 	 */
192 	diff = ticks_sub(val - 1, read(dev), top);
193 	if (diff > max_rel_val) {
194 		if (absolute) {
195 			err = -ETIME;
196 		}
197 
198 		/* Interrupt is triggered always for relative alarm and
199 		 * for absolute depending on the flag.
200 		 */
201 		if (irq_on_late) {
202 			set_cc_int_pending(dev, chan);
203 		} else {
204 			config->ch_data[id].callback = NULL;
205 		}
206 	} else {
207 		nrf_timer_int_enable(reg, nrf_timer_compare_int_get(chan));
208 	}
209 
210 	return err;
211 }
212 
set_alarm(const struct device * dev,uint8_t chan,const struct counter_alarm_cfg * alarm_cfg)213 static int set_alarm(const struct device *dev, uint8_t chan,
214 			const struct counter_alarm_cfg *alarm_cfg)
215 {
216 	const struct counter_nrfx_config *nrfx_config = dev->config;
217 	struct counter_nrfx_ch_data *chdata = &nrfx_config->ch_data[chan];
218 
219 	if (alarm_cfg->ticks >  get_top_value(dev)) {
220 		return -EINVAL;
221 	}
222 
223 	if (chdata->callback) {
224 		return -EBUSY;
225 	}
226 
227 	chdata->callback = alarm_cfg->callback;
228 	chdata->user_data = alarm_cfg->user_data;
229 
230 	return set_cc(dev, chan, alarm_cfg->ticks, alarm_cfg->flags);
231 }
232 
cancel_alarm(const struct device * dev,uint8_t chan_id)233 static int cancel_alarm(const struct device *dev, uint8_t chan_id)
234 {
235 	const struct counter_nrfx_config *config = dev->config;
236 	uint32_t int_mask =  nrf_timer_compare_int_get(ID_TO_CC(chan_id));
237 
238 	nrf_timer_int_disable(config->timer, int_mask);
239 	config->ch_data[chan_id].callback = NULL;
240 
241 	return 0;
242 }
243 
set_top_value(const struct device * dev,const struct counter_top_cfg * cfg)244 static int set_top_value(const struct device *dev,
245 			 const struct counter_top_cfg *cfg)
246 {
247 	const struct counter_nrfx_config *nrfx_config = dev->config;
248 	NRF_TIMER_Type *timer = nrfx_config->timer;
249 	struct counter_nrfx_data *data = dev->data;
250 	int err = 0;
251 	for (int i = 0; i < counter_get_num_of_channels(dev); i++) {
252 		/* Overflow can be changed only when all alarms are
253 		 * disables.
254 		 */
255 		if (nrfx_config->ch_data[i].callback) {
256 			return -EBUSY;
257 		}
258 	}
259 
260 	nrf_timer_int_disable(timer, COUNTER_TOP_INT_MASK);
261 	nrf_timer_cc_set(timer, TOP_CH, cfg->ticks);
262 	nrf_timer_event_clear(timer, COUNTER_TOP_EVT);
263 	nrf_timer_shorts_enable(timer, COUNTER_OVERFLOW_SHORT);
264 
265 	data->top_cb = cfg->callback;
266 	data->top_user_data = cfg->user_data;
267 
268 	if (!(cfg->flags & COUNTER_TOP_CFG_DONT_RESET)) {
269 		nrf_timer_task_trigger(timer, NRF_TIMER_TASK_CLEAR);
270 	} else if (read(dev) >= cfg->ticks) {
271 		err = -ETIME;
272 		if (cfg->flags & COUNTER_TOP_CFG_RESET_WHEN_LATE) {
273 			nrf_timer_task_trigger(timer, NRF_TIMER_TASK_CLEAR);
274 		}
275 	}
276 
277 	if (cfg->callback) {
278 		nrf_timer_int_enable(timer, COUNTER_TOP_INT_MASK);
279 	}
280 
281 	return err;
282 }
283 
get_pending_int(const struct device * dev)284 static uint32_t get_pending_int(const struct device *dev)
285 {
286 	return 0;
287 }
288 
init_timer(const struct device * dev,const struct counter_timer_config * config)289 static int init_timer(const struct device *dev,
290 		      const struct counter_timer_config *config)
291 {
292 	MAYBE_CONST_CONFIG struct counter_nrfx_config *nrfx_config =
293 			(MAYBE_CONST_CONFIG struct counter_nrfx_config *)dev->config;
294 
295 #if defined(CONFIG_SOC_SERIES_BSIM_NRFXX)
296 	/* For simulated devices we need to convert the hardcoded DT address from the real
297 	 * peripheral into the correct one for simulation
298 	 */
299 	nrfx_config->timer = nhw_convert_periph_base_addr(nrfx_config->timer);
300 #endif
301 
302 	NRF_TIMER_Type *reg = nrfx_config->timer;
303 
304 	nrf_timer_bit_width_set(reg, config->bit_width);
305 	nrf_timer_mode_set(reg, config->mode);
306 	nrf_timer_prescaler_set(reg, config->prescaler);
307 
308 	nrf_timer_cc_set(reg, TOP_CH, counter_get_max_top_value(dev));
309 
310 	NRFX_IRQ_ENABLE(NRFX_IRQ_NUMBER_GET(reg));
311 
312 	return 0;
313 }
314 
get_guard_period(const struct device * dev,uint32_t flags)315 static uint32_t get_guard_period(const struct device *dev, uint32_t flags)
316 {
317 	struct counter_nrfx_data *data = dev->data;
318 
319 	return data->guard_period;
320 }
321 
set_guard_period(const struct device * dev,uint32_t guard,uint32_t flags)322 static int set_guard_period(const struct device *dev, uint32_t guard,
323 			    uint32_t flags)
324 {
325 	struct counter_nrfx_data *data = dev->data;
326 
327 	__ASSERT_NO_MSG(guard < get_top_value(dev));
328 
329 	data->guard_period = guard;
330 	return 0;
331 }
332 
top_irq_handle(const struct device * dev)333 static void top_irq_handle(const struct device *dev)
334 {
335 	const struct counter_nrfx_config *config = dev->config;
336 	struct counter_nrfx_data *data = dev->data;
337 
338 	NRF_TIMER_Type *reg = config->timer;
339 	counter_top_callback_t cb = data->top_cb;
340 
341 	if (nrf_timer_event_check(reg, COUNTER_TOP_EVT) &&
342 		nrf_timer_int_enable_check(reg, COUNTER_TOP_INT_MASK)) {
343 		nrf_timer_event_clear(reg, COUNTER_TOP_EVT);
344 		__ASSERT(cb != NULL, "top event enabled - expecting callback");
345 		cb(dev, data->top_user_data);
346 	}
347 }
348 
alarm_irq_handle(const struct device * dev,uint32_t id)349 static void alarm_irq_handle(const struct device *dev, uint32_t id)
350 {
351 	const struct counter_nrfx_config *config = dev->config;
352 	struct counter_nrfx_data *data = dev->data;
353 
354 	uint32_t cc = ID_TO_CC(id);
355 	NRF_TIMER_Type *reg = config->timer;
356 	uint32_t int_mask = nrf_timer_compare_int_get(cc);
357 	nrf_timer_event_t evt = nrf_timer_compare_event_get(cc);
358 	bool hw_irq_pending = nrf_timer_event_check(reg, evt) &&
359 			      nrf_timer_int_enable_check(reg, int_mask);
360 	bool sw_irq_pending = data->cc_int_pending & BIT(cc);
361 
362 	if (hw_irq_pending || sw_irq_pending) {
363 		struct counter_nrfx_ch_data *chdata;
364 		counter_alarm_callback_t cb;
365 
366 		nrf_timer_event_clear(reg, evt);
367 		atomic_and(&data->cc_int_pending, ~BIT(cc));
368 		nrf_timer_int_disable(reg, int_mask);
369 
370 		chdata = &config->ch_data[id];
371 		cb = chdata->callback;
372 		chdata->callback = NULL;
373 
374 		if (cb) {
375 			uint32_t cc_val = nrf_timer_cc_get(reg, cc);
376 
377 			cb(dev, id, cc_val, chdata->user_data);
378 		}
379 	}
380 }
381 
irq_handler(const void * arg)382 static void irq_handler(const void *arg)
383 {
384 	const struct device *dev = arg;
385 
386 	top_irq_handle(dev);
387 
388 	for (uint32_t i = 0; i < counter_get_num_of_channels(dev); i++) {
389 		alarm_irq_handle(dev, i);
390 	}
391 }
392 
393 static DEVICE_API(counter, counter_nrfx_driver_api) = {
394 	.start = start,
395 	.stop = stop,
396 	.get_value = get_value,
397 	.set_alarm = set_alarm,
398 	.cancel_alarm = cancel_alarm,
399 	.set_top_value = set_top_value,
400 	.get_pending_int = get_pending_int,
401 	.get_top_value = get_top_value,
402 	.get_guard_period = get_guard_period,
403 	.set_guard_period = set_guard_period,
404 };
405 
406 /*
407  * Device instantiation is done with node labels due to HAL API
408  * requirements. In particular, TIMERx_MAX_SIZE values from HALs
409  * are indexed by peripheral number, so DT_INST APIs won't work.
410  */
411 
412 #define TIMER_IRQ_CONNECT(idx)							\
413 	COND_CODE_1(DT_INST_PROP(idx, zli),					\
414 		(IRQ_DIRECT_CONNECT(DT_INST_IRQN(idx),				\
415 				    DT_INST_IRQ(idx, priority),			\
416 				    counter_timer##idx##_isr_wrapper,		\
417 				    IRQ_ZERO_LATENCY)),				\
418 		(IRQ_CONNECT(DT_INST_IRQN(idx), DT_INST_IRQ(idx, priority),	\
419 			    irq_handler, DEVICE_DT_INST_GET(idx), 0))		\
420 	)
421 
422 #if !defined(CONFIG_SOC_SERIES_BSIM_NRFXX)
423 #define CHECK_MAX_FREQ(idx)									\
424 		BUILD_ASSERT(DT_INST_PROP(idx, max_frequency) ==				\
425 			NRF_TIMER_BASE_FREQUENCY_GET((NRF_TIMER_Type *)DT_INST_REG_ADDR(idx)))
426 #else
427 #define CHECK_MAX_FREQ(idx)
428 #endif
429 
430 #define COUNTER_NRFX_TIMER_DEVICE(idx)								\
431 	BUILD_ASSERT(DT_INST_PROP(idx, prescaler) <=						\
432 			TIMER_PRESCALER_PRESCALER_Msk,						\
433 		     "TIMER prescaler out of range");						\
434 	COND_CODE_1(DT_INST_PROP(idx, zli), (							\
435 		ISR_DIRECT_DECLARE(counter_timer##idx##_isr_wrapper)				\
436 		{										\
437 			irq_handler(DEVICE_DT_INST_GET(idx));					\
438 			/* No rescheduling, it shall not access zephyr primitives. */		\
439 			return 0;								\
440 		}), ())										\
441 	static int counter_##idx##_init(const struct device *dev)				\
442 	{											\
443 		TIMER_IRQ_CONNECT(idx);								\
444 		static const struct counter_timer_config config = {				\
445 			.prescaler = DT_INST_PROP(idx, prescaler),				\
446 			.mode = NRF_TIMER_MODE_TIMER,						\
447 			.bit_width = (DT_INST_PROP(idx, max_bit_width) == 32) ?			\
448 					NRF_TIMER_BIT_WIDTH_32 : NRF_TIMER_BIT_WIDTH_16,	\
449 		};										\
450 		return init_timer(dev, &config);						\
451 	}											\
452 	static struct counter_nrfx_data counter_##idx##_data;					\
453 	static struct counter_nrfx_ch_data							\
454 		counter##idx##_ch_data[CC_TO_ID(DT_INST_PROP(idx, cc_num))];			\
455 	LOG_INSTANCE_REGISTER(LOG_MODULE_NAME, idx, CONFIG_COUNTER_LOG_LEVEL);			\
456 	static MAYBE_CONST_CONFIG struct counter_nrfx_config nrfx_counter_##idx##_config = {	\
457 		.info = {									\
458 			.max_top_value = (uint32_t)BIT64_MASK(DT_INST_PROP(idx, max_bit_width)),\
459 			.freq = DT_INST_PROP(idx, max_frequency) /				\
460 				BIT(DT_INST_PROP(idx, prescaler)),				\
461 			.flags = COUNTER_CONFIG_INFO_COUNT_UP,					\
462 			.channels = CC_TO_ID(DT_INST_PROP(idx, cc_num)),			\
463 		},										\
464 		.ch_data = counter##idx##_ch_data,						\
465 		.timer = (NRF_TIMER_Type *)DT_INST_REG_ADDR(idx),				\
466 		LOG_INSTANCE_PTR_INIT(log, LOG_MODULE_NAME, idx)				\
467 	};											\
468 	CHECK_MAX_FREQ(idx);									\
469 	DEVICE_DT_INST_DEFINE(idx,								\
470 			    counter_##idx##_init,						\
471 			    NULL,								\
472 			    &counter_##idx##_data,						\
473 			    &nrfx_counter_##idx##_config.info,					\
474 			    PRE_KERNEL_1, CONFIG_COUNTER_INIT_PRIORITY,				\
475 			    &counter_nrfx_driver_api);
476 
477 DT_INST_FOREACH_STATUS_OKAY(COUNTER_NRFX_TIMER_DEVICE)
478