text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```unknown # Counter and timer configuration options config TIMER_DTMR_CMSDK_APB bool "ARM CMSDK (Cortex-M System Design Kit) DTMR Timer driver" default y depends on DT_HAS_ARM_CMSDK_DTIMER_ENABLED help The dualtimer (DTMR) present in the platform is used as a timer. This option enables the support for the timer. ```
/content/code_sandbox/drivers/counter/Kconfig.dtmr_cmsdk_apb
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
81
```unknown # IMX EPIT configuration options config COUNTER_IMX_EPIT bool "IMX EPIT driver" default y depends on DT_HAS_NXP_IMX_EPIT_ENABLED help Enable the IMX EPIT driver. ```
/content/code_sandbox/drivers/counter/Kconfig.imx_epit
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
52
```unknown # Xilinx AXI Timer config COUNTER_XLNX_AXI_TIMER bool "Xilinx AXI Timer driver" default y depends on DT_HAS_XLNX_XPS_TIMER_1_00_A_ENABLED help Enable counter support for the Xilinx AXI Timer v2.0 IP. ```
/content/code_sandbox/drivers/counter/Kconfig.xlnx
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
67
```c /* * */ #define DT_DRV_COMPAT gd_gd32_timer #include <zephyr/device.h> #include <zephyr/drivers/clock_control.h> #include <zephyr/drivers/clock_control/gd32.h> #include <zephyr/drivers/counter.h> #include <zephyr/drivers/reset.h> #include <zephyr/irq.h> #include <zephyr/logging/log.h> #include <zephyr/sys/atomic.h> #include <gd32_timer.h> LOG_MODULE_REGISTER(counter_gd32_timer); #define TIMER_INT_CH(ch) (TIMER_INT_CH0 << ch) #define TIMER_FLAG_CH(ch) (TIMER_FLAG_CH0 << ch) #define TIMER_INT_ALL (0xFFu) struct counter_gd32_ch_data { counter_alarm_callback_t callback; void *user_data; }; struct counter_gd32_data { counter_top_callback_t top_cb; void *top_user_data; uint32_t guard_period; atomic_t cc_int_pending; uint32_t freq; struct counter_gd32_ch_data alarm[]; }; struct counter_gd32_config { struct counter_config_info counter_info; uint32_t reg; uint16_t clkid; struct reset_dt_spec reset; uint16_t prescaler; void (*irq_config)(const struct device *dev); void (*set_irq_pending)(void); uint32_t (*get_irq_pending)(void); }; static uint32_t get_autoreload_value(const struct device *dev) { const struct counter_gd32_config *config = dev->config; return TIMER_CAR(config->reg); } static void set_autoreload_value(const struct device *dev, uint32_t value) { const struct counter_gd32_config *config = dev->config; TIMER_CAR(config->reg) = value; } static uint32_t get_counter(const struct device *dev) { const struct counter_gd32_config *config = dev->config; return TIMER_CNT(config->reg); } static void set_counter(const struct device *dev, uint32_t value) { const struct counter_gd32_config *config = dev->config; TIMER_CNT(config->reg) = value; } static void set_software_event_gen(const struct device *dev, uint8_t evt) { const struct counter_gd32_config *config = dev->config; TIMER_SWEVG(config->reg) |= evt; } static void set_prescaler(const struct device *dev, uint16_t prescaler) { const struct counter_gd32_config *config = dev->config; TIMER_PSC(config->reg) = prescaler; } static void set_compare_value(const struct device *dev, uint16_t chan, uint32_t compare_value) { const struct counter_gd32_config *config = dev->config; switch (chan) { case 0: TIMER_CH0CV(config->reg) = compare_value; break; case 1: TIMER_CH1CV(config->reg) = compare_value; break; case 2: TIMER_CH2CV(config->reg) = compare_value; break; case 3: TIMER_CH3CV(config->reg) = compare_value; break; } } static void interrupt_enable(const struct device *dev, uint32_t interrupt) { const struct counter_gd32_config *config = dev->config; TIMER_DMAINTEN(config->reg) |= interrupt; } static void interrupt_disable(const struct device *dev, uint32_t interrupt) { const struct counter_gd32_config *config = dev->config; TIMER_DMAINTEN(config->reg) &= ~interrupt; } static uint32_t interrupt_flag_get(const struct device *dev, uint32_t interrupt) { const struct counter_gd32_config *config = dev->config; return (TIMER_DMAINTEN(config->reg) & TIMER_INTF(config->reg) & interrupt); } static void interrupt_flag_clear(const struct device *dev, uint32_t interrupt) { const struct counter_gd32_config *config = dev->config; TIMER_INTF(config->reg) &= ~interrupt; } static int counter_gd32_timer_start(const struct device *dev) { const struct counter_gd32_config *config = dev->config; TIMER_CTL0(config->reg) |= (uint32_t)TIMER_CTL0_CEN; return 0; } static int counter_gd32_timer_stop(const struct device *dev) { const struct counter_gd32_config *config = dev->config; TIMER_CTL0(config->reg) &= ~(uint32_t)TIMER_CTL0_CEN; return 0; } static int counter_gd32_timer_get_value(const struct device *dev, uint32_t *ticks) { *ticks = get_counter(dev); return 0; } static uint32_t counter_gd32_timer_get_top_value(const struct device *dev) { return get_autoreload_value(dev); } static uint32_t ticks_add(uint32_t val1, uint32_t val2, uint32_t top) { uint32_t to_top; if (likely(IS_BIT_MASK(top))) { return (val1 + val2) & top; } to_top = top - val1; return (val2 <= to_top) ? val1 + val2 : val2 - to_top; } static uint32_t ticks_sub(uint32_t val, uint32_t old, uint32_t top) { if (likely(IS_BIT_MASK(top))) { return (val - old) & top; } /* if top is not 2^n-1 */ return (val >= old) ? (val - old) : val + top + 1 - old; } static void set_cc_int_pending(const struct device *dev, uint8_t chan) { const struct counter_gd32_config *config = dev->config; struct counter_gd32_data *data = dev->data; atomic_or(&data->cc_int_pending, TIMER_INT_CH(chan)); config->set_irq_pending(); } static int set_cc(const struct device *dev, uint8_t chan, uint32_t val, uint32_t flags) { const struct counter_gd32_config *config = dev->config; struct counter_gd32_data *data = dev->data; __ASSERT_NO_MSG(data->guard_period < counter_gd32_timer_get_top_value(dev)); bool absolute = flags & COUNTER_ALARM_CFG_ABSOLUTE; uint32_t top = counter_gd32_timer_get_top_value(dev); uint32_t now, diff, max_rel_val; bool irq_on_late; int err = 0; ARG_UNUSED(config); __ASSERT(!(TIMER_DMAINTEN(config->reg) & TIMER_INT_CH(chan)), "Expected that CC interrupt is disabled."); /* First take care of a risk of an event coming from CC being set to * next tick. Reconfigure CC to future (now tick is the furthest * future). */ now = get_counter(dev); set_compare_value(dev, chan, now); interrupt_flag_clear(dev, TIMER_FLAG_CH(chan)); if (absolute) { max_rel_val = top - data->guard_period; irq_on_late = flags & COUNTER_ALARM_CFG_EXPIRE_WHEN_LATE; } else { /* If relative value is smaller than half of the counter range * it is assumed that there is a risk of setting value too late * and late detection algorithm must be applied. When late * setting is detected, interrupt shall be triggered for * immediate expiration of the timer. Detection is performed * by limiting relative distance between CC and counter. * * Note that half of counter range is an arbitrary value. */ irq_on_late = val < (top / 2); /* limit max to detect short relative being set too late. */ max_rel_val = irq_on_late ? top / 2 : top; val = ticks_add(now, val, top); } set_compare_value(dev, chan, val); /* decrement value to detect also case when val == get_counter(dev). * Otherwise, condition would need to include comparing diff against 0. */ diff = ticks_sub(val - 1, get_counter(dev), top); if (diff > max_rel_val) { if (absolute) { err = -ETIME; } /* Interrupt is triggered always for relative alarm and * for absolute depending on the flag. */ if (irq_on_late) { set_cc_int_pending(dev, chan); } else { data->alarm[chan].callback = NULL; } } else { interrupt_enable(dev, TIMER_INT_CH(chan)); } return err; } static int counter_gd32_timer_set_alarm(const struct device *dev, uint8_t chan, const struct counter_alarm_cfg *alarm_cfg) { struct counter_gd32_data *data = dev->data; struct counter_gd32_ch_data *chdata = &data->alarm[chan]; if (alarm_cfg->ticks > counter_gd32_timer_get_top_value(dev)) { return -EINVAL; } if (chdata->callback) { return -EBUSY; } chdata->callback = alarm_cfg->callback; chdata->user_data = alarm_cfg->user_data; return set_cc(dev, chan, alarm_cfg->ticks, alarm_cfg->flags); } static int counter_gd32_timer_cancel_alarm(const struct device *dev, uint8_t chan) { struct counter_gd32_data *data = dev->data; interrupt_disable(dev, TIMER_INT_CH(chan)); data->alarm[chan].callback = NULL; return 0; } static int counter_gd32_timer_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { const struct counter_gd32_config *config = dev->config; struct counter_gd32_data *data = dev->data; int err = 0; for (uint32_t i = 0; i < config->counter_info.channels; i++) { /* Overflow can be changed only when all alarms are * disables. */ if (data->alarm[i].callback) { return -EBUSY; } } interrupt_disable(dev, TIMER_INT_UP); set_autoreload_value(dev, cfg->ticks); interrupt_flag_clear(dev, TIMER_INT_FLAG_UP); data->top_cb = cfg->callback; data->top_user_data = cfg->user_data; if (!(cfg->flags & COUNTER_TOP_CFG_DONT_RESET)) { set_counter(dev, 0); } else if (get_counter(dev) >= cfg->ticks) { err = -ETIME; if (cfg->flags & COUNTER_TOP_CFG_RESET_WHEN_LATE) { set_counter(dev, 0); } } if (cfg->callback) { interrupt_enable(dev, TIMER_INT_UP); } return err; } static uint32_t counter_gd32_timer_get_pending_int(const struct device *dev) { const struct counter_gd32_config *cfg = dev->config; return cfg->get_irq_pending(); } static uint32_t counter_gd32_timer_get_freq(const struct device *dev) { struct counter_gd32_data *data = dev->data; return data->freq; } static uint32_t counter_gd32_timer_get_guard_period(const struct device *dev, uint32_t flags) { struct counter_gd32_data *data = dev->data; return data->guard_period; } static int counter_gd32_timer_set_guard_period(const struct device *dev, uint32_t guard, uint32_t flags) { struct counter_gd32_data *data = dev->data; __ASSERT_NO_MSG(guard < counter_gd32_timer_get_top_value(dev)); data->guard_period = guard; return 0; } static void top_irq_handle(const struct device *dev) { struct counter_gd32_data *data = dev->data; counter_top_callback_t cb = data->top_cb; if (interrupt_flag_get(dev, TIMER_INT_FLAG_UP) != 0) { interrupt_flag_clear(dev, TIMER_INT_FLAG_UP); __ASSERT(cb != NULL, "top event enabled - expecting callback"); cb(dev, data->top_user_data); } } static void alarm_irq_handle(const struct device *dev, uint32_t chan) { struct counter_gd32_data *data = dev->data; struct counter_gd32_ch_data *alarm = &data->alarm[chan]; counter_alarm_callback_t cb; bool hw_irq_pending = !!(interrupt_flag_get(dev, TIMER_FLAG_CH(chan))); bool sw_irq_pending = data->cc_int_pending & TIMER_INT_CH(chan); if (hw_irq_pending || sw_irq_pending) { atomic_and(&data->cc_int_pending, ~TIMER_INT_CH(chan)); interrupt_disable(dev, TIMER_INT_CH(chan)); interrupt_flag_clear(dev, TIMER_FLAG_CH(chan)); cb = alarm->callback; alarm->callback = NULL; if (cb) { cb(dev, chan, get_counter(dev), alarm->user_data); } } } static void irq_handler(const struct device *dev) { const struct counter_gd32_config *cfg = dev->config; top_irq_handle(dev); for (uint32_t i = 0; i < cfg->counter_info.channels; i++) { alarm_irq_handle(dev, i); } } static int counter_gd32_timer_init(const struct device *dev) { const struct counter_gd32_config *cfg = dev->config; struct counter_gd32_data *data = dev->data; uint32_t pclk; clock_control_on(GD32_CLOCK_CONTROLLER, (clock_control_subsys_t)&cfg->clkid); clock_control_get_rate(GD32_CLOCK_CONTROLLER, (clock_control_subsys_t)&cfg->clkid, &pclk); data->freq = pclk / (cfg->prescaler + 1); interrupt_disable(dev, TIMER_INT_ALL); reset_line_toggle_dt(&cfg->reset); cfg->irq_config(dev); set_prescaler(dev, cfg->prescaler); set_autoreload_value(dev, cfg->counter_info.max_top_value); set_software_event_gen(dev, TIMER_SWEVG_UPG); return 0; } static const struct counter_driver_api counter_api = { .start = counter_gd32_timer_start, .stop = counter_gd32_timer_stop, .get_value = counter_gd32_timer_get_value, .set_alarm = counter_gd32_timer_set_alarm, .cancel_alarm = counter_gd32_timer_cancel_alarm, .set_top_value = counter_gd32_timer_set_top_value, .get_pending_int = counter_gd32_timer_get_pending_int, .get_top_value = counter_gd32_timer_get_top_value, .get_guard_period = counter_gd32_timer_get_guard_period, .set_guard_period = counter_gd32_timer_set_guard_period, .get_freq = counter_gd32_timer_get_freq, }; #define TIMER_IRQ_CONFIG(n) \ static void irq_config_##n(const struct device *dev) \ { \ IRQ_CONNECT(DT_INST_IRQ_BY_NAME(n, global, irq), \ DT_INST_IRQ_BY_NAME(n, global, priority), \ irq_handler, DEVICE_DT_INST_GET(n), 0); \ irq_enable(DT_INST_IRQ_BY_NAME(n, global, irq)); \ } \ static void set_irq_pending_##n(void) \ { \ (NVIC_SetPendingIRQ(DT_INST_IRQ_BY_NAME(n, global, irq))); \ } \ static uint32_t get_irq_pending_##n(void) \ { \ return NVIC_GetPendingIRQ( \ DT_INST_IRQ_BY_NAME(n, global, irq)); \ } #define TIMER_IRQ_CONFIG_ADVANCED(n) \ static void irq_config_##n(const struct device *dev) \ { \ IRQ_CONNECT((DT_INST_IRQ_BY_NAME(n, up, irq)), \ (DT_INST_IRQ_BY_NAME(n, up, priority)), \ irq_handler, (DEVICE_DT_INST_GET(n)), 0); \ irq_enable((DT_INST_IRQ_BY_NAME(n, up, irq))); \ IRQ_CONNECT((DT_INST_IRQ_BY_NAME(n, cc, irq)), \ (DT_INST_IRQ_BY_NAME(n, cc, priority)), \ irq_handler, (DEVICE_DT_INST_GET(n)), 0); \ irq_enable((DT_INST_IRQ_BY_NAME(n, cc, irq))); \ } \ static void set_irq_pending_##n(void) \ { \ (NVIC_SetPendingIRQ(DT_INST_IRQ_BY_NAME(n, cc, irq))); \ } \ static uint32_t get_irq_pending_##n(void) \ { \ return NVIC_GetPendingIRQ(DT_INST_IRQ_BY_NAME(n, cc, irq)); \ } #define GD32_TIMER_INIT(n) \ COND_CODE_1(DT_INST_PROP(n, is_advanced), \ (TIMER_IRQ_CONFIG_ADVANCED(n)), (TIMER_IRQ_CONFIG(n))); \ static struct counter_gd32_data_##n { \ struct counter_gd32_data data; \ struct counter_gd32_ch_data alarm[DT_INST_PROP(n, channels)]; \ } timer_data_##n = {0}; \ static const struct counter_gd32_config timer_config_##n = { \ .counter_info = {.max_top_value = COND_CODE_1( \ DT_INST_PROP(n, is_32bit), \ (UINT32_MAX), (UINT16_MAX)), \ .flags = COUNTER_CONFIG_INFO_COUNT_UP, \ .freq = 0, \ .channels = DT_INST_PROP(n, channels)}, \ .reg = DT_INST_REG_ADDR(n), \ .clkid = DT_INST_CLOCKS_CELL(n, id), \ .reset = RESET_DT_SPEC_INST_GET(n), \ .prescaler = DT_INST_PROP(n, prescaler), \ .irq_config = irq_config_##n, \ .set_irq_pending = set_irq_pending_##n, \ .get_irq_pending = get_irq_pending_##n, \ }; \ \ DEVICE_DT_INST_DEFINE(n, counter_gd32_timer_init, NULL, \ &timer_data_##n, &timer_config_##n, \ PRE_KERNEL_1, CONFIG_COUNTER_INIT_PRIORITY, \ &counter_api); DT_INST_FOREACH_STATUS_OKAY(GD32_TIMER_INIT); ```
/content/code_sandbox/drivers/counter/counter_gd32_timer.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,947
```unknown # MCUXpresso SDK Periodic Interrupt Timer (PIT) config COUNTER_NXP_PIT bool "NXP PIT driver" default y depends on DT_HAS_NXP_PIT_CHANNEL_ENABLED && \ DT_HAS_NXP_PIT_ENABLED help Enable support for the NXP Periodic Interrupt Timer (PIT). ```
/content/code_sandbox/drivers/counter/Kconfig.nxp_pit
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
72
```c /* * */ #define DT_DRV_COMPAT nxp_kinetis_rtc #include <zephyr/drivers/counter.h> #include <zephyr/irq.h> #include <zephyr/kernel.h> #include <zephyr/sys_clock.h> #include <fsl_rtc.h> #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(mcux_rtc, CONFIG_COUNTER_LOG_LEVEL); struct mcux_rtc_data { counter_alarm_callback_t alarm_callback; counter_top_callback_t top_callback; void *alarm_user_data; void *top_user_data; }; struct mcux_rtc_config { struct counter_config_info info; RTC_Type *base; void (*irq_config_func)(const struct device *dev); }; static int mcux_rtc_start(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_rtc_config *config = CONTAINER_OF(info, struct mcux_rtc_config, info); RTC_StartTimer(config->base); RTC_EnableInterrupts(config->base, kRTC_AlarmInterruptEnable | kRTC_TimeOverflowInterruptEnable | kRTC_TimeInvalidInterruptEnable); return 0; } static int mcux_rtc_stop(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_rtc_config *config = CONTAINER_OF(info, struct mcux_rtc_config, info); RTC_DisableInterrupts(config->base, kRTC_AlarmInterruptEnable | kRTC_TimeOverflowInterruptEnable | kRTC_TimeInvalidInterruptEnable); RTC_StopTimer(config->base); /* clear out any set alarms */ config->base->TAR = 0; return 0; } static uint32_t mcux_rtc_read(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_rtc_config *config = CONTAINER_OF(info, struct mcux_rtc_config, info); uint32_t ticks = config->base->TSR; /* * Read TSR seconds twice in case it glitches during an update. * This can happen when a read occurs at the time the register is * incrementing. */ if (config->base->TSR == ticks) { return ticks; } ticks = config->base->TSR; return ticks; } static int mcux_rtc_get_value(const struct device *dev, uint32_t *ticks) { *ticks = mcux_rtc_read(dev); return 0; } static int mcux_rtc_set_alarm(const struct device *dev, uint8_t chan_id, const struct counter_alarm_cfg *alarm_cfg) { const struct counter_config_info *info = dev->config; const struct mcux_rtc_config *config = CONTAINER_OF(info, struct mcux_rtc_config, info); struct mcux_rtc_data *data = dev->data; uint32_t ticks = alarm_cfg->ticks; uint32_t current = mcux_rtc_read(dev); LOG_DBG("Current time is %d ticks", current); if (chan_id != 0U) { LOG_ERR("Invalid channel id"); return -EINVAL; } if (data->alarm_callback != NULL) { return -EBUSY; } if ((alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) == 0) { ticks += current; } if (ticks < current) { LOG_ERR("Alarm cannot be earlier than current time"); return -EINVAL; } data->alarm_callback = alarm_cfg->callback; data->alarm_user_data = alarm_cfg->user_data; config->base->TAR = ticks; LOG_DBG("Alarm set to %d ticks", ticks); return 0; } static int mcux_rtc_cancel_alarm(const struct device *dev, uint8_t chan_id) { struct mcux_rtc_data *data = dev->data; if (chan_id != 0U) { LOG_ERR("Invalid channel id"); return -EINVAL; } data->alarm_callback = NULL; return 0; } static int mcux_rtc_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { const struct counter_config_info *info = dev->config; const struct mcux_rtc_config *config = CONTAINER_OF(info, struct mcux_rtc_config, info); struct mcux_rtc_data *data = dev->data; if (cfg->ticks != info->max_top_value) { LOG_ERR("Wrap can only be set to 0x%x.", info->max_top_value); return -ENOTSUP; } if (!(cfg->flags & COUNTER_TOP_CFG_DONT_RESET)) { RTC_StopTimer(config->base); config->base->TSR = 0; RTC_StartTimer(config->base); } data->top_callback = cfg->callback; data->top_user_data = cfg->user_data; return 0; } static uint32_t mcux_rtc_get_pending_int(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_rtc_config *config = CONTAINER_OF(info, struct mcux_rtc_config, info); return RTC_GetStatusFlags(config->base) & RTC_SR_TAF_MASK; } static uint32_t mcux_rtc_get_top_value(const struct device *dev) { const struct counter_config_info *info = dev->config; return info->max_top_value; } static void mcux_rtc_isr(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_rtc_config *config = CONTAINER_OF(info, struct mcux_rtc_config, info); struct mcux_rtc_data *data = dev->data; counter_alarm_callback_t cb; uint32_t current = mcux_rtc_read(dev); LOG_DBG("Current time is %d ticks", current); if ((RTC_GetStatusFlags(config->base) & RTC_SR_TAF_MASK) && (data->alarm_callback)) { cb = data->alarm_callback; data->alarm_callback = NULL; cb(dev, 0, current, data->alarm_user_data); } if ((RTC_GetStatusFlags(config->base) & RTC_SR_TOF_MASK) && (data->top_callback)) { data->top_callback(dev, data->top_user_data); } /* * Clear any conditions to ack the IRQ * * callback may have already reset the alarm flag if a new * alarm value was programmed to the TAR */ RTC_StopTimer(config->base); if (RTC_GetStatusFlags(config->base) & RTC_SR_TAF_MASK) { RTC_ClearStatusFlags(config->base, kRTC_AlarmFlag); } else if (RTC_GetStatusFlags(config->base) & RTC_SR_TIF_MASK) { RTC_ClearStatusFlags(config->base, kRTC_TimeInvalidFlag); } else if (RTC_GetStatusFlags(config->base) & RTC_SR_TOF_MASK) { RTC_ClearStatusFlags(config->base, kRTC_TimeOverflowFlag); } RTC_StartTimer(config->base); } static int mcux_rtc_init(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_rtc_config *config = CONTAINER_OF(info, struct mcux_rtc_config, info); rtc_config_t rtc_config; RTC_GetDefaultConfig(&rtc_config); RTC_Init(config->base, &rtc_config); /* DT_ENUM_IDX(DT_NODELABEL(rtc), clock_source): * "RTC": 0 * "LPO": 1 */ BUILD_ASSERT((((DT_INST_ENUM_IDX(0, clock_source) == 1) && FSL_FEATURE_RTC_HAS_LPO_ADJUST) || DT_INST_ENUM_IDX(0, clock_source) == 0), "Cannot choose the LPO clock for that instance of the RTC"); #if (defined(FSL_FEATURE_RTC_HAS_LPO_ADJUST) && FSL_FEATURE_RTC_HAS_LPO_ADJUST) /* The RTC prescaler increments using the LPO 1 kHz clock * instead of the RTC clock */ RTC_EnableLPOClock(config->base, DT_INST_ENUM_IDX(0, clock_source)); #endif #if !(defined(FSL_FEATURE_RTC_HAS_NO_CR_OSCE) && FSL_FEATURE_RTC_HAS_NO_CR_OSCE) /* Enable 32kHz oscillator and wait for 1ms to settle */ RTC_SetClockSource(config->base); k_busy_wait(USEC_PER_MSEC); #endif /* !FSL_FEATURE_RTC_HAS_NO_CR_OSCE */ config->irq_config_func(dev); return 0; } static const struct counter_driver_api mcux_rtc_driver_api = { .start = mcux_rtc_start, .stop = mcux_rtc_stop, .get_value = mcux_rtc_get_value, .set_alarm = mcux_rtc_set_alarm, .cancel_alarm = mcux_rtc_cancel_alarm, .set_top_value = mcux_rtc_set_top_value, .get_pending_int = mcux_rtc_get_pending_int, .get_top_value = mcux_rtc_get_top_value, }; static struct mcux_rtc_data mcux_rtc_data_0; static void mcux_rtc_irq_config_0(const struct device *dev); static struct mcux_rtc_config mcux_rtc_config_0 = { .base = (RTC_Type *)DT_INST_REG_ADDR(0), .irq_config_func = mcux_rtc_irq_config_0, .info = { .max_top_value = UINT32_MAX, .freq = DT_INST_PROP(0, clock_frequency) / DT_INST_PROP(0, prescaler), .flags = COUNTER_CONFIG_INFO_COUNT_UP, .channels = 1, }, }; DEVICE_DT_INST_DEFINE(0, &mcux_rtc_init, NULL, &mcux_rtc_data_0, &mcux_rtc_config_0.info, POST_KERNEL, CONFIG_COUNTER_INIT_PRIORITY, &mcux_rtc_driver_api); static void mcux_rtc_irq_config_0(const struct device *dev) { IRQ_CONNECT(DT_INST_IRQN(0), DT_INST_IRQ(0, priority), mcux_rtc_isr, DEVICE_DT_INST_GET(0), 0); irq_enable(DT_INST_IRQN(0)); } ```
/content/code_sandbox/drivers/counter/counter_mcux_rtc.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,225
```c /* * */ #define DT_DRV_COMPAT microchip_mcp7940n #include <zephyr/device.h> #include <zephyr/drivers/counter.h> #include <zephyr/drivers/gpio.h> #include <zephyr/drivers/i2c.h> #include <zephyr/drivers/rtc/mcp7940n.h> #include <zephyr/kernel.h> #include <zephyr/logging/log.h> #include <zephyr/sys/timeutil.h> #include <zephyr/sys/util.h> #include <time.h> LOG_MODULE_REGISTER(MCP7940N, CONFIG_COUNTER_LOG_LEVEL); /* Alarm channels */ #define ALARM0_ID 0 #define ALARM1_ID 1 /* Size of block when writing whole struct */ #define RTC_TIME_REGISTERS_SIZE sizeof(struct mcp7940n_time_registers) #define RTC_ALARM_REGISTERS_SIZE sizeof(struct mcp7940n_alarm_registers) /* Largest block size */ #define MAX_WRITE_SIZE (RTC_TIME_REGISTERS_SIZE) /* tm struct uses years since 1900 but unix time uses years since * 1970. MCP7940N default year is '1' so the offset is 69 */ #define UNIX_YEAR_OFFSET 69 /* Macro used to decode BCD to UNIX time to avoid potential copy and paste * errors. */ #define RTC_BCD_DECODE(reg_prefix) (reg_prefix##_one + reg_prefix##_ten * 10) struct mcp7940n_config { struct counter_config_info generic; struct i2c_dt_spec i2c; const struct gpio_dt_spec int_gpios; }; struct mcp7940n_data { const struct device *mcp7940n; struct k_sem lock; struct mcp7940n_time_registers registers; struct mcp7940n_alarm_registers alm0_registers; struct mcp7940n_alarm_registers alm1_registers; struct k_work alarm_work; struct gpio_callback int_callback; counter_alarm_callback_t counter_handler[2]; uint32_t counter_ticks[2]; void *alarm_user_data[2]; bool int_active_high; }; /** @brief Convert bcd time in device registers to UNIX time * * @param dev the MCP7940N device pointer. * * @retval returns unix time. */ static time_t decode_rtc(const struct device *dev) { struct mcp7940n_data *data = dev->data; time_t time_unix = 0; struct tm time = { 0 }; time.tm_sec = RTC_BCD_DECODE(data->registers.rtc_sec.sec); time.tm_min = RTC_BCD_DECODE(data->registers.rtc_min.min); time.tm_hour = RTC_BCD_DECODE(data->registers.rtc_hours.hr); time.tm_mday = RTC_BCD_DECODE(data->registers.rtc_date.date); time.tm_wday = data->registers.rtc_weekday.weekday; /* tm struct starts months at 0, mcp7940n starts at 1 */ time.tm_mon = RTC_BCD_DECODE(data->registers.rtc_month.month) - 1; /* tm struct uses years since 1900 but unix time uses years since 1970 */ time.tm_year = RTC_BCD_DECODE(data->registers.rtc_year.year) + UNIX_YEAR_OFFSET; time_unix = timeutil_timegm(&time); LOG_DBG("Unix time is %d\n", (uint32_t)time_unix); return time_unix; } /** @brief Encode time struct tm into mcp7940n rtc registers * * @param dev the MCP7940N device pointer. * @param time_buffer tm struct containing time to be encoded into mcp7940n * registers. * * @retval return 0 on success, or a negative error code from invalid * parameter. */ static int encode_rtc(const struct device *dev, struct tm *time_buffer) { struct mcp7940n_data *data = dev->data; uint8_t month; uint8_t year_since_epoch; /* In a tm struct, months start at 0, mcp7940n starts with 1 */ month = time_buffer->tm_mon + 1; if (time_buffer->tm_year < UNIX_YEAR_OFFSET) { return -EINVAL; } year_since_epoch = time_buffer->tm_year - UNIX_YEAR_OFFSET; /* Set external oscillator configuration bit */ data->registers.rtc_sec.start_osc = 1; data->registers.rtc_sec.sec_one = time_buffer->tm_sec % 10; data->registers.rtc_sec.sec_ten = time_buffer->tm_sec / 10; data->registers.rtc_min.min_one = time_buffer->tm_min % 10; data->registers.rtc_min.min_ten = time_buffer->tm_min / 10; data->registers.rtc_hours.hr_one = time_buffer->tm_hour % 10; data->registers.rtc_hours.hr_ten = time_buffer->tm_hour / 10; data->registers.rtc_weekday.weekday = time_buffer->tm_wday; data->registers.rtc_date.date_one = time_buffer->tm_mday % 10; data->registers.rtc_date.date_ten = time_buffer->tm_mday / 10; data->registers.rtc_month.month_one = month % 10; data->registers.rtc_month.month_ten = month / 10; data->registers.rtc_year.year_one = year_since_epoch % 10; data->registers.rtc_year.year_ten = year_since_epoch / 10; return 0; } /** @brief Encode time struct tm into mcp7940n alarm registers * * @param dev the MCP7940N device pointer. * @param time_buffer tm struct containing time to be encoded into mcp7940n * registers. * @param alarm_id alarm ID, can be 0 or 1 for MCP7940N. * * @retval return 0 on success, or a negative error code from invalid * parameter. */ static int encode_alarm(const struct device *dev, struct tm *time_buffer, uint8_t alarm_id) { struct mcp7940n_data *data = dev->data; uint8_t month; struct mcp7940n_alarm_registers *alm_regs; if (alarm_id == ALARM0_ID) { alm_regs = &data->alm0_registers; } else if (alarm_id == ALARM1_ID) { alm_regs = &data->alm1_registers; } else { return -EINVAL; } /* In a tm struct, months start at 0 */ month = time_buffer->tm_mon + 1; alm_regs->alm_sec.sec_one = time_buffer->tm_sec % 10; alm_regs->alm_sec.sec_ten = time_buffer->tm_sec / 10; alm_regs->alm_min.min_one = time_buffer->tm_min % 10; alm_regs->alm_min.min_ten = time_buffer->tm_min / 10; alm_regs->alm_hours.hr_one = time_buffer->tm_hour % 10; alm_regs->alm_hours.hr_ten = time_buffer->tm_hour / 10; alm_regs->alm_weekday.weekday = time_buffer->tm_wday; alm_regs->alm_date.date_one = time_buffer->tm_mday % 10; alm_regs->alm_date.date_ten = time_buffer->tm_mday / 10; alm_regs->alm_month.month_one = month % 10; alm_regs->alm_month.month_ten = month / 10; return 0; } /** @brief Reads single register from MCP7940N * * @param dev the MCP7940N device pointer. * @param addr register address. * @param val pointer to uint8_t that will contain register value if * successful. * * @retval return 0 on success, or a negative error code from an I2C * transaction. */ static int read_register(const struct device *dev, uint8_t addr, uint8_t *val) { const struct mcp7940n_config *cfg = dev->config; int rc = i2c_write_read_dt(&cfg->i2c, &addr, sizeof(addr), val, 1); return rc; } /** @brief Read registers from device and populate mcp7940n_registers struct * * @param dev the MCP7940N device pointer. * @param unix_time pointer to time_t value that will contain unix time if * successful. * * @retval return 0 on success, or a negative error code from an I2C * transaction. */ static int read_time(const struct device *dev, time_t *unix_time) { struct mcp7940n_data *data = dev->data; const struct mcp7940n_config *cfg = dev->config; uint8_t addr = REG_RTC_SEC; int rc = i2c_write_read_dt(&cfg->i2c, &addr, sizeof(addr), &data->registers, RTC_TIME_REGISTERS_SIZE); if (rc >= 0) { *unix_time = decode_rtc(dev); } return rc; } /** @brief Write a single register to MCP7940N * * @param dev the MCP7940N device pointer. * @param addr register address. * @param value Value that will be written to the register. * * @retval return 0 on success, or a negative error code from an I2C * transaction or invalid parameter. */ static int write_register(const struct device *dev, enum mcp7940n_register addr, uint8_t value) { const struct mcp7940n_config *cfg = dev->config; int rc = 0; uint8_t time_data[2] = {addr, value}; rc = i2c_write_dt(&cfg->i2c, time_data, sizeof(time_data)); return rc; } /** @brief Write a full time struct to MCP7940N registers. * * @param dev the MCP7940N device pointer. * @param addr first register address to write to, should be REG_RTC_SEC, * REG_ALM0_SEC or REG_ALM0_SEC. * @param size size of data struct that will be written. * * @retval return 0 on success, or a negative error code from an I2C * transaction or invalid parameter. */ static int write_data_block(const struct device *dev, enum mcp7940n_register addr, uint8_t size) { struct mcp7940n_data *data = dev->data; const struct mcp7940n_config *cfg = dev->config; int rc = 0; uint8_t time_data[MAX_WRITE_SIZE + 1]; uint8_t *write_block_start; if (size > MAX_WRITE_SIZE) { return -EINVAL; } if (addr >= REG_INVAL) { return -EINVAL; } if (addr == REG_RTC_SEC) { write_block_start = (uint8_t *)&data->registers; } else if (addr == REG_ALM0_SEC) { write_block_start = (uint8_t *)&data->alm0_registers; } else if (addr == REG_ALM1_SEC) { write_block_start = (uint8_t *)&data->alm1_registers; } else { return -EINVAL; } /* Load register address into first byte then fill in data values */ time_data[0] = addr; memcpy(&time_data[1], write_block_start, size); rc = i2c_write_dt(&cfg->i2c, time_data, size + 1); return rc; } /** @brief Sets the correct weekday. * * If the time is never set then the device defaults to 1st January 1970 * but with the wrong weekday set. This function ensures the weekday is * correct in this case. * * @param dev the MCP7940N device pointer. * @param unix_time pointer to unix time that will be used to work out the weekday * * @retval return 0 on success, or a negative error code from an I2C * transaction or invalid parameter. */ static int set_day_of_week(const struct device *dev, time_t *unix_time) { struct mcp7940n_data *data = dev->data; struct tm time_buffer = { 0 }; int rc = 0; if (gmtime_r(unix_time, &time_buffer) != NULL) { data->registers.rtc_weekday.weekday = time_buffer.tm_wday; rc = write_register(dev, REG_RTC_WDAY, *((uint8_t *)(&data->registers.rtc_weekday))); } else { rc = -EINVAL; } return rc; } /** @brief Checks the interrupt pending flag (IF) of a given alarm. * * A callback is fired if an IRQ is pending. * * @param dev the MCP7940N device pointer. * @param alarm_id ID of alarm, can be 0 or 1 for MCP7940N. */ static void mcp7940n_handle_interrupt(const struct device *dev, uint8_t alarm_id) { struct mcp7940n_data *data = dev->data; uint8_t alarm_reg_address; struct mcp7940n_alarm_registers *alm_regs; counter_alarm_callback_t cb; uint32_t ticks = 0; bool fire_callback = false; if (alarm_id == ALARM0_ID) { alarm_reg_address = REG_ALM0_WDAY; alm_regs = &data->alm0_registers; } else if (alarm_id == ALARM1_ID) { alarm_reg_address = REG_ALM1_WDAY; alm_regs = &data->alm1_registers; } else { return; } k_sem_take(&data->lock, K_FOREVER); /* Check if this alarm has a pending interrupt */ read_register(dev, alarm_reg_address, (uint8_t *)&alm_regs->alm_weekday); if (alm_regs->alm_weekday.alm_if) { /* Clear interrupt */ alm_regs->alm_weekday.alm_if = 0; write_register(dev, alarm_reg_address, *((uint8_t *)(&alm_regs->alm_weekday))); /* Fire callback */ if (data->counter_handler[alarm_id]) { cb = data->counter_handler[alarm_id]; ticks = data->counter_ticks[alarm_id]; fire_callback = true; } } k_sem_give(&data->lock); if (fire_callback) { cb(data->mcp7940n, 0, ticks, data->alarm_user_data[alarm_id]); } } static void mcp7940n_work_handler(struct k_work *work) { struct mcp7940n_data *data = CONTAINER_OF(work, struct mcp7940n_data, alarm_work); /* Check interrupt flags for both alarms */ mcp7940n_handle_interrupt(data->mcp7940n, ALARM0_ID); mcp7940n_handle_interrupt(data->mcp7940n, ALARM1_ID); } static void mcp7940n_init_cb(const struct device *dev, struct gpio_callback *gpio_cb, uint32_t pins) { struct mcp7940n_data *data = CONTAINER_OF(gpio_cb, struct mcp7940n_data, int_callback); ARG_UNUSED(pins); k_work_submit(&data->alarm_work); } int mcp7940n_rtc_set_time(const struct device *dev, time_t unix_time) { struct mcp7940n_data *data = dev->data; struct tm time_buffer = { 0 }; int rc = 0; if (unix_time > UINT32_MAX) { LOG_ERR("Unix time must be 32-bit"); return -EINVAL; } k_sem_take(&data->lock, K_FOREVER); /* Convert unix_time to civil time */ gmtime_r(&unix_time, &time_buffer); LOG_DBG("Desired time is %d-%d-%d %d:%d:%d\n", (time_buffer.tm_year + 1900), (time_buffer.tm_mon + 1), time_buffer.tm_mday, time_buffer.tm_hour, time_buffer.tm_min, time_buffer.tm_sec); /* Encode time */ rc = encode_rtc(dev, &time_buffer); if (rc < 0) { goto out; } /* Write to device */ rc = write_data_block(dev, REG_RTC_SEC, RTC_TIME_REGISTERS_SIZE); out: k_sem_give(&data->lock); return rc; } static int mcp7940n_counter_start(const struct device *dev) { struct mcp7940n_data *data = dev->data; int rc = 0; k_sem_take(&data->lock, K_FOREVER); /* Set start oscillator configuration bit */ data->registers.rtc_sec.start_osc = 1; rc = write_register(dev, REG_RTC_SEC, *((uint8_t *)(&data->registers.rtc_sec))); k_sem_give(&data->lock); return rc; } static int mcp7940n_counter_stop(const struct device *dev) { struct mcp7940n_data *data = dev->data; int rc = 0; k_sem_take(&data->lock, K_FOREVER); /* Clear start oscillator configuration bit */ data->registers.rtc_sec.start_osc = 0; rc = write_register(dev, REG_RTC_SEC, *((uint8_t *)(&data->registers.rtc_sec))); k_sem_give(&data->lock); return rc; } static int mcp7940n_counter_get_value(const struct device *dev, uint32_t *ticks) { struct mcp7940n_data *data = dev->data; time_t unix_time; int rc; k_sem_take(&data->lock, K_FOREVER); /* Get time */ rc = read_time(dev, &unix_time); /* Convert time to ticks */ if (rc >= 0) { *ticks = unix_time; } k_sem_give(&data->lock); return rc; } static int mcp7940n_counter_set_alarm(const struct device *dev, uint8_t alarm_id, const struct counter_alarm_cfg *alarm_cfg) { struct mcp7940n_data *data = dev->data; uint32_t seconds_until_alarm; time_t current_time; time_t alarm_time; struct tm time_buffer = { 0 }; uint8_t alarm_base_address; struct mcp7940n_alarm_registers *alm_regs; int rc = 0; k_sem_take(&data->lock, K_FOREVER); if (alarm_id == ALARM0_ID) { alarm_base_address = REG_ALM0_SEC; alm_regs = &data->alm0_registers; } else if (alarm_id == ALARM1_ID) { alarm_base_address = REG_ALM1_SEC; alm_regs = &data->alm1_registers; } else { rc = -EINVAL; goto out; } /* Convert ticks to time */ seconds_until_alarm = alarm_cfg->ticks; /* Get current time and add alarm offset */ rc = read_time(dev, &current_time); if (rc < 0) { goto out; } alarm_time = current_time + seconds_until_alarm; gmtime_r(&alarm_time, &time_buffer); /* Set alarm trigger mask and alarm enable flag */ if (alarm_id == ALARM0_ID) { data->registers.rtc_control.alm0_en = 1; } else if (alarm_id == ALARM1_ID) { data->registers.rtc_control.alm1_en = 1; } /* Set alarm to match with second, minute, hour, day of week, day of * month and month */ alm_regs->alm_weekday.alm_msk = MCP7940N_ALARM_TRIGGER_ALL; /* Write time to alarm registers */ encode_alarm(dev, &time_buffer, alarm_id); rc = write_data_block(dev, alarm_base_address, RTC_ALARM_REGISTERS_SIZE); if (rc < 0) { goto out; } /* Enable alarm */ rc = write_register(dev, REG_RTC_CONTROL, *((uint8_t *)(&data->registers.rtc_control))); if (rc < 0) { goto out; } /* Config user data and callback */ data->counter_handler[alarm_id] = alarm_cfg->callback; data->counter_ticks[alarm_id] = current_time; data->alarm_user_data[alarm_id] = alarm_cfg->user_data; out: k_sem_give(&data->lock); return rc; } static int mcp7940n_counter_cancel_alarm(const struct device *dev, uint8_t alarm_id) { struct mcp7940n_data *data = dev->data; int rc = 0; k_sem_take(&data->lock, K_FOREVER); /* Clear alarm enable bit */ if (alarm_id == ALARM0_ID) { data->registers.rtc_control.alm0_en = 0; } else if (alarm_id == ALARM1_ID) { data->registers.rtc_control.alm1_en = 0; } else { rc = -EINVAL; goto out; } rc = write_register(dev, REG_RTC_CONTROL, *((uint8_t *)(&data->registers.rtc_control))); out: k_sem_give(&data->lock); return rc; } static int mcp7940n_counter_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { return -ENOTSUP; } /* This function can be used to poll the alarm interrupt flags if the MCU is * not connected to the MC7940N MFP pin. It can also be used to check if an * alarm was triggered while the MCU was in reset. This function will clear * the interrupt flag * * Return bitmask of alarm interrupt flag (IF) where each IF is shifted by * the alarm ID. */ static uint32_t mcp7940n_counter_get_pending_int(const struct device *dev) { struct mcp7940n_data *data = dev->data; uint32_t interrupt_pending = 0; int rc; k_sem_take(&data->lock, K_FOREVER); /* Check interrupt flag for alarm 0 */ rc = read_register(dev, REG_ALM0_WDAY, (uint8_t *)&data->alm0_registers.alm_weekday); if (rc < 0) { goto out; } if (data->alm0_registers.alm_weekday.alm_if) { /* Clear interrupt */ data->alm0_registers.alm_weekday.alm_if = 0; rc = write_register(dev, REG_ALM0_WDAY, *((uint8_t *)(&data->alm0_registers.alm_weekday))); if (rc < 0) { goto out; } interrupt_pending |= (1 << ALARM0_ID); } /* Check interrupt flag for alarm 1 */ rc = read_register(dev, REG_ALM1_WDAY, (uint8_t *)&data->alm1_registers.alm_weekday); if (rc < 0) { goto out; } if (data->alm1_registers.alm_weekday.alm_if) { /* Clear interrupt */ data->alm1_registers.alm_weekday.alm_if = 0; rc = write_register(dev, REG_ALM1_WDAY, *((uint8_t *)(&data->alm1_registers.alm_weekday))); if (rc < 0) { goto out; } interrupt_pending |= (1 << ALARM1_ID); } out: k_sem_give(&data->lock); if (rc) { interrupt_pending = 0; } return (interrupt_pending); } static uint32_t mcp7940n_counter_get_top_value(const struct device *dev) { return UINT32_MAX; } static int mcp7940n_init(const struct device *dev) { struct mcp7940n_data *data = dev->data; const struct mcp7940n_config *cfg = dev->config; int rc = 0; time_t unix_time = 0; /* Initialize and take the lock */ k_sem_init(&data->lock, 0, 1); if (!device_is_ready(cfg->i2c.bus)) { LOG_ERR("I2C device %s is not ready", cfg->i2c.bus->name); rc = -ENODEV; goto out; } rc = read_time(dev, &unix_time); if (rc < 0) { goto out; } rc = set_day_of_week(dev, &unix_time); if (rc < 0) { goto out; } /* Set 24-hour time */ data->registers.rtc_hours.twelve_hr = false; rc = write_register(dev, REG_RTC_HOUR, *((uint8_t *)(&data->registers.rtc_hours))); if (rc < 0) { goto out; } /* Configure alarm interrupt gpio */ if (cfg->int_gpios.port != NULL) { if (!gpio_is_ready_dt(&cfg->int_gpios)) { LOG_ERR("Port device %s is not ready", cfg->int_gpios.port->name); rc = -ENODEV; goto out; } data->mcp7940n = dev; k_work_init(&data->alarm_work, mcp7940n_work_handler); gpio_pin_configure_dt(&cfg->int_gpios, GPIO_INPUT); gpio_pin_interrupt_configure_dt(&cfg->int_gpios, GPIO_INT_EDGE_TO_ACTIVE); gpio_init_callback(&data->int_callback, mcp7940n_init_cb, BIT(cfg->int_gpios.pin)); gpio_add_callback(cfg->int_gpios.port, &data->int_callback); /* Configure interrupt polarity */ if ((cfg->int_gpios.dt_flags & GPIO_ACTIVE_LOW) == GPIO_ACTIVE_LOW) { data->int_active_high = false; } else { data->int_active_high = true; } data->alm0_registers.alm_weekday.alm_pol = data->int_active_high; data->alm1_registers.alm_weekday.alm_pol = data->int_active_high; rc = write_register(dev, REG_ALM0_WDAY, *((uint8_t *)(&data->alm0_registers.alm_weekday))); rc = write_register(dev, REG_ALM1_WDAY, *((uint8_t *)(&data->alm1_registers.alm_weekday))); } out: k_sem_give(&data->lock); return rc; } static const struct counter_driver_api mcp7940n_api = { .start = mcp7940n_counter_start, .stop = mcp7940n_counter_stop, .get_value = mcp7940n_counter_get_value, .set_alarm = mcp7940n_counter_set_alarm, .cancel_alarm = mcp7940n_counter_cancel_alarm, .set_top_value = mcp7940n_counter_set_top_value, .get_pending_int = mcp7940n_counter_get_pending_int, .get_top_value = mcp7940n_counter_get_top_value, }; #define INST_DT_MCP7904N(index) \ \ static struct mcp7940n_data mcp7940n_data_##index; \ \ static const struct mcp7940n_config mcp7940n_config_##index = { \ .generic = { \ .max_top_value = UINT32_MAX, \ .freq = 1, \ .flags = COUNTER_CONFIG_INFO_COUNT_UP, \ .channels = 2, \ }, \ .i2c = I2C_DT_SPEC_INST_GET(index), \ .int_gpios = GPIO_DT_SPEC_INST_GET_OR(index, int_gpios, {0}), \ }; \ \ DEVICE_DT_INST_DEFINE(index, mcp7940n_init, NULL, \ &mcp7940n_data_##index, \ &mcp7940n_config_##index, \ POST_KERNEL, \ CONFIG_COUNTER_INIT_PRIORITY, \ &mcp7940n_api); DT_INST_FOREACH_STATUS_OKAY(INST_DT_MCP7904N); ```
/content/code_sandbox/drivers/counter/rtc_mcp7940n.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
6,066
```c /* * */ #include <zephyr/drivers/counter.h> #include <zephyr/spinlock.h> #include <zephyr/irq.h> #include <zephyr/arch/cpu.h> #include <string.h> #define DT_DRV_COMPAT andestech_atcpit100 /* register definitions */ #define REG_IDR 0x00 /* ID and Revision Reg. */ #define REG_CFG 0x10 /* Configuration Reg. */ #define REG_INTE 0x14 /* Interrupt Enable Reg. */ #define REG_ISTA 0x18 /* Interrupt Status Reg. */ #define REG_CHEN 0x1C /* Channel Enable Reg. */ #define REG_CTRL0 0x20 /* Channel 0 Control Reg. */ #define REG_RELD0 0x24 /* Channel 0 Reload Reg. */ #define REG_CNTR0 0x28 /* Channel 0 Counter Reg. */ #define REG_CTRL1 0x30 /* Channel 1 Control Reg. */ #define REG_RELD1 0x34 /* Channel 1 Reload Reg. */ #define REG_CNTR1 0x38 /* Channel 1 Counter Reg. */ #define REG_CTRL2 0x40 /* Channel 2 Control Reg. */ #define REG_RELD2 0x44 /* Channel 2 Reload Reg. */ #define REG_CNTR2 0x48 /* Channel 2 Counter Reg. */ #define REG_CTRL3 0x50 /* Channel 3 Control Reg. */ #define REG_RELD3 0x54 /* Channel 3 Reload Reg. */ #define REG_CNTR3 0x58 /* Channel 3 Counter Reg. */ #define PIT_BASE (((const struct atcpit100_config *)(dev)->config)->base) #define PIT_INTE(dev) (PIT_BASE + REG_INTE) #define PIT_ISTA(dev) (PIT_BASE + REG_ISTA) #define PIT_CHEN(dev) (PIT_BASE + REG_CHEN) #define PIT_CH_CTRL(dev, ch) (PIT_BASE + REG_CTRL0 + (ch << 4)) #define PIT_CH_RELD(dev, ch) (PIT_BASE + REG_RELD0 + (ch << 4)) #define PIT_CH_CNTR(dev, ch) (PIT_BASE + REG_CNTR0 + (ch << 4)) #define CTRL_CH_SRC_PCLK BIT(3) #define CTRL_CH_MODE_32BIT BIT(0) #define CHANNEL_NUM (4) #define CH_NUM_PER_COUNTER (CHANNEL_NUM - 1) #define TIMER0_CHANNEL(ch) BIT(((ch) * CHANNEL_NUM)) typedef void (*atcpit100_cfg_func_t)(void); struct atcpit100_config { struct counter_config_info info; uint32_t base; uint32_t divider; uint32_t irq_num; atcpit100_cfg_func_t cfg_func; }; struct counter_atcpit100_ch_data { counter_alarm_callback_t alarm_callback; void *alarm_user_data; }; struct atcpit100_data { counter_top_callback_t top_callback; void *top_user_data; uint32_t guard_period; struct k_spinlock lock; struct counter_atcpit100_ch_data ch_data[CH_NUM_PER_COUNTER]; }; static inline uint32_t get_current_tick(const struct device *dev, uint32_t ch) { const struct atcpit100_config *config = dev->config; uint32_t top, now_cnt; /* Preload cycles is reload register + 1 */ top = sys_read32(PIT_CH_RELD(dev, ch)) + 1; now_cnt = top - sys_read32(PIT_CH_CNTR(dev, ch)); return (now_cnt / config->divider); } static void atcpit100_irq_handler(void *arg) { struct device *dev = (struct device *)arg; struct atcpit100_data *data = dev->data; counter_alarm_callback_t cb; uint32_t int_status, int_enable, ch_enable, cur_ticks; uint8_t i; ch_enable = sys_read32(PIT_CHEN(dev)); int_enable = sys_read32(PIT_INTE(dev)); int_status = sys_read32(PIT_ISTA(dev)); if (int_status & TIMER0_CHANNEL(3)) { if (data->top_callback) { data->top_callback(dev, data->top_user_data); } } for (i = 0; i < CH_NUM_PER_COUNTER; i++) { if (int_status & TIMER0_CHANNEL(i)) { int_enable &= ~TIMER0_CHANNEL(i); ch_enable &= ~TIMER0_CHANNEL(i); } } /* Disable channel and interrupt */ sys_write32(int_enable, PIT_INTE(dev)); sys_write32(ch_enable, PIT_CHEN(dev)); /* Clear interrupt status */ sys_write32(int_status, PIT_ISTA(dev)); for (i = 0; i < CH_NUM_PER_COUNTER; i++) { if (int_status & TIMER0_CHANNEL(i)) { cur_ticks = get_current_tick(dev, 3); cb = data->ch_data[i].alarm_callback; data->ch_data[i].alarm_callback = NULL; if (cb != NULL) { cb(dev, i, cur_ticks, data->ch_data[i].alarm_user_data); } } } } static int counter_atcpit100_init(const struct device *dev) { const struct atcpit100_config *config = dev->config; uint32_t reg; /* Disable all channels */ sys_write32(0, PIT_CHEN(dev)); /* Channel 0 ~ 3, 32 bits timer, PCLK source */ reg = CTRL_CH_MODE_32BIT | CTRL_CH_SRC_PCLK; sys_write32(reg, PIT_CH_CTRL(dev, 0)); sys_write32(reg, PIT_CH_CTRL(dev, 1)); sys_write32(reg, PIT_CH_CTRL(dev, 2)); sys_write32(reg, PIT_CH_CTRL(dev, 3)); /* Disable all interrupt and clear all pending interrupt */ sys_write32(0, PIT_INTE(dev)); sys_write32(UINT32_MAX, PIT_ISTA(dev)); /* Select channel 3 as default counter and set max top value */ reg = config->info.max_top_value * config->divider; /* Set cycle - 1 to reload register */ sys_write32((reg - 1), PIT_CH_RELD(dev, 3)); config->cfg_func(); irq_enable(config->irq_num); return 0; } static int atcpit100_start(const struct device *dev) { struct atcpit100_data *data = dev->data; k_spinlock_key_t key; uint32_t reg; key = k_spin_lock(&data->lock); /* Enable channel */ reg = sys_read32(PIT_CHEN(dev)); reg |= TIMER0_CHANNEL(3); sys_write32(reg, PIT_CHEN(dev)); k_spin_unlock(&data->lock, key); return 0; } static int atcpit100_stop(const struct device *dev) { struct atcpit100_data *data = dev->data; k_spinlock_key_t key; uint32_t reg; key = k_spin_lock(&data->lock); /* Disable channel interrupt */ reg = sys_read32(PIT_INTE(dev)); reg &= ~TIMER0_CHANNEL(3); sys_write32(reg, PIT_INTE(dev)); /* Disable channel */ reg = sys_read32(PIT_CHEN(dev)); reg &= ~TIMER0_CHANNEL(3); sys_write32(reg, PIT_CHEN(dev)); /* Clear interrupt status */ sys_write32(TIMER0_CHANNEL(3), PIT_ISTA(dev)); k_spin_unlock(&data->lock, key); return 0; } static int atcpit100_get_value(const struct device *dev, uint32_t *ticks) { struct atcpit100_data *data = dev->data; k_spinlock_key_t key; key = k_spin_lock(&data->lock); *ticks = get_current_tick(dev, 3); k_spin_unlock(&data->lock, key); return 0; } static int atcpit100_set_alarm(const struct device *dev, uint8_t chan_id, const struct counter_alarm_cfg *alarm_cfg) { const struct atcpit100_config *config = dev->config; struct atcpit100_data *data = dev->data; uint32_t top, now_cnt, remain_cnt, alarm_cnt, flags, reg; k_spinlock_key_t key; int err = 0; if (chan_id >= CH_NUM_PER_COUNTER) { return -ENOTSUP; } if (!alarm_cfg->callback) { return -EINVAL; } if (data->ch_data[chan_id].alarm_callback) { return -EBUSY; } key = k_spin_lock(&data->lock); /* Preload cycles is reload register + 1 */ top = sys_read32(PIT_CH_RELD(dev, 3)) + 1; remain_cnt = sys_read32(PIT_CH_CNTR(dev, 3)); alarm_cnt = alarm_cfg->ticks * config->divider; if (alarm_cnt > top) { err = -EINVAL; goto out; } flags = alarm_cfg->flags; data->ch_data[chan_id].alarm_callback = alarm_cfg->callback; data->ch_data[chan_id].alarm_user_data = alarm_cfg->user_data; if (flags & COUNTER_ALARM_CFG_ABSOLUTE) { uint32_t irq_on_late, max_rel_val; now_cnt = top - remain_cnt; max_rel_val = top - (data->guard_period * config->divider); irq_on_late = flags & COUNTER_ALARM_CFG_EXPIRE_WHEN_LATE; if (now_cnt < alarm_cnt) { /* Absolute alarm is in this round counting */ reg = alarm_cnt - now_cnt; irq_on_late = 0; } else { /* Absolute alarm is in the next round counting */ reg = alarm_cnt + remain_cnt; } if (reg > max_rel_val) { /* Absolute alarm is in the guard period */ err = -ETIME; if (!irq_on_late) { data->ch_data[chan_id].alarm_callback = NULL; goto out; } } if (irq_on_late) { /* Trigger interrupt immediately */ reg = 1; } } else { /* Round up decreasing counter to tick boundary */ now_cnt = remain_cnt + config->divider - 1; now_cnt = (now_cnt / config->divider) * config->divider; /* Adjusting relative alarm counter to tick boundary */ reg = alarm_cnt - (now_cnt - remain_cnt); } /* Set cycle - 1 to reload register */ sys_write32((reg - 1), PIT_CH_RELD(dev, chan_id)); /* Enable channel interrupt */ reg = sys_read32(PIT_INTE(dev)); reg |= TIMER0_CHANNEL(chan_id); sys_write32(reg, PIT_INTE(dev)); /* Enable channel */ reg = sys_read32(PIT_CHEN(dev)); reg |= TIMER0_CHANNEL(chan_id); sys_write32(reg, PIT_CHEN(dev)); out: k_spin_unlock(&data->lock, key); return err; } static int atcpit100_cancel_alarm(const struct device *dev, uint8_t chan_id) { struct atcpit100_data *data = dev->data; k_spinlock_key_t key; uint32_t reg; if (chan_id >= CH_NUM_PER_COUNTER) { return -ENOTSUP; } key = k_spin_lock(&data->lock); /* Disable channel interrupt */ reg = sys_read32(PIT_INTE(dev)); reg &= ~TIMER0_CHANNEL(chan_id); sys_write32(reg, PIT_INTE(dev)); /* Disable channel */ reg = sys_read32(PIT_CHEN(dev)); reg &= ~TIMER0_CHANNEL(chan_id); sys_write32(reg, PIT_CHEN(dev)); /* Clear interrupt status */ sys_write32(TIMER0_CHANNEL(chan_id), PIT_ISTA(dev)); data->ch_data[chan_id].alarm_callback = NULL; k_spin_unlock(&data->lock, key); return 0; } static int atcpit100_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { const struct atcpit100_config *config = dev->config; struct atcpit100_data *data = dev->data; uint32_t ticks, reg, reset_counter = 1; k_spinlock_key_t key; int err = 0; uint8_t i; for (i = 0; i < counter_get_num_of_channels(dev); i++) { if (data->ch_data[i].alarm_callback) { return -EBUSY; } } if (cfg->ticks > config->info.max_top_value) { return -ENOTSUP; } key = k_spin_lock(&data->lock); if (cfg->callback) { /* Disable channel interrupt */ reg = sys_read32(PIT_INTE(dev)); reg &= ~TIMER0_CHANNEL(3); sys_write32(reg, PIT_INTE(dev)); data->top_callback = cfg->callback; data->top_user_data = cfg->user_data; /* Enable channel interrupt */ reg = sys_read32(PIT_INTE(dev)); reg |= TIMER0_CHANNEL(3); sys_write32(reg, PIT_INTE(dev)); } if (cfg->flags & COUNTER_TOP_CFG_DONT_RESET) { /* Don't reset counter */ reset_counter = 0; ticks = get_current_tick(dev, 3); if (ticks >= cfg->ticks) { err = -ETIME; if (cfg->flags & COUNTER_TOP_CFG_RESET_WHEN_LATE) { /* Reset counter if current is late */ reset_counter = 1; } } } /* Set cycle - 1 to reload register */ reg = cfg->ticks * config->divider; sys_write32((reg - 1), PIT_CH_RELD(dev, 3)); if (reset_counter) { /* Disable channel */ reg = sys_read32(PIT_CHEN(dev)); reg &= ~TIMER0_CHANNEL(3); sys_write32(reg, PIT_CHEN(dev)); /* Clear interrupt status */ sys_write32(TIMER0_CHANNEL(3), PIT_ISTA(dev)); /* Enable channel interrupt */ reg = sys_read32(PIT_INTE(dev)); reg |= TIMER0_CHANNEL(3); sys_write32(reg, PIT_INTE(dev)); /* Enable channel */ reg = sys_read32(PIT_CHEN(dev)); reg |= TIMER0_CHANNEL(3); sys_write32(reg, PIT_CHEN(dev)); } k_spin_unlock(&data->lock, key); return err; } static uint32_t atcpit100_get_pending_int(const struct device *dev) { uint32_t reg = sys_read32(PIT_ISTA(dev)); reg &= (TIMER0_CHANNEL(0) | TIMER0_CHANNEL(1) | TIMER0_CHANNEL(2) | TIMER0_CHANNEL(3)); return !(!reg); } static uint32_t atcpit100_get_top_value(const struct device *dev) { const struct atcpit100_config *config = dev->config; uint32_t top = sys_read32(PIT_CH_RELD(dev, 3)) + 1; return (top / config->divider); } static uint32_t atcpit100_get_guard_period(const struct device *dev, uint32_t flags) { struct atcpit100_data *data = dev->data; return data->guard_period; } static int atcpit100_set_guard_period(const struct device *dev, uint32_t ticks, uint32_t flags) { const struct atcpit100_config *config = dev->config; struct atcpit100_data *data = dev->data; uint32_t top = sys_read32(PIT_CH_RELD(dev, 3)) + 1; if ((ticks * config->divider) > top) { return -EINVAL; } data->guard_period = ticks; return 0; } static const struct counter_driver_api atcpit100_driver_api = { .start = atcpit100_start, .stop = atcpit100_stop, .get_value = atcpit100_get_value, .set_alarm = atcpit100_set_alarm, .cancel_alarm = atcpit100_cancel_alarm, .set_top_value = atcpit100_set_top_value, .get_pending_int = atcpit100_get_pending_int, .get_top_value = atcpit100_get_top_value, .get_guard_period = atcpit100_get_guard_period, .set_guard_period = atcpit100_set_guard_period, }; #define COUNTER_ATCPIT100_INIT(n) \ static void counter_atcpit100_cfg_##n(void); \ static struct atcpit100_data atcpit100_data_##n; \ \ static const struct atcpit100_config atcpit100_config_##n = { \ .info = { \ .max_top_value = \ (UINT32_MAX/DT_INST_PROP(n, prescaler)),\ .freq = (DT_INST_PROP(n, clock_frequency) / \ DT_INST_PROP(n, prescaler)), \ .flags = COUNTER_CONFIG_INFO_COUNT_UP, \ .channels = CH_NUM_PER_COUNTER, \ }, \ .base = DT_INST_REG_ADDR(n), \ .divider = DT_INST_PROP(n, prescaler), \ .irq_num = DT_INST_IRQN(n), \ .cfg_func = counter_atcpit100_cfg_##n, \ }; \ \ DEVICE_DT_INST_DEFINE(n, \ counter_atcpit100_init, \ NULL, \ &atcpit100_data_##n, \ &atcpit100_config_##n, \ PRE_KERNEL_1, \ CONFIG_KERNEL_INIT_PRIORITY_DEFAULT, \ &atcpit100_driver_api); \ \ static void counter_atcpit100_cfg_##n(void) \ { \ IRQ_CONNECT(DT_INST_IRQN(n), \ DT_INST_IRQ(n, priority), \ atcpit100_irq_handler, \ DEVICE_DT_INST_GET(n), \ 0); \ } DT_INST_FOREACH_STATUS_OKAY(COUNTER_ATCPIT100_INIT) ```
/content/code_sandbox/drivers/counter/counter_andes_atcpit100.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,960
```c /* * */ #define DT_DRV_COMPAT maxim_ds3231 #include <zephyr/device.h> #include <zephyr/drivers/rtc/maxim_ds3231.h> #include <zephyr/drivers/gpio.h> #include <zephyr/drivers/i2c.h> #include <zephyr/kernel.h> #include <zephyr/logging/log.h> #include <zephyr/sys/timeutil.h> #include <zephyr/sys/util.h> LOG_MODULE_REGISTER(DS3231, CONFIG_COUNTER_LOG_LEVEL); #define REG_MONCEN_CENTURY 0x80 #define REG_HOURS_12H 0x40 #define REG_HOURS_PM 0x20 #define REG_HOURS_20 0x20 #define REG_HOURS_10 0x20 #define REG_DAYDATE_DOW 0x40 #define REG_ALARM_IGN 0x80 /* Return lower 32-bits of time as counter value */ #define COUNTER_GET(t) ((uint32_t) (t & UINT32_MAX)) enum { SYNCSM_IDLE, SYNCSM_PREP_READ, SYNCSM_FINISH_READ, SYNCSM_PREP_WRITE, SYNCSM_FINISH_WRITE, }; struct register_map { uint8_t sec; uint8_t min; uint8_t hour; uint8_t dow; uint8_t dom; uint8_t moncen; uint8_t year; struct { uint8_t sec; uint8_t min; uint8_t hour; uint8_t date; } __packed alarm1; struct { uint8_t min; uint8_t hour; uint8_t date; } __packed alarm2; uint8_t ctrl; uint8_t ctrl_stat; uint8_t aging; int8_t temp_units; uint8_t temp_frac256; }; struct ds3231_config { /* Common structure first because generic API expects this here. */ struct counter_config_info generic; struct i2c_dt_spec bus; struct gpio_dt_spec isw_gpios; }; struct ds3231_data { const struct device *ds3231; struct register_map registers; struct k_sem lock; /* Timer structure used for synchronization */ struct k_timer sync_timer; /* Work structures for the various cases of ISW interrupt. */ struct k_work alarm_work; struct k_work sqw_work; struct k_work sync_work; /* Forward ISW interrupt to proper worker. */ struct gpio_callback isw_callback; /* syncclock captured in the last ISW interrupt handler */ uint32_t isw_syncclock; struct maxim_ds3231_syncpoint syncpoint; struct maxim_ds3231_syncpoint new_sp; uint32_t syncclock_base; /* Pointer to the structure used to notify when a synchronize * or set operation completes. Null when nobody's waiting for * such an operation, or when doing a no-notify synchronize * through the signal API. */ union { void *ptr; struct sys_notify *notify; struct k_poll_signal *signal; } sync; /* Handlers and state when using the counter alarm API. */ counter_alarm_callback_t counter_handler[2]; uint32_t counter_ticks[2]; /* Handlers and state for DS3231 alarm API. */ maxim_ds3231_alarm_callback_handler_t alarm_handler[2]; void *alarm_user_data[2]; uint8_t alarm_flags[2]; /* Flags recording requests for ISW monitoring. */ uint8_t isw_mon_req; #define ISW_MON_REQ_Alarm 0x01 #define ISW_MON_REQ_Sync 0x02 /* Status of synchronization operations. */ uint8_t sync_state; bool sync_signal; }; /* * Set and clear specific bits in the control register. * * This function assumes the device register cache is valid and will * update the device only if the value changes as a result of applying * the set and clear changes. * * Caches and returns the value with the changes applied. */ static int sc_ctrl(const struct device *dev, uint8_t set, uint8_t clear) { struct ds3231_data *data = dev->data; const struct ds3231_config *cfg = dev->config; struct register_map *rp = &data->registers; uint8_t ctrl = (rp->ctrl & ~clear) | set; int rc = ctrl; if (rp->ctrl != ctrl) { uint8_t buf[2] = { offsetof(struct register_map, ctrl), ctrl, }; rc = i2c_write_dt(&cfg->bus, buf, sizeof(buf)); if (rc >= 0) { rp->ctrl = ctrl; rc = ctrl; } } return rc; } int maxim_ds3231_ctrl_update(const struct device *dev, uint8_t set_bits, uint8_t clear_bits) { struct ds3231_data *data = dev->data; k_sem_take(&data->lock, K_FOREVER); int rc = sc_ctrl(dev, set_bits, clear_bits); k_sem_give(&data->lock); return rc; } /* * Read the ctrl_stat register then set and clear bits in it. * * OSF, A1F, and A2F will be written with 1s if the corresponding bits * do not appear in either set or clear. This ensures that if any * flag becomes set between the read and the write that indicator will * not be cleared. * * Returns the value as originally read (disregarding the effect of * clears and sets). */ static inline int rsc_stat(const struct device *dev, uint8_t set, uint8_t clear) { uint8_t const ign = MAXIM_DS3231_REG_STAT_OSF | MAXIM_DS3231_ALARM1 | MAXIM_DS3231_ALARM2; struct ds3231_data *data = dev->data; const struct ds3231_config *cfg = dev->config; struct register_map *rp = &data->registers; uint8_t addr = offsetof(struct register_map, ctrl_stat); int rc; rc = i2c_write_read_dt(&cfg->bus, &addr, sizeof(addr), &rp->ctrl_stat, sizeof(rp->ctrl_stat)); if (rc >= 0) { uint8_t stat = rp->ctrl_stat & ~clear; if (rp->ctrl_stat != stat) { uint8_t buf[2] = { addr, stat | (ign & ~(set | clear)), }; rc = i2c_write_dt(&cfg->bus, buf, sizeof(buf)); } if (rc >= 0) { rc = rp->ctrl_stat; } } return rc; } int maxim_ds3231_stat_update(const struct device *dev, uint8_t set_bits, uint8_t clear_bits) { struct ds3231_data *data = dev->data; k_sem_take(&data->lock, K_FOREVER); int rv = rsc_stat(dev, set_bits, clear_bits); k_sem_give(&data->lock); return rv; } /* * Look for current users of the interrupt/square-wave signal and * enable monitoring if and only if at least one consumer is active. */ static void validate_isw_monitoring(const struct device *dev) { struct ds3231_data *data = dev->data; const struct ds3231_config *cfg = dev->config; const struct register_map *rp = &data->registers; uint8_t isw_mon_req = 0; if (rp->ctrl & (MAXIM_DS3231_ALARM1 | MAXIM_DS3231_ALARM2)) { isw_mon_req |= ISW_MON_REQ_Alarm; } if (data->sync_state != SYNCSM_IDLE) { isw_mon_req |= ISW_MON_REQ_Sync; } LOG_DBG("ISW %p : %d ?= %d", cfg->isw_gpios.port, isw_mon_req, data->isw_mon_req); if ((cfg->isw_gpios.port != NULL) && (isw_mon_req != data->isw_mon_req)) { int rc = 0; /* Disable before reconfigure */ rc = gpio_pin_interrupt_configure_dt(&cfg->isw_gpios, GPIO_INT_DISABLE); if ((rc >= 0) && ((isw_mon_req & ISW_MON_REQ_Sync) != (data->isw_mon_req & ISW_MON_REQ_Sync))) { if (isw_mon_req & ISW_MON_REQ_Sync) { rc = sc_ctrl(dev, 0, MAXIM_DS3231_REG_CTRL_INTCN | MAXIM_DS3231_REG_CTRL_RS_Msk); } else { rc = sc_ctrl(dev, MAXIM_DS3231_REG_CTRL_INTCN, 0); } } data->isw_mon_req = isw_mon_req; /* Enable if any requests active */ if ((rc >= 0) && (isw_mon_req != 0)) { rc = gpio_pin_interrupt_configure_dt( &cfg->isw_gpios, GPIO_INT_EDGE_TO_ACTIVE); } LOG_INF("ISW reconfigure to %x: %d", isw_mon_req, rc); } } static const uint8_t *decode_time(struct tm *tp, const uint8_t *rp, bool with_sec) { uint8_t reg; if (with_sec) { reg = *rp++; tp->tm_sec = bcd2bin(reg & 0x7F); } reg = *rp++; tp->tm_min = bcd2bin(reg & 0x7F); reg = *rp++; tp->tm_hour = (reg & 0x0F); if (REG_HOURS_12H & reg) { /* 12-hour */ if (REG_HOURS_10 & reg) { tp->tm_hour += 10; } if (REG_HOURS_PM & reg) { tp->tm_hour += 12; } } else { /* 24 hour */ tp->tm_hour += 10 * ((reg >> 4) & 0x03); } return rp; } static uint8_t decode_alarm(const uint8_t *ap, bool with_sec, time_t *tp) { struct tm tm = { /* tm_year zero is 1900 with underflows a 32-bit counter * representation. Use 1978-01, the first January after the * POSIX epoch where the first day of the month is the first * day of the week. */ .tm_year = 78, }; const uint8_t *dp = decode_time(&tm, ap, with_sec); uint8_t flags = 0; uint8_t amf = MAXIM_DS3231_ALARM_FLAGS_IGNDA; /* Done decoding time, now decode day/date. */ if (REG_DAYDATE_DOW & *dp) { flags |= MAXIM_DS3231_ALARM_FLAGS_DOW; /* Because tm.tm_wday does not contribute to the UNIX * time that the civil time translates into, we need * to also record the tm_mday for our selected base * 1978-01 that will produce the correct tm_wday. */ tm.tm_mday = (*dp & 0x07); tm.tm_wday = tm.tm_mday - 1; } else { tm.tm_mday = bcd2bin(*dp & 0x3F); } /* Walk backwards to extract the alarm mask flags. */ while (true) { if (REG_ALARM_IGN & *dp) { flags |= amf; } amf >>= 1; if (dp-- == ap) { break; } } /* Convert to the reduced representation. */ *tp = timeutil_timegm(&tm); return flags; } static int encode_alarm(uint8_t *ap, bool with_sec, time_t time, uint8_t flags) { struct tm tm; uint8_t val; (void)gmtime_r(&time, &tm); /* For predictable behavior the low 4 bits of flags * (corresponding to AxMy) must be 0b1111, 0b1110, 0b1100, * 0b1000, or 0b0000. This corresponds to the bitwise inverse * being one less than a power of two. */ if (!is_power_of_two(1U + (0x0F & ~flags))) { LOG_DBG("invalid alarm mask in flags: %02x", flags); return -EINVAL; } if (with_sec) { if (flags & MAXIM_DS3231_ALARM_FLAGS_IGNSE) { val = REG_ALARM_IGN; } else { val = bin2bcd(tm.tm_sec); } *ap++ = val; } if (flags & MAXIM_DS3231_ALARM_FLAGS_IGNMN) { val = REG_ALARM_IGN; } else { val = bin2bcd(tm.tm_min); } *ap++ = val; if (flags & MAXIM_DS3231_ALARM_FLAGS_IGNHR) { val = REG_ALARM_IGN; } else { val = bin2bcd(tm.tm_hour); } *ap++ = val; if (flags & MAXIM_DS3231_ALARM_FLAGS_IGNDA) { val = REG_ALARM_IGN; } else if (flags & MAXIM_DS3231_ALARM_FLAGS_DOW) { val = REG_DAYDATE_DOW | (tm.tm_wday + 1); } else { val = bin2bcd(tm.tm_mday); } *ap++ = val; return 0; } static uint32_t decode_rtc(struct ds3231_data *data) { struct tm tm = { 0 }; const struct register_map *rp = &data->registers; time_t t; decode_time(&tm, &rp->sec, true); tm.tm_wday = (rp->dow & 0x07) - 1; tm.tm_mday = bcd2bin(rp->dom & 0x3F); tm.tm_mon = 10 * (((0xF0 & ~REG_MONCEN_CENTURY) & rp->moncen) >> 4) + (rp->moncen & 0x0F) - 1; tm.tm_year = bcd2bin(rp->year); if (REG_MONCEN_CENTURY & rp->moncen) { tm.tm_year += 100; } t = timeutil_timegm(&tm); return COUNTER_GET(t); } static int update_registers(const struct device *dev) { struct ds3231_data *data = dev->data; const struct ds3231_config *cfg = dev->config; uint32_t syncclock; int rc; uint8_t addr = 0; data->syncclock_base = maxim_ds3231_read_syncclock(dev); rc = i2c_write_read_dt(&cfg->bus, &addr, sizeof(addr), &data->registers, sizeof(data->registers)); syncclock = maxim_ds3231_read_syncclock(dev); if (rc < 0) { return rc; } return 0; } int maxim_ds3231_get_alarm(const struct device *dev, uint8_t id, struct maxim_ds3231_alarm *cp) { struct ds3231_data *data = dev->data; const struct ds3231_config *cfg = dev->config; int rv = 0; uint8_t addr; uint8_t len; if (id == 0) { addr = offsetof(struct register_map, alarm1); len = sizeof(data->registers.alarm1); } else if (id < cfg->generic.channels) { addr = offsetof(struct register_map, alarm2); len = sizeof(data->registers.alarm2); } else { rv = -EINVAL; goto out; } k_sem_take(&data->lock, K_FOREVER); /* Update alarm structure */ uint8_t *rbp = &data->registers.sec + addr; rv = i2c_write_read_dt(&cfg->bus, &addr, sizeof(addr), rbp, len); if (rv < 0) { LOG_DBG("get_config at %02x failed: %d\n", addr, rv); goto out_locked; } *cp = (struct maxim_ds3231_alarm){ 0 }; cp->flags = decode_alarm(rbp, (id == 0), &cp->time); cp->handler = data->alarm_handler[id]; cp->user_data = data->alarm_user_data[id]; out_locked: k_sem_give(&data->lock); out: return rv; } static int cancel_alarm(const struct device *dev, uint8_t id) { struct ds3231_data *data = dev->data; data->alarm_handler[id] = NULL; data->alarm_user_data[id] = NULL; return sc_ctrl(dev, 0, MAXIM_DS3231_ALARM1 << id); } static int ds3231_counter_cancel_alarm(const struct device *dev, uint8_t id) { struct ds3231_data *data = dev->data; const struct ds3231_config *cfg = dev->config; int rv = 0; if (id >= cfg->generic.channels) { rv = -EINVAL; goto out; } k_sem_take(&data->lock, K_FOREVER); rv = cancel_alarm(dev, id); k_sem_give(&data->lock); out: /* Throw away information counter API disallows */ if (rv >= 0) { rv = 0; } return rv; } static int set_alarm(const struct device *dev, uint8_t id, const struct maxim_ds3231_alarm *cp) { struct ds3231_data *data = dev->data; const struct ds3231_config *cfg = dev->config; uint8_t addr; uint8_t len; if (id == 0) { addr = offsetof(struct register_map, alarm1); len = sizeof(data->registers.alarm1); } else if (id < cfg->generic.channels) { addr = offsetof(struct register_map, alarm2); len = sizeof(data->registers.alarm2); } else { return -EINVAL; } uint8_t buf[5] = { addr }; int rc = encode_alarm(buf + 1, (id == 0), cp->time, cp->flags); if (rc < 0) { return rc; } /* @todo resolve race condition: a previously stored alarm may * trigger between clear of AxF and the write of the new alarm * control. */ rc = rsc_stat(dev, 0U, (MAXIM_DS3231_ALARM1 << id)); if (rc >= 0) { rc = i2c_write_dt(&cfg->bus, buf, len + 1); } if ((rc >= 0) && (cp->handler != NULL)) { rc = sc_ctrl(dev, MAXIM_DS3231_ALARM1 << id, 0); } if (rc >= 0) { memmove(&data->registers.sec + addr, buf + 1, len); data->alarm_handler[id] = cp->handler; data->alarm_user_data[id] = cp->user_data; data->alarm_flags[id] = cp->flags; validate_isw_monitoring(dev); } return rc; } int maxim_ds3231_set_alarm(const struct device *dev, uint8_t id, const struct maxim_ds3231_alarm *cp) { struct ds3231_data *data = dev->data; k_sem_take(&data->lock, K_FOREVER); int rc = set_alarm(dev, id, cp); k_sem_give(&data->lock); return rc; } int maxim_ds3231_check_alarms(const struct device *dev) { struct ds3231_data *data = dev->data; const struct register_map *rp = &data->registers; uint8_t mask = (MAXIM_DS3231_ALARM1 | MAXIM_DS3231_ALARM2); k_sem_take(&data->lock, K_FOREVER); /* Fetch and clear only the alarm flags that are not * interrupt-enabled. */ int rv = rsc_stat(dev, 0U, (rp->ctrl & mask) ^ mask); if (rv >= 0) { rv &= mask; } k_sem_give(&data->lock); return rv; } static int check_handled_alarms(const struct device *dev) { struct ds3231_data *data = dev->data; const struct register_map *rp = &data->registers; uint8_t mask = (MAXIM_DS3231_ALARM1 | MAXIM_DS3231_ALARM2); /* Fetch and clear only the alarm flags that are * interrupt-enabled. Leave any flags that are not enabled; * it may be an alarm that triggered a wakeup. */ mask &= rp->ctrl; int rv = rsc_stat(dev, 0U, mask); if (rv > 0) { rv &= mask; } return rv; } static void counter_alarm_forwarder(const struct device *dev, uint8_t id, uint32_t syncclock, void *ud) { /* Dummy handler marking a counter callback. */ } static void alarm_worker(struct k_work *work) { struct ds3231_data *data = CONTAINER_OF(work, struct ds3231_data, alarm_work); const struct device *ds3231 = data->ds3231; const struct ds3231_config *cfg = ds3231->config; k_sem_take(&data->lock, K_FOREVER); int af = check_handled_alarms(ds3231); while (af > 0) { uint8_t id; for (id = 0; id < cfg->generic.channels; ++id) { if ((af & (MAXIM_DS3231_ALARM1 << id)) == 0) { continue; } maxim_ds3231_alarm_callback_handler_t handler = data->alarm_handler[id]; void *ud = data->alarm_user_data[id]; if (data->alarm_flags[id] & MAXIM_DS3231_ALARM_FLAGS_AUTODISABLE) { int rc = cancel_alarm(ds3231, id); LOG_DBG("autodisable %d: %d", id, rc); validate_isw_monitoring(ds3231); } if (handler == counter_alarm_forwarder) { counter_alarm_callback_t cb = data->counter_handler[id]; uint32_t ticks = data->counter_ticks[id]; data->counter_handler[id] = NULL; data->counter_ticks[id] = 0; if (cb) { k_sem_give(&data->lock); cb(ds3231, id, ticks, ud); k_sem_take(&data->lock, K_FOREVER); } } else if (handler != NULL) { k_sem_give(&data->lock); handler(ds3231, id, data->isw_syncclock, ud); k_sem_take(&data->lock, K_FOREVER); } } af = check_handled_alarms(ds3231); } k_sem_give(&data->lock); if (af < 0) { LOG_ERR("failed to read alarm flags"); return; } LOG_DBG("ALARM %02x at %u latency %u", af, data->isw_syncclock, maxim_ds3231_read_syncclock(ds3231) - data->isw_syncclock); } static void sqw_worker(struct k_work *work) { struct ds3231_data *data = CONTAINER_OF(work, struct ds3231_data, sqw_work); uint32_t syncclock = maxim_ds3231_read_syncclock(data->ds3231); /* This is a placeholder for potential application-controlled * use of the square wave functionality. */ LOG_DBG("SQW %u latency %u", data->isw_syncclock, syncclock - data->isw_syncclock); } static int read_time(const struct device *dev, time_t *time) { struct ds3231_data *data = dev->data; const struct ds3231_config *cfg = dev->config; uint8_t addr = 0; int rc = i2c_write_read_dt(&cfg->bus, &addr, sizeof(addr), &data->registers, 7); if (rc >= 0) { *time = decode_rtc(data); } return rc; } static int ds3231_counter_get_value(const struct device *dev, uint32_t *ticks) { struct ds3231_data *data = dev->data; time_t time = 0; k_sem_take(&data->lock, K_FOREVER); int rc = read_time(dev, &time); k_sem_give(&data->lock); if (rc >= 0) { *ticks = COUNTER_GET(time); } return rc; } static void sync_finish(const struct device *dev, int rc) { struct ds3231_data *data = dev->data; struct sys_notify *notify = NULL; struct k_poll_signal *signal = NULL; if (data->sync_signal) { signal = data->sync.signal; } else { notify = data->sync.notify; } data->sync.ptr = NULL; data->sync_signal = false; data->sync_state = SYNCSM_IDLE; (void)validate_isw_monitoring(dev); LOG_DBG("sync complete, notify %d to %p or %p\n", rc, notify, signal); k_sem_give(&data->lock); if (notify != NULL) { maxim_ds3231_notify_callback cb = (maxim_ds3231_notify_callback)sys_notify_finalize(notify, rc); if (cb) { cb(dev, notify, rc); } } else if (signal != NULL) { k_poll_signal_raise(signal, rc); } } static void sync_prep_read(const struct device *dev) { struct ds3231_data *data = dev->data; int rc = sc_ctrl(dev, 0U, MAXIM_DS3231_REG_CTRL_INTCN | MAXIM_DS3231_REG_CTRL_RS_Msk); if (rc < 0) { sync_finish(dev, rc); return; } data->sync_state = SYNCSM_FINISH_READ; validate_isw_monitoring(dev); } static void sync_finish_read(const struct device *dev) { struct ds3231_data *data = dev->data; time_t time = 0; (void)read_time(dev, &time); data->syncpoint.rtc.tv_sec = time; data->syncpoint.rtc.tv_nsec = 0; data->syncpoint.syncclock = data->isw_syncclock; sync_finish(dev, 0); } static void sync_timer_handler(struct k_timer *tmr) { struct ds3231_data *data = CONTAINER_OF(tmr, struct ds3231_data, sync_timer); LOG_INF("sync_timer fired"); k_work_submit(&data->sync_work); } static void sync_prep_write(const struct device *dev) { struct ds3231_data *data = dev->data; uint32_t syncclock = maxim_ds3231_read_syncclock(dev); uint32_t offset = syncclock - data->new_sp.syncclock; uint32_t syncclock_Hz = maxim_ds3231_syncclock_frequency(dev); uint32_t offset_s = offset / syncclock_Hz; uint32_t offset_ms = (offset % syncclock_Hz) * 1000U / syncclock_Hz; time_t when = data->new_sp.rtc.tv_sec; when += offset_s; offset_ms += data->new_sp.rtc.tv_nsec / NSEC_PER_USEC / USEC_PER_MSEC; if (offset_ms >= MSEC_PER_SEC) { offset_ms -= MSEC_PER_SEC; } else { when += 1; } uint32_t rem_ms = MSEC_PER_SEC - offset_ms; if (rem_ms < 5) { when += 1; rem_ms += MSEC_PER_SEC; } data->new_sp.rtc.tv_sec = when; data->new_sp.rtc.tv_nsec = 0; data->sync_state = SYNCSM_FINISH_WRITE; k_timer_start(&data->sync_timer, K_MSEC(rem_ms), K_NO_WAIT); LOG_INF("sync %u in %u ms after %u", COUNTER_GET(when), rem_ms, syncclock); } static void sync_finish_write(const struct device *dev) { struct ds3231_data *data = dev->data; const struct ds3231_config *cfg = dev->config; time_t when = data->new_sp.rtc.tv_sec; struct tm tm; uint8_t buf[8]; uint8_t *bp = buf; uint8_t val; *bp++ = offsetof(struct register_map, sec); (void)gmtime_r(&when, &tm); val = bin2bcd(tm.tm_sec); *bp++ = val; val = bin2bcd(tm.tm_min); *bp++ = val; val = bin2bcd(tm.tm_hour); *bp++ = val; *bp++ = 1 + tm.tm_wday; val = bin2bcd(tm.tm_mday); *bp++ = val; tm.tm_mon += 1; val = bin2bcd(tm.tm_mon); if (tm.tm_year >= 100) { tm.tm_year -= 100; val |= REG_MONCEN_CENTURY; } *bp++ = val; val = bin2bcd(tm.tm_year); *bp++ = val; uint32_t syncclock = maxim_ds3231_read_syncclock(dev); int rc = i2c_write_dt(&cfg->bus, buf, bp - buf); if (rc >= 0) { data->syncpoint.rtc.tv_sec = when; data->syncpoint.rtc.tv_nsec = 0; data->syncpoint.syncclock = syncclock; LOG_INF("sync %u at %u", COUNTER_GET(when), syncclock); } sync_finish(dev, rc); } static void sync_worker(struct k_work *work) { struct ds3231_data *data = CONTAINER_OF(work, struct ds3231_data, sync_work); uint32_t syncclock = maxim_ds3231_read_syncclock(data->ds3231); bool unlock = true; k_sem_take(&data->lock, K_FOREVER); LOG_DBG("SYNC.%u %u latency %u", data->sync_state, data->isw_syncclock, syncclock - data->isw_syncclock); switch (data->sync_state) { default: case SYNCSM_IDLE: break; case SYNCSM_PREP_READ: sync_prep_read(data->ds3231); break; case SYNCSM_FINISH_READ: sync_finish_read(data->ds3231); break; case SYNCSM_PREP_WRITE: sync_prep_write(data->ds3231); break; case SYNCSM_FINISH_WRITE: sync_finish_write(data->ds3231); unlock = false; break; } if (unlock) { k_sem_give(&data->lock); } } static void isw_gpio_callback(const struct device *port, struct gpio_callback *cb, uint32_t pins) { struct ds3231_data *data = CONTAINER_OF(cb, struct ds3231_data, isw_callback); data->isw_syncclock = maxim_ds3231_read_syncclock(data->ds3231); if (data->registers.ctrl & MAXIM_DS3231_REG_CTRL_INTCN) { k_work_submit(&data->alarm_work); } else if (data->sync_state != SYNCSM_IDLE) { k_work_submit(&data->sync_work); } else { k_work_submit(&data->sqw_work); } } int z_impl_maxim_ds3231_get_syncpoint(const struct device *dev, struct maxim_ds3231_syncpoint *syncpoint) { struct ds3231_data *data = dev->data; int rv = 0; k_sem_take(&data->lock, K_FOREVER); if (data->syncpoint.rtc.tv_sec == 0) { rv = -ENOENT; } else { __ASSERT_NO_MSG(syncpoint != NULL); *syncpoint = data->syncpoint; } k_sem_give(&data->lock); return rv; } int maxim_ds3231_synchronize(const struct device *dev, struct sys_notify *notify) { const struct ds3231_config *cfg = dev->config; struct ds3231_data *data = dev->data; int rv = 0; if (notify == NULL) { rv = -EINVAL; goto out; } if (cfg->isw_gpios.port == NULL) { rv = -ENOTSUP; goto out; } k_sem_take(&data->lock, K_FOREVER); if (data->sync_state != SYNCSM_IDLE) { rv = -EBUSY; goto out_locked; } data->sync_signal = false; data->sync.notify = notify; data->sync_state = SYNCSM_PREP_READ; out_locked: k_sem_give(&data->lock); if (rv >= 0) { k_work_submit(&data->sync_work); } out: return rv; } int z_impl_maxim_ds3231_req_syncpoint(const struct device *dev, struct k_poll_signal *sig) { const struct ds3231_config *cfg = dev->config; struct ds3231_data *data = dev->data; int rv = 0; if (cfg->isw_gpios.port == NULL) { rv = -ENOTSUP; goto out; } k_sem_take(&data->lock, K_FOREVER); if (data->sync_state != SYNCSM_IDLE) { rv = -EBUSY; goto out_locked; } data->sync_signal = true; data->sync.signal = sig; data->sync_state = SYNCSM_PREP_READ; out_locked: k_sem_give(&data->lock); if (rv >= 0) { k_work_submit(&data->sync_work); } out: return rv; } int maxim_ds3231_set(const struct device *dev, const struct maxim_ds3231_syncpoint *syncpoint, struct sys_notify *notify) { const struct ds3231_config *cfg = dev->config; struct ds3231_data *data = dev->data; int rv = 0; if ((syncpoint == NULL) || (notify == NULL)) { rv = -EINVAL; goto out; } if (cfg->isw_gpios.port == NULL) { rv = -ENOTSUP; goto out; } k_sem_take(&data->lock, K_FOREVER); if (data->sync_state != SYNCSM_IDLE) { rv = -EBUSY; goto out_locked; } data->new_sp = *syncpoint; data->sync_signal = false; data->sync.notify = notify; data->sync_state = SYNCSM_PREP_WRITE; out_locked: k_sem_give(&data->lock); if (rv >= 0) { k_work_submit(&data->sync_work); } out: return rv; } static int ds3231_init(const struct device *dev) { struct ds3231_data *data = dev->data; const struct ds3231_config *cfg = dev->config; int rc; /* Initialize and take the lock */ k_sem_init(&data->lock, 0, 1); data->ds3231 = dev; if (!device_is_ready(cfg->bus.bus)) { LOG_ERR("I2C device not ready"); rc = -ENODEV; goto out; } rc = update_registers(dev); if (rc < 0) { LOG_WRN("Failed to fetch registers: %d", rc); goto out; } /* INTCN and AxIE to power-up default, RS to 1 Hz */ rc = sc_ctrl(dev, MAXIM_DS3231_REG_CTRL_INTCN, MAXIM_DS3231_REG_CTRL_RS_Msk | MAXIM_DS3231_ALARM1 | MAXIM_DS3231_ALARM2); if (rc < 0) { LOG_WRN("Failed to reset config: %d", rc); goto out; } /* Do not clear pending flags in the status register. This * device may have been used for external wakeup, which can be * detected using the extended API. */ if (cfg->isw_gpios.port != NULL) { if (!gpio_is_ready_dt(&cfg->isw_gpios)) { LOG_ERR("INTn/SQW GPIO device not ready"); rc = -ENODEV; goto out; } k_timer_init(&data->sync_timer, sync_timer_handler, NULL); k_work_init(&data->alarm_work, alarm_worker); k_work_init(&data->sqw_work, sqw_worker); k_work_init(&data->sync_work, sync_worker); gpio_init_callback(&data->isw_callback, isw_gpio_callback, BIT(cfg->isw_gpios.pin)); rc = gpio_pin_configure_dt(&cfg->isw_gpios, GPIO_INPUT); if (rc >= 0) { rc = gpio_pin_interrupt_configure_dt(&cfg->isw_gpios, GPIO_INT_DISABLE); } if (rc >= 0) { rc = gpio_add_callback(cfg->isw_gpios.port, &data->isw_callback); if (rc < 0) { LOG_ERR("Failed to configure ISW callback: %d", rc); } } } out: k_sem_give(&data->lock); LOG_DBG("Initialized %d", rc); if (rc > 0) { rc = 0; } return rc; } static int ds3231_counter_start(const struct device *dev) { return -EALREADY; } static int ds3231_counter_stop(const struct device *dev) { return -ENOTSUP; } int ds3231_counter_set_alarm(const struct device *dev, uint8_t id, const struct counter_alarm_cfg *alarm_cfg) { struct ds3231_data *data = dev->data; const struct register_map *rp = &data->registers; const struct ds3231_config *cfg = dev->config; time_t when; int rc = 0; if (id >= cfg->generic.channels) { rc = -ENOTSUP; goto out; } k_sem_take(&data->lock, K_FOREVER); if (rp->ctrl & (MAXIM_DS3231_ALARM1 << id)) { rc = -EBUSY; goto out_locked; } if ((alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) == 0) { rc = read_time(dev, &when); if (rc >= 0) { when += alarm_cfg->ticks; } } else { when = alarm_cfg->ticks; } struct maxim_ds3231_alarm alarm = { .time = COUNTER_GET(when), .handler = counter_alarm_forwarder, .user_data = alarm_cfg->user_data, .flags = MAXIM_DS3231_ALARM_FLAGS_AUTODISABLE, }; if (rc >= 0) { data->counter_handler[id] = alarm_cfg->callback; data->counter_ticks[id] = COUNTER_GET(alarm.time); rc = set_alarm(dev, id, &alarm); } out_locked: k_sem_give(&data->lock); out: /* Throw away information counter API disallows */ if (rc >= 0) { rc = 0; } return rc; } static uint32_t ds3231_counter_get_top_value(const struct device *dev) { return UINT32_MAX; } static uint32_t ds3231_counter_get_pending_int(const struct device *dev) { return 0; } static int ds3231_counter_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { return -ENOTSUP; } static const struct counter_driver_api ds3231_api = { .start = ds3231_counter_start, .stop = ds3231_counter_stop, .get_value = ds3231_counter_get_value, .set_alarm = ds3231_counter_set_alarm, .cancel_alarm = ds3231_counter_cancel_alarm, .set_top_value = ds3231_counter_set_top_value, .get_pending_int = ds3231_counter_get_pending_int, .get_top_value = ds3231_counter_get_top_value, }; static const struct ds3231_config ds3231_0_config = { .generic = { .max_top_value = UINT32_MAX, .freq = 1, .flags = COUNTER_CONFIG_INFO_COUNT_UP, .channels = 2, }, .bus = I2C_DT_SPEC_INST_GET(0), /* Driver does not currently use 32k GPIO. */ .isw_gpios = GPIO_DT_SPEC_INST_GET_OR(0, isw_gpios, {}), }; static struct ds3231_data ds3231_0_data; #if CONFIG_COUNTER_INIT_PRIORITY <= CONFIG_I2C_INIT_PRIORITY #error CONFIG_COUNTER_INIT_PRIORITY must be greater than I2C_INIT_PRIORITY #endif DEVICE_DT_INST_DEFINE(0, ds3231_init, NULL, &ds3231_0_data, &ds3231_0_config, POST_KERNEL, CONFIG_COUNTER_INIT_PRIORITY, &ds3231_api); #ifdef CONFIG_USERSPACE #include <zephyr/internal/syscall_handler.h> int z_vrfy_maxim_ds3231_get_syncpoint(const struct device *dev, struct maxim_ds3231_syncpoint *syncpoint) { struct maxim_ds3231_syncpoint value; int rv; K_OOPS(K_SYSCALL_SPECIFIC_DRIVER(dev, K_OBJ_DRIVER_COUNTER, &ds3231_api)); K_OOPS(K_SYSCALL_MEMORY_WRITE(syncpoint, sizeof(*syncpoint))); rv = z_impl_maxim_ds3231_get_syncpoint(dev, &value); if (rv >= 0) { K_OOPS(k_usermode_to_copy(syncpoint, &value, sizeof(*syncpoint))); } return rv; } #include <zephyr/syscalls/maxim_ds3231_get_syncpoint_mrsh.c> int z_vrfy_maxim_ds3231_req_syncpoint(const struct device *dev, struct k_poll_signal *sig) { K_OOPS(K_SYSCALL_SPECIFIC_DRIVER(dev, K_OBJ_DRIVER_COUNTER, &ds3231_api)); if (sig != NULL) { K_OOPS(K_SYSCALL_OBJ(sig, K_OBJ_POLL_SIGNAL)); } return z_impl_maxim_ds3231_req_syncpoint(dev, sig); } #include <zephyr/syscalls/maxim_ds3231_req_syncpoint_mrsh.c> #endif /* CONFIG_USERSPACE */ ```
/content/code_sandbox/drivers/counter/maxim_ds3231.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
9,359
```c /* * */ #define DT_DRV_COMPAT snps_dw_timers #include <zephyr/device.h> #include <zephyr/drivers/counter.h> #include <zephyr/spinlock.h> #include <zephyr/logging/log.h> #include <zephyr/drivers/reset.h> #include <zephyr/drivers/clock_control.h> LOG_MODULE_REGISTER(dw_timer, CONFIG_COUNTER_LOG_LEVEL); static int counter_dw_timer_get_value(const struct device *timer_dev, uint32_t *ticks); /* DW APB timer register offsets */ #define LOADCOUNT_OFST 0x0 #define CURRENTVAL_OFST 0x4 #define CONTROLREG_OFST 0x8 #define EOI_OFST 0xc #define INTSTAT_OFST 0x10 /* free running mode value */ #define FREE_RUNNING_MODE_VAL 0xFFFFFFFFUL /* DW APB timer control flags */ #define TIMER_CONTROL_ENABLE_BIT 0 #define TIMER_MODE_BIT 1 #define TIMER_INTR_MASK_BIT 2 /* DW APB timer modes */ #define USER_DEFINED_MODE 1 #define FREE_RUNNING_MODE 0 #define DEV_CFG(_dev) ((const struct counter_dw_timer_config *)(_dev)->config) #define DEV_DATA(_dev) ((struct counter_dw_timer_drv_data *const)(_dev)->data) /* Device Configuration */ struct counter_dw_timer_config { struct counter_config_info info; DEVICE_MMIO_NAMED_ROM(timer_mmio); /* clock frequency of timer */ uint32_t freq; #if DT_ANY_INST_HAS_PROP_STATUS_OKAY(clocks) /* clock controller dev instance */ const struct device *clk_dev; /* identifier for timer to get clock freq from clk manager */ clock_control_subsys_t clkid; #endif #if DT_ANY_INST_HAS_PROP_STATUS_OKAY(resets) /* reset controller device configuration*/ const struct reset_dt_spec reset; #endif /* interrupt config function ptr */ void (*irq_config)(void); }; /* Driver data */ struct counter_dw_timer_drv_data { /* mmio address mapping info */ DEVICE_MMIO_NAMED_RAM(timer_mmio); #if DT_ANY_INST_HAS_PROP_STATUS_OKAY(clocks) /* clock frequency of timer */ uint32_t freq; #endif /* spin lock to protect user data */ struct k_spinlock lock; /* top callback function */ counter_top_callback_t top_cb; /* alarm callback function */ counter_alarm_callback_t alarm_cb; /* private user data */ void *prv_data; }; static void counter_dw_timer_irq_handler(const struct device *timer_dev) { uint32_t ticks = 0; uintptr_t reg_base = DEVICE_MMIO_NAMED_GET(timer_dev, timer_mmio); struct counter_dw_timer_drv_data *const data = DEV_DATA(timer_dev); k_spinlock_key_t key; counter_alarm_callback_t alarm_cb = data->alarm_cb; /* read EOI register to clear interrupt flag */ sys_read32(reg_base + EOI_OFST); counter_dw_timer_get_value(timer_dev, &ticks); key = k_spin_lock(&data->lock); /* In case of alarm, mask interrupt and disable the callback. User * can configure the alarm in same context within callback function. */ if (data->alarm_cb) { sys_set_bit(reg_base + CONTROLREG_OFST, TIMER_INTR_MASK_BIT); data->alarm_cb = NULL; alarm_cb(timer_dev, 0, ticks, data->prv_data); } else if (data->top_cb) { data->top_cb(timer_dev, data->prv_data); } k_spin_unlock(&data->lock, key); } static int counter_dw_timer_start(const struct device *dev) { uintptr_t reg_base = DEVICE_MMIO_NAMED_GET(dev, timer_mmio); /* disable timer before starting in free-running mode */ sys_clear_bit(reg_base + CONTROLREG_OFST, TIMER_CONTROL_ENABLE_BIT); /* starting timer in free running mode */ sys_clear_bit(reg_base + CONTROLREG_OFST, TIMER_MODE_BIT); sys_set_bit(reg_base + CONTROLREG_OFST, TIMER_INTR_MASK_BIT); sys_write32(FREE_RUNNING_MODE_VAL, reg_base + LOADCOUNT_OFST); /* enable timer */ sys_set_bit(reg_base + CONTROLREG_OFST, TIMER_CONTROL_ENABLE_BIT); return 0; } int counter_dw_timer_disable(const struct device *dev) { uintptr_t reg_base = DEVICE_MMIO_NAMED_GET(dev, timer_mmio); /* stop timer */ sys_clear_bit(reg_base + CONTROLREG_OFST, TIMER_CONTROL_ENABLE_BIT); return 0; } static uint32_t counter_dw_timer_get_top_value(const struct device *timer_dev) { uint32_t top_val = 0; uintptr_t reg_base = DEVICE_MMIO_NAMED_GET(timer_dev, timer_mmio); /* get the current top value from load count register */ top_val = sys_read32(reg_base + LOADCOUNT_OFST); return top_val; } static int counter_dw_timer_get_value(const struct device *timer_dev, uint32_t *ticks) { uintptr_t reg_base = DEVICE_MMIO_NAMED_GET(timer_dev, timer_mmio); /* current value of the current value register */ *ticks = sys_read32(reg_base + CURRENTVAL_OFST); return 0; } static int counter_dw_timer_set_top_value(const struct device *timer_dev, const struct counter_top_cfg *top_cfg) { uintptr_t reg_base = DEVICE_MMIO_NAMED_GET(timer_dev, timer_mmio); struct counter_dw_timer_drv_data *const data = DEV_DATA(timer_dev); k_spinlock_key_t key; if (top_cfg == NULL) { LOG_ERR("Invalid top value configuration"); return -EINVAL; } /* top value cannot be updated without reset */ if (top_cfg->flags & COUNTER_TOP_CFG_DONT_RESET) { LOG_ERR("Updating top value without reset is not supported"); return -ENOTSUP; } key = k_spin_lock(&data->lock); /* top value cannot be updated if the alarm is active */ if (data->alarm_cb) { k_spin_unlock(&data->lock, key); LOG_ERR("Top value cannot be updated, alarm is active!"); return -EBUSY; } if (!top_cfg->callback) { /* mask an interrupt if callback is not passed */ sys_set_bit(reg_base + CONTROLREG_OFST, TIMER_INTR_MASK_BIT); } else { /* unmask interrupt if callback is passed */ sys_clear_bit(reg_base + CONTROLREG_OFST, TIMER_INTR_MASK_BIT); } data->top_cb = top_cfg->callback; data->prv_data = top_cfg->user_data; /* top value can be loaded only when timer is stopped and re-enabled */ sys_clear_bit(reg_base + CONTROLREG_OFST, TIMER_CONTROL_ENABLE_BIT); /* configuring timer in user-defined mode */ sys_set_bit(reg_base + CONTROLREG_OFST, TIMER_MODE_BIT); /* set new top value */ sys_write32(top_cfg->ticks, reg_base + LOADCOUNT_OFST); sys_set_bit(reg_base + CONTROLREG_OFST, TIMER_CONTROL_ENABLE_BIT); k_spin_unlock(&data->lock, key); return 0; } static int counter_dw_timer_set_alarm(const struct device *timer_dev, uint8_t chan_id, const struct counter_alarm_cfg *alarm_cfg) { ARG_UNUSED(chan_id); uintptr_t reg_base = DEVICE_MMIO_NAMED_GET(timer_dev, timer_mmio); struct counter_dw_timer_drv_data *const data = DEV_DATA(timer_dev); k_spinlock_key_t key; if (alarm_cfg == NULL) { LOG_ERR("Invalid alarm configuration"); return -EINVAL; } /* Alarm callback is mandatory */ if (!alarm_cfg->callback) { LOG_ERR("Alarm callback function cannot be null"); return -EINVAL; } /* absolute alarm is not supported as interrupts are triggered * only when the counter reaches 0(downcounter) */ if (alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) { LOG_ERR("Absolute alarm is not supported"); return -ENOTSUP; } key = k_spin_lock(&data->lock); /* check if alarm is already active */ if (data->alarm_cb != NULL) { LOG_ERR("Alarm is already active\n"); k_spin_unlock(&data->lock, key); return -EBUSY; } data->alarm_cb = alarm_cfg->callback; data->prv_data = alarm_cfg->user_data; sys_clear_bit(reg_base + CONTROLREG_OFST, TIMER_CONTROL_ENABLE_BIT); /* start timer in user-defined mode */ sys_set_bit(reg_base + CONTROLREG_OFST, TIMER_MODE_BIT); sys_clear_bit(reg_base + CONTROLREG_OFST, TIMER_INTR_MASK_BIT); sys_write32(alarm_cfg->ticks, reg_base + LOADCOUNT_OFST); sys_set_bit(reg_base + CONTROLREG_OFST, TIMER_CONTROL_ENABLE_BIT); k_spin_unlock(&data->lock, key); return 0; } static int counter_dw_timer_cancel_alarm(const struct device *timer_dev, uint8_t chan_id) { ARG_UNUSED(chan_id); uintptr_t reg_base = DEVICE_MMIO_NAMED_GET(timer_dev, timer_mmio); struct counter_dw_timer_drv_data *const data = DEV_DATA(timer_dev); k_spinlock_key_t key; key = k_spin_lock(&data->lock); sys_write32(0, reg_base + CONTROLREG_OFST); data->alarm_cb = NULL; data->prv_data = NULL; k_spin_unlock(&data->lock, key); return 0; } uint32_t counter_dw_timer_get_freq(const struct device *timer_dev) { #if DT_ANY_INST_HAS_PROP_STATUS_OKAY(clocks) struct counter_dw_timer_drv_data *const data = DEV_DATA(timer_dev); return data->freq; #else const struct counter_dw_timer_config *config = DEV_CFG(timer_dev); return config->freq; #endif } static const struct counter_driver_api dw_timer_driver_api = { .start = counter_dw_timer_start, .stop = counter_dw_timer_disable, .get_value = counter_dw_timer_get_value, .set_top_value = counter_dw_timer_set_top_value, .get_top_value = counter_dw_timer_get_top_value, .set_alarm = counter_dw_timer_set_alarm, .cancel_alarm = counter_dw_timer_cancel_alarm, .get_freq = counter_dw_timer_get_freq, }; static int counter_dw_timer_init(const struct device *timer_dev) { DEVICE_MMIO_NAMED_MAP(timer_dev, timer_mmio, K_MEM_CACHE_NONE); const struct counter_dw_timer_config *timer_config = DEV_CFG(timer_dev); #if DT_ANY_INST_HAS_PROP_STATUS_OKAY(clocks) || DT_ANY_INST_HAS_PROP_STATUS_OKAY(resets) int ret; #endif /* * get clock rate from clock_frequency property if valid, * otherwise, get clock rate from clock manager */ #if DT_ANY_INST_HAS_PROP_STATUS_OKAY(clocks) struct counter_dw_timer_drv_data *const data = DEV_DATA(timer_dev); if (!device_is_ready(timer_config->clk_dev)) { LOG_ERR("clock controller device not ready"); return -ENODEV; } ret = clock_control_get_rate(timer_config->clk_dev, timer_config->clkid, &data->freq); if (ret != 0) { LOG_ERR("Unable to get clock rate: err:%d", ret); return ret; } #endif /* Reset timer only if reset controller driver is supported */ #if DT_ANY_INST_HAS_PROP_STATUS_OKAY(resets) if (timer_config->reset.dev != NULL) { if (!device_is_ready(timer_config->reset.dev)) { LOG_ERR("Reset controller device not ready"); return -ENODEV; } ret = reset_line_toggle(timer_config->reset.dev, timer_config->reset.id); if (ret != 0) { LOG_ERR("Timer reset failed"); return ret; } } #endif timer_config->irq_config(); return 0; } #define DW_SNPS_TIMER_CLOCK_RATE_INIT(inst) \ COND_CODE_1(DT_INST_NODE_HAS_PROP(inst, clock_frequency), \ ( \ .freq = DT_INST_PROP(inst, clock_frequency), \ ), \ ( \ .freq = 0, \ .clk_dev = DEVICE_DT_GET(DT_INST_CLOCKS_CTLR(inst)), \ .clkid = (clock_control_subsys_t)DT_INST_CLOCKS_CELL(inst, clkid), \ ) \ ) #define DW_SNPS_TIMER_SNPS_RESET_SPEC_INIT(inst) \ .reset = RESET_DT_SPEC_INST_GET(inst), \ #define CREATE_DW_TIMER_DEV(inst) \ static void counter_dw_timer_irq_config_##inst(void); \ static struct counter_dw_timer_drv_data timer_data_##inst; \ static const struct counter_dw_timer_config timer_config_##inst = { \ DEVICE_MMIO_NAMED_ROM_INIT(timer_mmio, DT_DRV_INST(inst)), \ DW_SNPS_TIMER_CLOCK_RATE_INIT(inst) \ .info = { \ .max_top_value = UINT32_MAX, \ .channels = 1, \ }, \ IF_ENABLED(DT_INST_NODE_HAS_PROP(inst, resets), \ (DW_SNPS_TIMER_SNPS_RESET_SPEC_INIT(inst))) \ .irq_config = counter_dw_timer_irq_config_##inst, \ }; \ DEVICE_DT_INST_DEFINE(inst, \ counter_dw_timer_init, \ NULL, &timer_data_##inst, \ &timer_config_##inst, POST_KERNEL, \ CONFIG_COUNTER_INIT_PRIORITY, \ &dw_timer_driver_api); \ static void counter_dw_timer_irq_config_##inst(void) \ { \ IRQ_CONNECT(DT_INST_IRQN(inst), \ DT_INST_IRQ(inst, priority), \ counter_dw_timer_irq_handler, \ DEVICE_DT_INST_GET(inst), 0); \ irq_enable(DT_INST_IRQN(inst)); \ } DT_INST_FOREACH_STATUS_OKAY(CREATE_DW_TIMER_DEV); ```
/content/code_sandbox/drivers/counter/counter_dw_timer.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,020
```unknown # GD32 counter timer configuration options config COUNTER_TIMER_GD32 bool "GD32 timer counter driver" default y depends on DT_HAS_GD_GD32_TIMER_ENABLED && !SOC_SERIES_GD32VF103 select USE_GD32_TIMER help Enable counter timer driver for GD32 series devices. ```
/content/code_sandbox/drivers/counter/Kconfig.gd32
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
71
```unknown # MCUXpresso SDK RTC config COUNTER_MCUX_GPT bool "MCUX GPT driver" default y depends on DT_HAS_NXP_IMX_GPT_ENABLED select KERNEL_DIRECT_MAP if MMU help Enable support for mcux General Purpose Timer (GPT) driver. ```
/content/code_sandbox/drivers/counter/Kconfig.mcux_gpt
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
65
```unknown # Counter and timer configuration options config TIMER_TMR_CMSDK_APB bool "ARM CMSDK (Cortex-M System Design Kit) Timer driver" default y depends on DT_HAS_ARM_CMSDK_TIMER_ENABLED help The timers (TMR) present in the platform are used as timers. This option enables the support for the timers. ```
/content/code_sandbox/drivers/counter/Kconfig.tmr_cmsdk_apb
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
76
```c /* * */ #define DT_DRV_COMPAT nxp_s32_sys_timer #include <zephyr/kernel.h> #include <zephyr/drivers/counter.h> #include <zephyr/drivers/clock_control.h> #if defined(CONFIG_GIC) #include <zephyr/drivers/interrupt_controller/gic.h> #endif /* CONFIG_GIC */ #include <zephyr/logging/log.h> #include <zephyr/irq.h> LOG_MODULE_REGISTER(nxp_s32_sys_timer, CONFIG_COUNTER_LOG_LEVEL); /* System Timer Module (STM) register definitions */ /* Control */ #define STM_CR 0x0 #define STM_CR_TEN_MASK BIT(0) #define STM_CR_TEN(v) FIELD_PREP(STM_CR_TEN_MASK, (v)) #define STM_CR_FRZ_MASK BIT(1) #define STM_CR_FRZ(v) FIELD_PREP(STM_CR_FRZ_MASK, (v)) #define STM_CR_CPS_MASK GENMASK(15, 8) #define STM_CR_CPS(v) FIELD_PREP(STM_CR_CPS_MASK, (v)) /* Count */ #define STM_CNT 0x4 #define STM_CNT_CNT_MASK GENMASK(31, 0) #define STM_CNT_CNT(v) FIELD_PREP(STM_CNT_CNT_MASK, (v)) /* Channel Control */ #define STM_CCR(n) (0x10 + 0x10 * (n)) #define STM_CCR_CEN_MASK BIT(0) #define STM_CCR_CEN(v) FIELD_PREP(STM_CCR_CEN_MASK, (v)) /* Channel Interrupt */ #define STM_CIR(n) (0x14 + 0x10 * (n)) #define STM_CIR_CIF_MASK BIT(0) #define STM_CIR_CIF(v) FIELD_PREP(STM_CIR_CIF_MASK, (v)) /* Channel Compare */ #define STM_CMP(n) (0x18 + 0x10 * (n)) #define STM_CMP_CMP_MASK GENMASK(31, 0) #define STM_CMP_CMP(v) FIELD_PREP(STM_CMP_CMP_MASK, (v)) /* Handy accessors */ #define REG_READ(r) sys_read32(config->base + (r)) #define REG_WRITE(r, v) sys_write32((v), config->base + (r)) #define SYS_TIMER_MAX_VALUE 0xFFFFFFFFU #define SYS_TIMER_NUM_CHANNELS 4 struct nxp_s32_sys_timer_chan_data { counter_alarm_callback_t callback; void *user_data; }; struct nxp_s32_sys_timer_data { struct nxp_s32_sys_timer_chan_data ch_data[SYS_TIMER_NUM_CHANNELS]; uint32_t guard_period; atomic_t irq_pending; }; struct nxp_s32_sys_timer_config { struct counter_config_info info; mem_addr_t base; const struct device *clock_dev; clock_control_subsys_t clock_subsys; uint8_t prescaler; bool freeze; unsigned int irqn; }; static ALWAYS_INLINE void irq_set_pending(unsigned int irq) { #if defined(CONFIG_GIC) arm_gic_irq_set_pending(irq); #else NVIC_SetPendingIRQ(irq); #endif /* CONFIG_GIC */ } static uint32_t ticks_add(uint32_t val1, uint32_t val2, uint32_t top) { uint32_t to_top; if (likely(IS_BIT_MASK(top))) { return (val1 + val2) & top; } /* top is not 2^n-1 */ to_top = top - val1; return (val2 <= to_top) ? val1 + val2 : val2 - to_top; } static uint32_t ticks_sub(uint32_t val, uint32_t old, uint32_t top) { if (likely(IS_BIT_MASK(top))) { return (val - old) & top; } /* top is not 2^n-1 */ return (val >= old) ? (val - old) : val + top + 1 - old; } static ALWAYS_INLINE void stm_disable_channel(const struct nxp_s32_sys_timer_config *config, uint8_t channel) { REG_WRITE(STM_CCR(channel), STM_CCR_CEN(0U)); REG_WRITE(STM_CIR(channel), STM_CIR_CIF(1U)); } static int stm_set_alarm(const struct device *dev, uint8_t channel, uint32_t ticks, uint32_t flags) { const struct nxp_s32_sys_timer_config *config = dev->config; struct nxp_s32_sys_timer_data *data = dev->data; struct nxp_s32_sys_timer_chan_data *ch_data = &data->ch_data[channel]; const uint32_t now = REG_READ(STM_CNT); const uint32_t top_val = config->info.max_top_value; int err = 0; uint32_t diff; uint32_t max_rel_val; bool irq_on_late; if (flags & COUNTER_ALARM_CFG_ABSOLUTE) { __ASSERT_NO_MSG(data->guard_period < top_val); max_rel_val = top_val - data->guard_period; irq_on_late = !!(flags & COUNTER_ALARM_CFG_EXPIRE_WHEN_LATE); } else { /* * If relative value is smaller than half of the counter range it is assumed * that there is a risk of setting value too late and late detection algorithm * must be applied. When late setting is detected, interrupt shall be * triggered for immediate expiration of the timer. Detection is performed * by limiting relative distance between CMP and CNT. * * Note that half of counter range is an arbitrary value. */ irq_on_late = ticks < (top_val / 2); /* Limit max to detect short relative being set too late */ max_rel_val = irq_on_late ? top_val / 2 : top_val; ticks = ticks_add(now, ticks, top_val); } /* Disable the channel before loading the new value so that it takes effect immediately */ stm_disable_channel(config, channel); REG_WRITE(STM_CMP(channel), ticks); REG_WRITE(STM_CCR(channel), STM_CCR_CEN(1U)); /* * Decrement value to detect also case when ticks == CNT. Otherwise, condition would need * to include comparing diff against 0. */ diff = ticks_sub(ticks - 1, REG_READ(STM_CNT), top_val); if (diff > max_rel_val) { if (flags & COUNTER_ALARM_CFG_ABSOLUTE) { err = -ETIME; } /* * Interrupt is triggered always for relative alarm and for absolute depending * on the flag */ if (irq_on_late) { atomic_or(&data->irq_pending, BIT(channel)); irq_set_pending(config->irqn); } else { ch_data->callback = NULL; } } return err; } static void stm_isr(const struct device *dev) { const struct nxp_s32_sys_timer_config *config = dev->config; struct nxp_s32_sys_timer_data *data = dev->data; struct nxp_s32_sys_timer_chan_data *ch_data = NULL; counter_alarm_callback_t cb = NULL; void *cb_args = NULL; uint8_t channel; bool pending; for (channel = 0; channel < SYS_TIMER_NUM_CHANNELS; ++channel) { pending = FIELD_GET(STM_CCR_CEN_MASK, REG_READ(STM_CCR(channel))) && FIELD_GET(STM_CIR_CIF_MASK, REG_READ(STM_CIR(channel))); if (pending || atomic_test_bit(&data->irq_pending, channel)) { stm_disable_channel(config, channel); atomic_and(&data->irq_pending, ~BIT(channel)); ch_data = &data->ch_data[channel]; if (ch_data->callback) { cb = ch_data->callback; cb_args = ch_data->user_data; ch_data->callback = NULL; ch_data->user_data = NULL; cb(dev, channel, REG_READ(STM_CNT), cb_args); } } } } static int nxp_s32_sys_timer_start(const struct device *dev) { const struct nxp_s32_sys_timer_config *config = dev->config; REG_WRITE(STM_CNT, 0U); REG_WRITE(STM_CR, REG_READ(STM_CR) | STM_CR_TEN(1U)); return 0; } static int nxp_s32_sys_timer_stop(const struct device *dev) { const struct nxp_s32_sys_timer_config *config = dev->config; REG_WRITE(STM_CR, REG_READ(STM_CR) & ~STM_CR_TEN_MASK); return 0; } static int nxp_s32_sys_timer_get_value(const struct device *dev, uint32_t *ticks) { const struct nxp_s32_sys_timer_config *config = dev->config; *ticks = REG_READ(STM_CNT); return 0; } static int nxp_s32_sys_timer_set_alarm(const struct device *dev, uint8_t channel, const struct counter_alarm_cfg *alarm_cfg) { const struct nxp_s32_sys_timer_config *config = dev->config; struct nxp_s32_sys_timer_data *data = dev->data; struct nxp_s32_sys_timer_chan_data *ch_data = &data->ch_data[channel]; if (ch_data->callback) { return -EBUSY; } if (alarm_cfg->ticks > config->info.max_top_value) { LOG_ERR("Invalid ticks value %d", alarm_cfg->ticks); return -EINVAL; } ch_data->callback = alarm_cfg->callback; ch_data->user_data = alarm_cfg->user_data; return stm_set_alarm(dev, channel, alarm_cfg->ticks, alarm_cfg->flags); } static int nxp_s32_sys_timer_cancel_alarm(const struct device *dev, uint8_t channel) { const struct nxp_s32_sys_timer_config *config = dev->config; struct nxp_s32_sys_timer_data *data = dev->data; struct nxp_s32_sys_timer_chan_data *ch_data = &data->ch_data[channel]; stm_disable_channel(config, channel); ch_data->callback = NULL; ch_data->user_data = NULL; return 0; } static uint32_t nxp_s32_sys_timer_get_pending_int(const struct device *dev) { const struct nxp_s32_sys_timer_config *config = dev->config; uint8_t i; for (i = 0; i < counter_get_num_of_channels(dev); i++) { if (REG_READ(STM_CIR(i)) & STM_CIR_CIF_MASK) { return 1; } } return 0; } static int nxp_s32_sys_timer_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { ARG_UNUSED(dev); ARG_UNUSED(cfg); /* Overflow is fixed and cannot be changed */ return -ENOTSUP; } static uint32_t nxp_s32_sys_timer_get_top_value(const struct device *dev) { const struct nxp_s32_sys_timer_config *config = dev->config; return config->info.max_top_value; } static int nxp_s32_sys_timer_set_guard_period(const struct device *dev, uint32_t guard, uint32_t flags) { struct nxp_s32_sys_timer_data *data = dev->data; ARG_UNUSED(flags); __ASSERT_NO_MSG(guard < nxp_s32_sys_timer_get_top_value(dev)); data->guard_period = guard; return 0; } static uint32_t nxp_s32_sys_timer_get_guard_period(const struct device *dev, uint32_t flags) { struct nxp_s32_sys_timer_data *data = dev->data; ARG_UNUSED(flags); return data->guard_period; } static uint32_t nxp_s32_sys_timer_get_frequency(const struct device *dev) { const struct nxp_s32_sys_timer_config *config = dev->config; uint32_t clock_rate; if (clock_control_get_rate(config->clock_dev, config->clock_subsys, &clock_rate)) { LOG_ERR("Failed to get clock frequency"); return 0; } return clock_rate / (config->prescaler + 1U); } static int nxp_s32_sys_timer_init(const struct device *dev) { const struct nxp_s32_sys_timer_config *config = dev->config; struct nxp_s32_sys_timer_data *data = dev->data; struct nxp_s32_sys_timer_chan_data *ch_data; int i; int err; if (!device_is_ready(config->clock_dev)) { LOG_ERR("Clock control device not ready"); return -ENODEV; } err = clock_control_on(config->clock_dev, config->clock_subsys); if (err) { LOG_ERR("Failed to enable clock"); return err; } REG_WRITE(STM_CNT, 0U); REG_WRITE(STM_CR, STM_CR_FRZ(config->freeze) | STM_CR_CPS(config->prescaler) | STM_CR_TEN(1U)); for (i = 0; i < counter_get_num_of_channels(dev); i++) { ch_data = &data->ch_data[i]; ch_data->callback = NULL; ch_data->user_data = NULL; REG_WRITE(STM_CCR(i), STM_CCR_CEN(0U)); REG_WRITE(STM_CIR(i), STM_CIR_CIF(1U)); REG_WRITE(STM_CMP(i), 0U); } return 0; } static const struct counter_driver_api nxp_s32_sys_timer_driver_api = { .start = nxp_s32_sys_timer_start, .stop = nxp_s32_sys_timer_stop, .get_value = nxp_s32_sys_timer_get_value, .set_alarm = nxp_s32_sys_timer_set_alarm, .cancel_alarm = nxp_s32_sys_timer_cancel_alarm, .set_top_value = nxp_s32_sys_timer_set_top_value, .get_top_value = nxp_s32_sys_timer_get_top_value, .set_guard_period = nxp_s32_sys_timer_set_guard_period, .get_guard_period = nxp_s32_sys_timer_get_guard_period, .get_pending_int = nxp_s32_sys_timer_get_pending_int, .get_freq = nxp_s32_sys_timer_get_frequency }; #define SYS_TIMER_INIT_DEVICE(n) \ static int nxp_s32_sys_timer_##n##_init(const struct device *dev) \ { \ IRQ_CONNECT(DT_INST_IRQN(n), DT_INST_IRQ(n, priority), \ stm_isr, DEVICE_DT_INST_GET(n), \ COND_CODE_1(DT_INST_IRQ_HAS_CELL(n, flags), \ (DT_INST_IRQ(n, flags)), (0))); \ irq_enable(DT_INST_IRQN(n)); \ \ return nxp_s32_sys_timer_init(dev); \ } \ \ static struct nxp_s32_sys_timer_data nxp_s32_sys_timer_data_##n; \ \ static const struct nxp_s32_sys_timer_config nxp_s32_sys_timer_config_##n = { \ .info = { \ .max_top_value = SYS_TIMER_MAX_VALUE, \ .channels = SYS_TIMER_NUM_CHANNELS, \ .flags = COUNTER_CONFIG_INFO_COUNT_UP, \ }, \ .base = DT_INST_REG_ADDR(n), \ .freeze = DT_INST_PROP(n, freeze), \ .prescaler = DT_INST_PROP(n, prescaler) - 1, \ .clock_dev = DEVICE_DT_GET(DT_INST_CLOCKS_CTLR(n)), \ .clock_subsys = (clock_control_subsys_t)DT_INST_CLOCKS_CELL(n, name), \ .irqn = DT_INST_IRQN(n), \ }; \ \ DEVICE_DT_INST_DEFINE(n, \ nxp_s32_sys_timer_##n##_init, \ NULL, \ &nxp_s32_sys_timer_data_##n, \ &nxp_s32_sys_timer_config_##n, \ POST_KERNEL, \ CONFIG_COUNTER_INIT_PRIORITY, \ &nxp_s32_sys_timer_driver_api); DT_INST_FOREACH_STATUS_OKAY(SYS_TIMER_INIT_DEVICE) ```
/content/code_sandbox/drivers/counter/counter_nxp_s32_sys_timer.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,497
```c /* * */ #include <zephyr/drivers/counter.h> #include <hal/nrf_timer.h> #include <zephyr/sys/atomic.h> #define LOG_LEVEL CONFIG_COUNTER_LOG_LEVEL #define LOG_MODULE_NAME counter_timer #include <zephyr/logging/log.h> #include <zephyr/irq.h> LOG_MODULE_REGISTER(LOG_MODULE_NAME, LOG_LEVEL); #define DT_DRV_COMPAT nordic_nrf_timer #define CC_TO_ID(cc_num) (cc_num - 2) #define ID_TO_CC(idx) (nrf_timer_cc_channel_t)(idx + 2) #define TOP_CH NRF_TIMER_CC_CHANNEL0 #define COUNTER_TOP_EVT NRF_TIMER_EVENT_COMPARE0 #define COUNTER_TOP_INT_MASK NRF_TIMER_INT_COMPARE0_MASK #define COUNTER_OVERFLOW_SHORT NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK #define COUNTER_READ_CC NRF_TIMER_CC_CHANNEL1 #if defined(CONFIG_SOC_SERIES_BSIM_NRFXX) #define MAYBE_CONST_CONFIG #else #define MAYBE_CONST_CONFIG const #endif struct counter_nrfx_data { counter_top_callback_t top_cb; void *top_user_data; uint32_t guard_period; atomic_t cc_int_pending; }; struct counter_nrfx_ch_data { counter_alarm_callback_t callback; void *user_data; }; struct counter_nrfx_config { struct counter_config_info info; struct counter_nrfx_ch_data *ch_data; NRF_TIMER_Type *timer; LOG_INSTANCE_PTR_DECLARE(log); }; struct counter_timer_config { nrf_timer_bit_width_t bit_width; nrf_timer_mode_t mode; uint32_t prescaler; }; static int start(const struct device *dev) { const struct counter_nrfx_config *config = dev->config; nrf_timer_task_trigger(config->timer, NRF_TIMER_TASK_START); return 0; } static int stop(const struct device *dev) { const struct counter_nrfx_config *config = dev->config; nrf_timer_task_trigger(config->timer, NRF_TIMER_TASK_SHUTDOWN); return 0; } static uint32_t get_top_value(const struct device *dev) { const struct counter_nrfx_config *config = dev->config; return nrf_timer_cc_get(config->timer, TOP_CH); } static uint32_t read(const struct device *dev) { const struct counter_nrfx_config *config = dev->config; NRF_TIMER_Type *timer = config->timer; nrf_timer_task_trigger(timer, nrf_timer_capture_task_get(COUNTER_READ_CC)); return nrf_timer_cc_get(timer, COUNTER_READ_CC); } static int get_value(const struct device *dev, uint32_t *ticks) { *ticks = read(dev); return 0; } static uint32_t ticks_add(uint32_t val1, uint32_t val2, uint32_t top) { uint32_t to_top; if (likely(IS_BIT_MASK(top))) { return (val1 + val2) & top; } to_top = top - val1; return (val2 <= to_top) ? val1 + val2 : val2 - to_top; } static uint32_t ticks_sub(uint32_t val, uint32_t old, uint32_t top) { if (likely(IS_BIT_MASK(top))) { return (val - old) & top; } /* if top is not 2^n-1 */ return (val >= old) ? (val - old) : val + top + 1 - old; } static void set_cc_int_pending(const struct device *dev, uint8_t chan) { const struct counter_nrfx_config *config = dev->config; struct counter_nrfx_data *data = dev->data; atomic_or(&data->cc_int_pending, BIT(chan)); NRFX_IRQ_PENDING_SET(NRFX_IRQ_NUMBER_GET(config->timer)); } static int set_cc(const struct device *dev, uint8_t id, uint32_t val, uint32_t flags) { const struct counter_nrfx_config *config = dev->config; struct counter_nrfx_data *data = dev->data; __ASSERT_NO_MSG(data->guard_period < get_top_value(dev)); bool absolute = flags & COUNTER_ALARM_CFG_ABSOLUTE; bool irq_on_late; NRF_TIMER_Type *reg = config->timer; uint8_t chan = ID_TO_CC(id); nrf_timer_event_t evt = nrf_timer_compare_event_get(chan); uint32_t top = get_top_value(dev); int err = 0; uint32_t prev_val; uint32_t now; uint32_t diff; uint32_t max_rel_val; __ASSERT(nrf_timer_int_enable_check(reg, nrf_timer_compare_int_get(chan)) == 0, "Expected that CC interrupt is disabled."); /* First take care of a risk of an event coming from CC being set to * next tick. Reconfigure CC to future (now tick is the furthest * future). */ now = read(dev); prev_val = nrf_timer_cc_get(reg, chan); nrf_timer_cc_set(reg, chan, now); nrf_timer_event_clear(reg, evt); if (absolute) { max_rel_val = top - data->guard_period; irq_on_late = flags & COUNTER_ALARM_CFG_EXPIRE_WHEN_LATE; } else { /* If relative value is smaller than half of the counter range * it is assumed that there is a risk of setting value too late * and late detection algorithm must be applied. When late * setting is detected, interrupt shall be triggered for * immediate expiration of the timer. Detection is performed * by limiting relative distance between CC and counter. * * Note that half of counter range is an arbitrary value. */ irq_on_late = val < (top / 2); /* limit max to detect short relative being set too late. */ max_rel_val = irq_on_late ? top / 2 : top; val = ticks_add(now, val, top); } nrf_timer_cc_set(reg, chan, val); /* decrement value to detect also case when val == read(dev). Otherwise, * condition would need to include comparing diff against 0. */ diff = ticks_sub(val - 1, read(dev), top); if (diff > max_rel_val) { if (absolute) { err = -ETIME; } /* Interrupt is triggered always for relative alarm and * for absolute depending on the flag. */ if (irq_on_late) { set_cc_int_pending(dev, chan); } else { config->ch_data[id].callback = NULL; } } else { nrf_timer_int_enable(reg, nrf_timer_compare_int_get(chan)); } return err; } static int set_alarm(const struct device *dev, uint8_t chan, const struct counter_alarm_cfg *alarm_cfg) { const struct counter_nrfx_config *nrfx_config = dev->config; struct counter_nrfx_ch_data *chdata = &nrfx_config->ch_data[chan]; if (alarm_cfg->ticks > get_top_value(dev)) { return -EINVAL; } if (chdata->callback) { return -EBUSY; } chdata->callback = alarm_cfg->callback; chdata->user_data = alarm_cfg->user_data; return set_cc(dev, chan, alarm_cfg->ticks, alarm_cfg->flags); } static int cancel_alarm(const struct device *dev, uint8_t chan_id) { const struct counter_nrfx_config *config = dev->config; uint32_t int_mask = nrf_timer_compare_int_get(ID_TO_CC(chan_id)); nrf_timer_int_disable(config->timer, int_mask); config->ch_data[chan_id].callback = NULL; return 0; } static int set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { const struct counter_nrfx_config *nrfx_config = dev->config; NRF_TIMER_Type *timer = nrfx_config->timer; struct counter_nrfx_data *data = dev->data; int err = 0; for (int i = 0; i < counter_get_num_of_channels(dev); i++) { /* Overflow can be changed only when all alarms are * disables. */ if (nrfx_config->ch_data[i].callback) { return -EBUSY; } } nrf_timer_int_disable(timer, COUNTER_TOP_INT_MASK); nrf_timer_cc_set(timer, TOP_CH, cfg->ticks); nrf_timer_event_clear(timer, COUNTER_TOP_EVT); nrf_timer_shorts_enable(timer, COUNTER_OVERFLOW_SHORT); data->top_cb = cfg->callback; data->top_user_data = cfg->user_data; if (!(cfg->flags & COUNTER_TOP_CFG_DONT_RESET)) { nrf_timer_task_trigger(timer, NRF_TIMER_TASK_CLEAR); } else if (read(dev) >= cfg->ticks) { err = -ETIME; if (cfg->flags & COUNTER_TOP_CFG_RESET_WHEN_LATE) { nrf_timer_task_trigger(timer, NRF_TIMER_TASK_CLEAR); } } if (cfg->callback) { nrf_timer_int_enable(timer, COUNTER_TOP_INT_MASK); } return err; } static uint32_t get_pending_int(const struct device *dev) { return 0; } static int init_timer(const struct device *dev, const struct counter_timer_config *config) { MAYBE_CONST_CONFIG struct counter_nrfx_config *nrfx_config = (MAYBE_CONST_CONFIG struct counter_nrfx_config *)dev->config; #if defined(CONFIG_SOC_SERIES_BSIM_NRFXX) /* For simulated devices we need to convert the hardcoded DT address from the real * peripheral into the correct one for simulation */ nrfx_config->timer = nhw_convert_periph_base_addr(nrfx_config->timer); #endif NRF_TIMER_Type *reg = nrfx_config->timer; nrf_timer_bit_width_set(reg, config->bit_width); nrf_timer_mode_set(reg, config->mode); nrf_timer_prescaler_set(reg, config->prescaler); nrf_timer_cc_set(reg, TOP_CH, counter_get_max_top_value(dev)); NRFX_IRQ_ENABLE(NRFX_IRQ_NUMBER_GET(reg)); return 0; } static uint32_t get_guard_period(const struct device *dev, uint32_t flags) { struct counter_nrfx_data *data = dev->data; return data->guard_period; } static int set_guard_period(const struct device *dev, uint32_t guard, uint32_t flags) { struct counter_nrfx_data *data = dev->data; __ASSERT_NO_MSG(guard < get_top_value(dev)); data->guard_period = guard; return 0; } static void top_irq_handle(const struct device *dev) { const struct counter_nrfx_config *config = dev->config; struct counter_nrfx_data *data = dev->data; NRF_TIMER_Type *reg = config->timer; counter_top_callback_t cb = data->top_cb; if (nrf_timer_event_check(reg, COUNTER_TOP_EVT) && nrf_timer_int_enable_check(reg, COUNTER_TOP_INT_MASK)) { nrf_timer_event_clear(reg, COUNTER_TOP_EVT); __ASSERT(cb != NULL, "top event enabled - expecting callback"); cb(dev, data->top_user_data); } } static void alarm_irq_handle(const struct device *dev, uint32_t id) { const struct counter_nrfx_config *config = dev->config; struct counter_nrfx_data *data = dev->data; uint32_t cc = ID_TO_CC(id); NRF_TIMER_Type *reg = config->timer; uint32_t int_mask = nrf_timer_compare_int_get(cc); nrf_timer_event_t evt = nrf_timer_compare_event_get(cc); bool hw_irq_pending = nrf_timer_event_check(reg, evt) && nrf_timer_int_enable_check(reg, int_mask); bool sw_irq_pending = data->cc_int_pending & BIT(cc); if (hw_irq_pending || sw_irq_pending) { struct counter_nrfx_ch_data *chdata; counter_alarm_callback_t cb; nrf_timer_event_clear(reg, evt); atomic_and(&data->cc_int_pending, ~BIT(cc)); nrf_timer_int_disable(reg, int_mask); chdata = &config->ch_data[id]; cb = chdata->callback; chdata->callback = NULL; if (cb) { uint32_t cc_val = nrf_timer_cc_get(reg, cc); cb(dev, id, cc_val, chdata->user_data); } } } static void irq_handler(const void *arg) { const struct device *dev = arg; top_irq_handle(dev); for (uint32_t i = 0; i < counter_get_num_of_channels(dev); i++) { alarm_irq_handle(dev, i); } } static const struct counter_driver_api counter_nrfx_driver_api = { .start = start, .stop = stop, .get_value = get_value, .set_alarm = set_alarm, .cancel_alarm = cancel_alarm, .set_top_value = set_top_value, .get_pending_int = get_pending_int, .get_top_value = get_top_value, .get_guard_period = get_guard_period, .set_guard_period = set_guard_period, }; /* * Device instantiation is done with node labels due to HAL API * requirements. In particular, TIMERx_MAX_SIZE values from HALs * are indexed by peripheral number, so DT_INST APIs won't work. */ #define TIMER_IRQ_CONNECT(idx) \ COND_CODE_1(DT_INST_PROP(idx, zli), \ (IRQ_DIRECT_CONNECT(DT_INST_IRQN(idx), \ DT_INST_IRQ(idx, priority), \ counter_timer##idx##_isr_wrapper, \ IRQ_ZERO_LATENCY)), \ (IRQ_CONNECT(DT_INST_IRQN(idx), DT_INST_IRQ(idx, priority), \ irq_handler, DEVICE_DT_INST_GET(idx), 0)) \ ) #if !defined(CONFIG_SOC_SERIES_BSIM_NRFXX) #define CHECK_MAX_FREQ(idx) \ BUILD_ASSERT(DT_INST_PROP(idx, max_frequency) == \ NRF_TIMER_BASE_FREQUENCY_GET((NRF_TIMER_Type *)DT_INST_REG_ADDR(idx))) #else #define CHECK_MAX_FREQ(idx) #endif #define COUNTER_NRFX_TIMER_DEVICE(idx) \ BUILD_ASSERT(DT_INST_PROP(idx, prescaler) <= \ TIMER_PRESCALER_PRESCALER_Msk, \ "TIMER prescaler out of range"); \ COND_CODE_1(DT_INST_PROP(idx, zli), ( \ ISR_DIRECT_DECLARE(counter_timer##idx##_isr_wrapper) \ { \ irq_handler(DEVICE_DT_INST_GET(idx)); \ /* No rescheduling, it shall not access zephyr primitives. */ \ return 0; \ }), ()) \ static int counter_##idx##_init(const struct device *dev) \ { \ TIMER_IRQ_CONNECT(idx); \ static const struct counter_timer_config config = { \ .prescaler = DT_INST_PROP(idx, prescaler), \ .mode = NRF_TIMER_MODE_TIMER, \ .bit_width = (DT_INST_PROP(idx, max_bit_width) == 32) ? \ NRF_TIMER_BIT_WIDTH_32 : NRF_TIMER_BIT_WIDTH_16, \ }; \ return init_timer(dev, &config); \ } \ static struct counter_nrfx_data counter_##idx##_data; \ static struct counter_nrfx_ch_data \ counter##idx##_ch_data[CC_TO_ID(DT_INST_PROP(idx, cc_num))]; \ LOG_INSTANCE_REGISTER(LOG_MODULE_NAME, idx, CONFIG_COUNTER_LOG_LEVEL); \ static MAYBE_CONST_CONFIG struct counter_nrfx_config nrfx_counter_##idx##_config = { \ .info = { \ .max_top_value = (uint32_t)BIT64_MASK(DT_INST_PROP(idx, max_bit_width)),\ .freq = DT_INST_PROP(idx, max_frequency) / \ BIT(DT_INST_PROP(idx, prescaler)), \ .flags = COUNTER_CONFIG_INFO_COUNT_UP, \ .channels = CC_TO_ID(DT_INST_PROP(idx, cc_num)), \ }, \ .ch_data = counter##idx##_ch_data, \ .timer = (NRF_TIMER_Type *)DT_INST_REG_ADDR(idx), \ LOG_INSTANCE_PTR_INIT(log, LOG_MODULE_NAME, idx) \ }; \ CHECK_MAX_FREQ(idx); \ DEVICE_DT_INST_DEFINE(idx, \ counter_##idx##_init, \ NULL, \ &counter_##idx##_data, \ &nrfx_counter_##idx##_config.info, \ PRE_KERNEL_1, CONFIG_COUNTER_INIT_PRIORITY, \ &counter_nrfx_driver_api); DT_INST_FOREACH_STATUS_OKAY(COUNTER_NRFX_TIMER_DEVICE) ```
/content/code_sandbox/drivers/counter/counter_nrfx_timer.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,694
```unknown # XEC counter configuration options config COUNTER_XEC bool "Microchip XEC series counter driver" default y depends on DT_HAS_MICROCHIP_XEC_TIMER_ENABLED help Enable counter driver for Microchip XEC MCU series. Such driver will expose the basic timer devices present on the MCU. ```
/content/code_sandbox/drivers/counter/Kconfig.xec
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
69
```c /* * */ #define DT_DRV_COMPAT zephyr_native_posix_counter #include <string.h> #include <zephyr/device.h> #include <zephyr/drivers/counter.h> #include <zephyr/irq.h> #include <soc.h> #include <hw_counter.h> #include <limits.h> #define DRIVER_CONFIG_INFO_FLAGS (COUNTER_CONFIG_INFO_COUNT_UP) #define DRIVER_CONFIG_INFO_CHANNELS CONFIG_COUNTER_NATIVE_POSIX_NBR_CHANNELS #define COUNTER_NATIVE_POSIX_IRQ_FLAGS (0) #define COUNTER_NATIVE_POSIX_IRQ_PRIORITY (2) #define COUNTER_PERIOD (USEC_PER_SEC / CONFIG_COUNTER_NATIVE_POSIX_FREQUENCY) #define TOP_VALUE (UINT_MAX) static struct counter_alarm_cfg pending_alarm[DRIVER_CONFIG_INFO_CHANNELS]; static bool is_alarm_pending[DRIVER_CONFIG_INFO_CHANNELS]; static struct counter_top_cfg top; static bool is_top_set; static const struct device *device; static void schedule_next_isr(void) { int64_t current_value = hw_counter_get_value(); uint32_t next_time = top.ticks; /* top.ticks is TOP_VALUE if is_top_set == false */ if (current_value == top.ticks) { current_value = -1; } for (int i = 0; i < DRIVER_CONFIG_INFO_CHANNELS; i++) { if (is_alarm_pending[i]) { if (pending_alarm[i].ticks > current_value) { /* If the alarm is not after a wrap */ next_time = MIN(pending_alarm[i].ticks, next_time); } } } /* We will at least get an interrupt at top.ticks even if is_top_set == false, * which is fine. We may use that to set the next alarm if needed */ hw_counter_set_target(next_time); } static void counter_isr(const void *arg) { ARG_UNUSED(arg); uint32_t current_value = hw_counter_get_value(); for (int i = 0; i < DRIVER_CONFIG_INFO_CHANNELS; i++) { if (is_alarm_pending[i] && (current_value == pending_alarm[i].ticks)) { is_alarm_pending[i] = false; if (pending_alarm[i].callback) { pending_alarm[i].callback(device, i, current_value, pending_alarm[i].user_data); } } } if (is_top_set && (current_value == top.ticks)) { if (top.callback) { top.callback(device, top.user_data); } } schedule_next_isr(); } static int ctr_init(const struct device *dev) { device = dev; memset(is_alarm_pending, 0, sizeof(is_alarm_pending)); is_top_set = false; top.ticks = TOP_VALUE; IRQ_CONNECT(COUNTER_EVENT_IRQ, COUNTER_NATIVE_POSIX_IRQ_PRIORITY, counter_isr, NULL, COUNTER_NATIVE_POSIX_IRQ_FLAGS); irq_enable(COUNTER_EVENT_IRQ); hw_counter_set_period(COUNTER_PERIOD); hw_counter_set_wrap_value((uint64_t)top.ticks + 1); hw_counter_reset(); return 0; } static int ctr_start(const struct device *dev) { ARG_UNUSED(dev); schedule_next_isr(); hw_counter_start(); return 0; } static int ctr_stop(const struct device *dev) { ARG_UNUSED(dev); hw_counter_stop(); return 0; } static int ctr_get_value(const struct device *dev, uint32_t *ticks) { ARG_UNUSED(dev); *ticks = hw_counter_get_value(); return 0; } static uint32_t ctr_get_pending_int(const struct device *dev) { ARG_UNUSED(dev); return 0; } static bool is_any_alarm_pending(void) { for (int i = 0; i < DRIVER_CONFIG_INFO_CHANNELS; i++) { if (is_alarm_pending[i]) { return true; } } return false; } static int ctr_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { ARG_UNUSED(dev); if (is_any_alarm_pending()) { posix_print_warning("Can't set top value while alarm is active\n"); return -EBUSY; } uint32_t current_value = hw_counter_get_value(); if (cfg->flags & COUNTER_TOP_CFG_DONT_RESET) { if (current_value >= cfg->ticks) { if (cfg->flags & COUNTER_TOP_CFG_RESET_WHEN_LATE) { hw_counter_reset(); } return -ETIME; } } else { hw_counter_reset(); } top = *cfg; hw_counter_set_wrap_value((uint64_t)top.ticks + 1); if ((cfg->ticks == TOP_VALUE) && !cfg->callback) { is_top_set = false; } else { is_top_set = true; } schedule_next_isr(); return 0; } static uint32_t ctr_get_top_value(const struct device *dev) { return top.ticks; } static int ctr_set_alarm(const struct device *dev, uint8_t chan_id, const struct counter_alarm_cfg *alarm_cfg) { ARG_UNUSED(dev); if (is_alarm_pending[chan_id]) { return -EBUSY; } uint32_t ticks = alarm_cfg->ticks; if (ticks > top.ticks) { posix_print_warning("Alarm ticks %u exceed top ticks %u\n", ticks, top.ticks); return -EINVAL; } if (!(alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE)) { uint32_t current_value = hw_counter_get_value(); ticks += current_value; if (ticks > top.ticks) { /* Handle wrap arounds */ ticks -= (top.ticks + 1); /* The count period is top.ticks + 1 */ } } pending_alarm[chan_id] = *alarm_cfg; pending_alarm[chan_id].ticks = ticks; is_alarm_pending[chan_id] = true; schedule_next_isr(); return 0; } static int ctr_cancel_alarm(const struct device *dev, uint8_t chan_id) { ARG_UNUSED(dev); if (!hw_counter_is_started()) { posix_print_warning("Counter not started\n"); return -ENOTSUP; } is_alarm_pending[chan_id] = false; schedule_next_isr(); return 0; } static const struct counter_driver_api ctr_api = { .start = ctr_start, .stop = ctr_stop, .get_value = ctr_get_value, .set_alarm = ctr_set_alarm, .cancel_alarm = ctr_cancel_alarm, .set_top_value = ctr_set_top_value, .get_pending_int = ctr_get_pending_int, .get_top_value = ctr_get_top_value, }; static const struct counter_config_info ctr_config = { .max_top_value = UINT_MAX, .freq = CONFIG_COUNTER_NATIVE_POSIX_FREQUENCY, .channels = DRIVER_CONFIG_INFO_CHANNELS, .flags = DRIVER_CONFIG_INFO_FLAGS }; DEVICE_DT_INST_DEFINE(0, ctr_init, NULL, NULL, &ctr_config, PRE_KERNEL_1, CONFIG_COUNTER_INIT_PRIORITY, &ctr_api); ```
/content/code_sandbox/drivers/counter/counter_native_posix.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,495
```unknown # Synopsys DesignWare Timer configuration option config COUNTER_SNPS_DW bool "Synopsys DesignWare Timer Driver" default y depends on DT_HAS_SNPS_DW_TIMERS_ENABLED help Enable Timer driver ```
/content/code_sandbox/drivers/counter/Kconfig.dw
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
52
```unknown config COUNTER_NRF_TIMER def_bool y depends on DT_HAS_NORDIC_NRF_TIMER_ENABLED config COUNTER_NRF_RTC def_bool y depends on DT_HAS_NORDIC_NRF_RTC_ENABLED # Internal flag which detects if PPI wrap feature is enabled for any instance config COUNTER_RTC_WITH_PPI_WRAP def_bool $(dt_nodelabel_bool_prop,rtc0,ppi-wrap) || \ $(dt_nodelabel_bool_prop,rtc1,ppi-wrap) || \ $(dt_nodelabel_bool_prop,rtc2,ppi-wrap) depends on COUNTER_NRF_RTC select NRFX_PPI if HAS_HW_NRF_PPI select NRFX_DPPI if HAS_HW_NRF_DPPIC # Internal flag which detects if fixed top feature is enabled for any instance config COUNTER_RTC_CUSTOM_TOP_SUPPORT def_bool !$(dt_nodelabel_bool_prop,rtc0,fixed-top) || \ !$(dt_nodelabel_bool_prop,rtc1,fixed-top) || \ !$(dt_nodelabel_bool_prop,rtc2,fixed-top) depends on COUNTER_NRF_RTC ```
/content/code_sandbox/drivers/counter/Kconfig.nrfx
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
249
```objective-c /* * */ #ifndef ZEPHYR_DRIVERS_COUNTER_TIMER_CMSDK_APB_H_ #define ZEPHYR_DRIVERS_COUNTER_TIMER_CMSDK_APB_H_ #include <zephyr/drivers/counter.h> #ifdef __cplusplus extern "C" { #endif struct timer_cmsdk_apb { /* Offset: 0x000 (R/W) control register */ volatile uint32_t ctrl; /* Offset: 0x004 (R/W) current value register */ volatile uint32_t value; /* Offset: 0x008 (R/W) reload value register */ volatile uint32_t reload; union { /* Offset: 0x00C (R/ ) interrupt status register */ volatile uint32_t intstatus; /* Offset: 0x00C ( /W) interruptclear register */ volatile uint32_t intclear; }; }; #define TIMER_CTRL_IRQ_EN (1 << 3) #define TIMER_CTRL_SEL_EXT_CLK (1 << 2) #define TIMER_CTRL_SEL_EXT_EN (1 << 1) #define TIMER_CTRL_EN (1 << 0) #define TIMER_CTRL_INT_CLEAR (1 << 0) #ifdef __cplusplus } #endif #endif /* ZEPHYR_DRIVERS_COUNTER_TIMER_CMSDK_APB_H_ */ ```
/content/code_sandbox/drivers/counter/timer_cmsdk_apb.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
270
```objective-c /* * */ #ifndef ZEPHYR_DRIVERS_COUNTER_DUALTIMER_CMSDK_APB_H_ #define ZEPHYR_DRIVERS_COUNTER_DUALTIMER_CMSDK_APB_H_ #include <zephyr/drivers/counter.h> #ifdef __cplusplus extern "C" { #endif struct dualtimer_cmsdk_apb { /* Offset: 0x000 (R/W) Timer 1 Load */ volatile uint32_t timer1load; /* Offset: 0x004 (R/ ) Timer 1 Counter Current Value */ volatile uint32_t timer1value; /* Offset: 0x008 (R/W) Timer 1 Control */ volatile uint32_t timer1ctrl; /* Offset: 0x00C ( /W) Timer 1 Interrupt Clear */ volatile uint32_t timer1intclr; /* Offset: 0x010 (R/ ) Timer 1 Raw Interrupt Status */ volatile uint32_t timer1ris; /* Offset: 0x014 (R/ ) Timer 1 Masked Interrupt Status */ volatile uint32_t timer1mis; /* Offset: 0x018 (R/W) Background Load Register */ volatile uint32_t timer1bgload; /* Reserved */ volatile uint32_t reserved0; /* Offset: 0x020 (R/W) Timer 2 Load */ volatile uint32_t timer2load; /* Offset: 0x024 (R/ ) Timer 2 Counter Current Value */ volatile uint32_t timer2value; /* Offset: 0x028 (R/W) Timer 2 Control */ volatile uint32_t timer2ctrl; /* Offset: 0x02C ( /W) Timer 2 Interrupt Clear */ volatile uint32_t timer2intclr; /* Offset: 0x030 (R/ ) Timer 2 Raw Interrupt Status */ volatile uint32_t timer2ris; /* Offset: 0x034 (R/ ) Timer 2 Masked Interrupt Status */ volatile uint32_t timer2mis; /* Offset: 0x038 (R/W) Background Load Register */ volatile uint32_t timer2bgload; /* Reserved */ volatile uint32_t reserved1[945]; /* Offset: 0xF00 (R/W) Integration Test Control Register */ volatile uint32_t itcr; /* Offset: 0xF04 ( /W) Integration Test Output Set Register */ volatile uint32_t itop; }; #define DUALTIMER_CTRL_EN (1 << 7) #define DUALTIMER_CTRL_MODE (1 << 6) #define DUALTIMER_CTRL_INTEN (1 << 5) #define DUALTIMER_CTRL_PRESCALE (3 << 2) #define DUALTIMER_CTRL_SIZE_32 (1 << 1) #define DUALTIMER_CTRL_ONESHOOT (1 << 0) #define DUALTIMER_INTCLR (1 << 0) #define DUALTIMER_RAWINTSTAT (1 << 0) #define DUALTIMER_MASKINTSTAT (1 << 0) #ifdef __cplusplus } #endif #endif /* ZEPHYR_DRIVERS_COUNTER_DUALTIMER_CMSDK_APB_H_ */ ```
/content/code_sandbox/drivers/counter/dualtimer_cmsdk_apb.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
664
```c /* * */ #define DT_DRV_COMPAT microchip_xec_timer /** * @file * @brief Microchip XEC Counter driver * * This is the driver for the 16/32-bit counters on the Microchip SoCs. * * Notes: * - The counters are running in down counting mode. * - Interrupts are triggered (if enabled) when the counter * reaches zero. * - These are not free running counters where there are separate * compare values for interrupts. When setting single shot alarms, * the counter values are changed so that interrupts are triggered * when the counters reach zero. */ #include <zephyr/irq.h> #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(counter_mchp_xec, CONFIG_COUNTER_LOG_LEVEL); #include <zephyr/drivers/counter.h> #include <soc.h> #include <errno.h> #include <stdbool.h> struct counter_xec_config { struct counter_config_info info; void (*config_func)(void); uint32_t base_address; uint16_t prescaler; uint8_t girq_id; uint8_t girq_bit; }; struct counter_xec_data { counter_alarm_callback_t alarm_cb; counter_top_callback_t top_cb; void *user_data; }; #define COUNTER_XEC_REG_BASE(_dev) \ ((struct btmr_regs *) \ ((const struct counter_xec_config * const) \ _dev->config)->base_address) #define COUNTER_XEC_CONFIG(_dev) \ (((const struct counter_xec_config * const) \ _dev->config)) #define COUNTER_XEC_DATA(_dev) \ ((struct counter_xec_data *)dev->data) static int counter_xec_start(const struct device *dev) { struct btmr_regs *counter = COUNTER_XEC_REG_BASE(dev); if (counter->CTRL & MCHP_BTMR_CTRL_ENABLE) { return -EALREADY; } counter->CTRL |= (MCHP_BTMR_CTRL_ENABLE | MCHP_BTMR_CTRL_START); LOG_DBG("%p Counter started", dev); return 0; } static int counter_xec_stop(const struct device *dev) { struct btmr_regs *counter = COUNTER_XEC_REG_BASE(dev); uint32_t reg; if (!(counter->CTRL & MCHP_BTMR_CTRL_ENABLE)) { /* Already stopped, nothing to do */ return 0; } reg = counter->CTRL; reg &= ~MCHP_BTMR_CTRL_ENABLE; reg &= ~MCHP_BTMR_CTRL_START; reg &= ~MCHP_BTMR_CTRL_HALT; reg &= ~MCHP_BTMR_CTRL_RELOAD; reg &= ~MCHP_BTMR_CTRL_AUTO_RESTART; counter->CTRL = reg; counter->IEN = MCHP_BTMR_INTDIS; counter->CNT = counter->PRLD; LOG_DBG("%p Counter stopped", dev); return 0; } static int counter_xec_get_value(const struct device *dev, uint32_t *ticks) { struct btmr_regs *counter = COUNTER_XEC_REG_BASE(dev); *ticks = counter->CNT; return 0; } static int counter_xec_set_alarm(const struct device *dev, uint8_t chan_id, const struct counter_alarm_cfg *alarm_cfg) { struct btmr_regs *counter = COUNTER_XEC_REG_BASE(dev); struct counter_xec_data *data = COUNTER_XEC_DATA(dev); if (chan_id != 0) { LOG_ERR("Invalid channel id %u", chan_id); return -ENOTSUP; } /* Interrupts are only triggered when the counter reaches 0. * So only relative alarms are supported. */ if (alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) { return -ENOTSUP; } if (data->alarm_cb != NULL) { return -EBUSY; } if (!alarm_cfg->callback) { return -EINVAL; } if (alarm_cfg->ticks > counter->PRLD) { return -EINVAL; } counter->CNT = alarm_cfg->ticks; data->alarm_cb = alarm_cfg->callback; data->user_data = alarm_cfg->user_data; counter->IEN = MCHP_BTMR_INTEN; LOG_DBG("%p Counter alarm set to %u ticks", dev, alarm_cfg->ticks); counter->CTRL |= MCHP_BTMR_CTRL_START; return 0; } static int counter_xec_cancel_alarm(const struct device *dev, uint8_t chan_id) { struct btmr_regs *counter = COUNTER_XEC_REG_BASE(dev); struct counter_xec_data *data = COUNTER_XEC_DATA(dev); if (chan_id != 0) { LOG_ERR("Invalid channel id %u", chan_id); return -ENOTSUP; } counter->CTRL &= ~MCHP_BTMR_CTRL_START; counter->IEN = MCHP_BTMR_INTDIS; data->alarm_cb = NULL; data->user_data = NULL; LOG_DBG("%p Counter alarm canceled", dev); return 0; } static uint32_t counter_xec_get_pending_int(const struct device *dev) { struct btmr_regs *counter = COUNTER_XEC_REG_BASE(dev); return counter->STS; } static uint32_t counter_xec_get_top_value(const struct device *dev) { struct btmr_regs *counter = COUNTER_XEC_REG_BASE(dev); return counter->PRLD; } static int counter_xec_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { struct btmr_regs *counter = COUNTER_XEC_REG_BASE(dev); const struct counter_xec_config *counter_cfg = COUNTER_XEC_CONFIG(dev); struct counter_xec_data *data = COUNTER_XEC_DATA(dev); int ret = 0; bool restart; if (data->alarm_cb) { return -EBUSY; } if (cfg->ticks > counter_cfg->info.max_top_value) { return -EINVAL; } restart = ((counter->CTRL & MCHP_BTMR_CTRL_START) != 0U); counter->CTRL &= ~MCHP_BTMR_CTRL_START; if (cfg->flags & COUNTER_TOP_CFG_DONT_RESET) { if (counter->CNT > cfg->ticks) { ret = -ETIME; if (cfg->flags & COUNTER_TOP_CFG_RESET_WHEN_LATE) { counter->CNT = cfg->ticks; } } } else { counter->CNT = cfg->ticks; } counter->PRLD = cfg->ticks; data->top_cb = cfg->callback; data->user_data = cfg->user_data; if (data->top_cb) { counter->IEN = MCHP_BTMR_INTEN; counter->CTRL |= MCHP_BTMR_CTRL_AUTO_RESTART; } else { counter->IEN = MCHP_BTMR_INTDIS; counter->CTRL &= ~MCHP_BTMR_CTRL_AUTO_RESTART; } LOG_DBG("%p Counter top value was set to %u", dev, cfg->ticks); if (restart) { counter->CTRL |= MCHP_BTMR_CTRL_START; } return ret; } static void counter_xec_isr(const struct device *dev) { struct btmr_regs *counter = COUNTER_XEC_REG_BASE(dev); const struct counter_xec_config *counter_cfg = COUNTER_XEC_CONFIG(dev); struct counter_xec_data *data = COUNTER_XEC_DATA(dev); counter_alarm_callback_t alarm_cb; void *user_data; counter->STS = MCHP_BTMR_STS_ACTIVE; #if defined(CONFIG_SOC_MEC172X_NSZ) mchp_soc_ecia_girq_src_clr(counter_cfg->girq_id, counter_cfg->girq_bit); #else MCHP_GIRQ_SRC(counter_cfg->girq_id) = BIT(counter_cfg->girq_bit); #endif LOG_DBG("%p Counter ISR", dev); if (data->alarm_cb) { /* Alarm is one-shot, so disable interrupt and callback */ counter->IEN = MCHP_BTMR_INTDIS; alarm_cb = data->alarm_cb; data->alarm_cb = NULL; user_data = data->user_data; alarm_cb(dev, 0, counter->CNT, user_data); } else if (data->top_cb) { data->top_cb(dev, data->user_data); } } static const struct counter_driver_api counter_xec_api = { .start = counter_xec_start, .stop = counter_xec_stop, .get_value = counter_xec_get_value, .set_alarm = counter_xec_set_alarm, .cancel_alarm = counter_xec_cancel_alarm, .set_top_value = counter_xec_set_top_value, .get_pending_int = counter_xec_get_pending_int, .get_top_value = counter_xec_get_top_value, }; static int counter_xec_init(const struct device *dev) { struct btmr_regs *counter = COUNTER_XEC_REG_BASE(dev); const struct counter_xec_config *counter_cfg = COUNTER_XEC_CONFIG(dev); counter_xec_stop(dev); counter->CTRL &= ~MCHP_BTMR_CTRL_COUNT_UP; counter->CTRL |= (counter_cfg->prescaler << MCHP_BTMR_CTRL_PRESCALE_POS) & MCHP_BTMR_CTRL_PRESCALE_MASK; /* Set preload and actually pre-load the counter */ counter->PRLD = counter_cfg->info.max_top_value; counter->CNT = counter_cfg->info.max_top_value; #if defined(CONFIG_SOC_MEC172X_NSZ) mchp_soc_ecia_girq_src_en(counter_cfg->girq_id, counter_cfg->girq_bit); #else MCHP_GIRQ_ENSET(counter_cfg->girq_id) = BIT(counter_cfg->girq_bit); #endif counter_cfg->config_func(); return 0; } #define COUNTER_XEC_INIT(inst) \ static void counter_xec_irq_config_##inst(void); \ \ static struct counter_xec_data counter_xec_dev_data_##inst; \ \ static struct counter_xec_config counter_xec_dev_config_##inst = { \ .info = { \ .max_top_value = DT_INST_PROP(inst, max_value), \ .freq = DT_INST_PROP(inst, clock_frequency) / \ (1 << DT_INST_PROP(inst, prescaler)), \ .flags = 0, \ .channels = 1, \ }, \ \ .config_func = counter_xec_irq_config_##inst, \ .base_address = DT_INST_REG_ADDR(inst), \ .prescaler = DT_INST_PROP(inst, prescaler), \ .girq_id = DT_INST_PROP_BY_IDX(0, girqs, 0), \ .girq_bit = DT_INST_PROP_BY_IDX(0, girqs, 1), \ }; \ \ DEVICE_DT_INST_DEFINE(inst, \ counter_xec_init, \ NULL, \ &counter_xec_dev_data_##inst, \ &counter_xec_dev_config_##inst, \ POST_KERNEL, \ CONFIG_COUNTER_INIT_PRIORITY, \ &counter_xec_api); \ \ static void counter_xec_irq_config_##inst(void) \ { \ IRQ_CONNECT(DT_INST_IRQN(inst), \ DT_INST_IRQ(inst, priority), \ counter_xec_isr, \ DEVICE_DT_INST_GET(inst), 0); \ irq_enable(DT_INST_IRQN(inst)); \ } DT_INST_FOREACH_STATUS_OKAY(COUNTER_XEC_INIT) ```
/content/code_sandbox/drivers/counter/counter_mchp_xec.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,541
```unknown # Counter configuration options menuconfig COUNTER bool "Counter drivers" help Enable support for counter and timer. if COUNTER config COUNTER_INIT_PRIORITY int "Counter init priority" default 60 help Counter driver device initialization priority. config COUNTER_SHELL bool "Counter shell" depends on SHELL help Enable Shell Commands for Counter and Timer module = COUNTER module-str = counter source "subsys/logging/Kconfig.template.log_config" source "drivers/counter/Kconfig.ambiq" source "drivers/counter/Kconfig.gecko" source "drivers/counter/Kconfig.tmr_cmsdk_apb" source "drivers/counter/Kconfig.dtmr_cmsdk_apb" source "drivers/counter/Kconfig.mcux_rtc" source "drivers/counter/Kconfig.mcux_lpc_rtc" source "drivers/counter/Kconfig.nrfx" source "drivers/counter/Kconfig.imx_epit" source "drivers/counter/Kconfig.stm32_rtc" source "drivers/counter/Kconfig.stm32_timer" source "drivers/counter/Kconfig.sam" source "drivers/counter/Kconfig.sam0" source "drivers/counter/Kconfig.ace" source "drivers/counter/Kconfig.cmos" source "drivers/counter/Kconfig.mcux_gpt" source "drivers/counter/Kconfig.mcux_qtmr" source "drivers/counter/Kconfig.mcux_snvs" source "drivers/counter/Kconfig.mcux_tpm" source "drivers/counter/Kconfig.xec" source "drivers/counter/Kconfig.mcux_lptmr" source "drivers/counter/Kconfig.maxim_ds3231" source "drivers/counter/Kconfig.native_posix" source "drivers/counter/Kconfig.nxp_pit" source "drivers/counter/Kconfig.xlnx" source "drivers/counter/Kconfig.esp32_tmr" source "drivers/counter/Kconfig.esp32_rtc" source "drivers/counter/Kconfig.smartbond_timer" source "drivers/counter/Kconfig.mcp7940n" source "drivers/counter/Kconfig.mcux_ctimer" source "drivers/counter/Kconfig.ifx_cat1" source "drivers/counter/Kconfig.andes_atcpit100" source "drivers/counter/Kconfig.nxp_s32" source "drivers/counter/Kconfig.gd32" source "drivers/counter/Kconfig.dw" source "drivers/counter/Kconfig.rpi_pico" source "drivers/counter/Kconfig.nxp_mrt" endif # COUNTER ```
/content/code_sandbox/drivers/counter/Kconfig
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
535
```unknown # MCUXpresso SDK Low Power Timer (LPTMR) config COUNTER_MCUX_LPTMR bool "MCUX LPTMR driver" default y depends on DT_HAS_NXP_LPTMR_ENABLED || \ COUNTER_MCUX_KINETIS_LPTMR help Enable support for the MCUX Low Power Timer (LPTMR). config COUNTER_MCUX_KINETIS_LPTMR bool default y depends on DT_HAS_NXP_KINETIS_LPTMR_ENABLED select DEPRECATED help The compatible string "nxp,kinetis-lptmr" should be swiched to "nxp,lptmr" in DT. The former will be removed eventually. ```
/content/code_sandbox/drivers/counter/Kconfig.mcux_lptmr
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
157
```c /* * */ #define DT_DRV_COMPAT xlnx_xps_timer_1_00_a #include <zephyr/arch/cpu.h> #include <zephyr/device.h> #include <zephyr/drivers/counter.h> #include <zephyr/irq.h> #include <zephyr/sys/sys_io.h> #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(xlnx_axi_timer, CONFIG_COUNTER_LOG_LEVEL); /* AXI Timer v2.0 registers offsets (See Xilinx PG079 for details) */ #define TCSR0_OFFSET 0x00 #define TLR0_OFFSET 0x04 #define TCR0_OFFSET 0x08 #define TCSR1_OFFSET 0x10 #define TLR1_OFFSET 0x14 #define TCR1_OFFSET 0x18 /* TCSRx bit definitions */ #define TCSR_MDT BIT(0) #define TCSR_UDT BIT(1) #define TCSR_GENT BIT(2) #define TCSR_CAPT BIT(3) #define TCSR_ARHT BIT(4) #define TCSR_LOAD BIT(5) #define TCSR_ENIT BIT(6) #define TCSR_ENT BIT(7) #define TCSR_TINT BIT(8) #define TCSR_PWMA BIT(9) #define TCSR_ENALL BIT(10) #define TCSR_CASC BIT(11) /* 1st timer used as main timer in auto-reload, count-down. generate mode */ #define TCSR0_DEFAULT (TCSR_ENIT | TCSR_ARHT | TCSR_GENT | TCSR_UDT) /* 2nd timer (if available) used as alarm timer in count-down, generate mode */ #define TCSR1_DEFAULT (TCSR_ENIT | TCSR_GENT | TCSR_UDT) struct xlnx_axi_timer_config { struct counter_config_info info; mm_reg_t base; void (*irq_config_func)(const struct device *dev); }; struct xlnx_axi_timer_data { counter_top_callback_t top_callback; void *top_user_data; counter_alarm_callback_t alarm_callback; void *alarm_user_data; }; static inline uint32_t xlnx_axi_timer_read32(const struct device *dev, mm_reg_t offset) { const struct xlnx_axi_timer_config *config = dev->config; return sys_read32(config->base + offset); } static inline void xlnx_axi_timer_write32(const struct device *dev, uint32_t value, mm_reg_t offset) { const struct xlnx_axi_timer_config *config = dev->config; sys_write32(value, config->base + offset); } static int xlnx_axi_timer_start(const struct device *dev) { const struct xlnx_axi_timer_data *data = dev->data; uint32_t tcsr = TCSR0_DEFAULT | TCSR_ENT; LOG_DBG("starting timer"); if (data->alarm_callback) { /* Start both timers synchronously */ tcsr |= TCSR_ENALL; } xlnx_axi_timer_write32(dev, tcsr, TCSR0_OFFSET); return 0; } static int xlnx_axi_timer_stop(const struct device *dev) { const struct xlnx_axi_timer_config *config = dev->config; unsigned int key; LOG_DBG("stopping timer"); key = irq_lock(); /* The timers cannot be stopped synchronously */ if (config->info.channels > 0) { xlnx_axi_timer_write32(dev, TCSR1_DEFAULT, TCSR1_OFFSET); } xlnx_axi_timer_write32(dev, TCSR0_DEFAULT, TCSR0_OFFSET); irq_unlock(key); return 0; } static int xlnx_axi_timer_get_value(const struct device *dev, uint32_t *ticks) { *ticks = xlnx_axi_timer_read32(dev, TCR0_OFFSET); return 0; } static int xlnx_axi_timer_set_alarm(const struct device *dev, uint8_t chan_id, const struct counter_alarm_cfg *cfg) { struct xlnx_axi_timer_data *data = dev->data; unsigned int key; uint32_t tcsr; ARG_UNUSED(chan_id); if (cfg->callback == NULL) { return -EINVAL; } if (data->alarm_callback != NULL) { return -EBUSY; } if (cfg->ticks > xlnx_axi_timer_read32(dev, TLR0_OFFSET)) { return -EINVAL; } if (cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) { /* * Since two different timers (with the same clock signal) are * used for main timer and alarm timer we cannot support * absolute alarms in a reliable way. */ return -ENOTSUP; } LOG_DBG("triggering alarm in 0x%08x ticks", cfg->ticks); /* Load alarm timer */ xlnx_axi_timer_write32(dev, cfg->ticks, TLR1_OFFSET); xlnx_axi_timer_write32(dev, TCSR1_DEFAULT | TCSR_LOAD, TCSR1_OFFSET); key = irq_lock(); data->alarm_callback = cfg->callback; data->alarm_user_data = cfg->user_data; /* Enable alarm timer only if main timer already enabled */ tcsr = xlnx_axi_timer_read32(dev, TCSR0_OFFSET); tcsr &= TCSR_ENT; xlnx_axi_timer_write32(dev, TCSR1_DEFAULT | tcsr, TCSR1_OFFSET); irq_unlock(key); return 0; } static int xlnx_axi_timer_cancel_alarm(const struct device *dev, uint8_t chan_id) { struct xlnx_axi_timer_data *data = dev->data; ARG_UNUSED(chan_id); LOG_DBG("cancelling alarm"); xlnx_axi_timer_write32(dev, TCSR1_DEFAULT, TCSR1_OFFSET); data->alarm_callback = NULL; data->alarm_user_data = NULL; return 0; } static int xlnx_axi_timer_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { struct xlnx_axi_timer_data *data = dev->data; bool reload = true; uint32_t tcsr; uint32_t now; if (cfg->ticks == 0) { return -EINVAL; } if (data->alarm_callback) { return -EBUSY; } LOG_DBG("setting top value to 0x%08x", cfg->ticks); data->top_callback = cfg->callback; data->top_user_data = cfg->user_data; if (cfg->flags & COUNTER_TOP_CFG_DONT_RESET) { reload = false; if (cfg->flags & COUNTER_TOP_CFG_RESET_WHEN_LATE) { now = xlnx_axi_timer_read32(dev, TCR0_OFFSET); reload = cfg->ticks < now; } } tcsr = xlnx_axi_timer_read32(dev, TCSR0_OFFSET); if ((tcsr & TCSR_ENT) == 0U) { /* Timer not enabled, force reload of new top value */ reload = true; } xlnx_axi_timer_write32(dev, cfg->ticks, TLR0_OFFSET); if (reload) { xlnx_axi_timer_write32(dev, tcsr | TCSR_LOAD, TCSR0_OFFSET); xlnx_axi_timer_write32(dev, tcsr, TCSR0_OFFSET); } return 0; } static uint32_t xlnx_axi_timer_get_pending_int(const struct device *dev) { const struct xlnx_axi_timer_config *config = dev->config; uint32_t pending = 0; uint32_t tcsr; tcsr = xlnx_axi_timer_read32(dev, TCSR0_OFFSET); if (tcsr & TCSR_TINT) { pending = 1; } if (config->info.channels > 0) { tcsr = xlnx_axi_timer_read32(dev, TCSR1_OFFSET); if (tcsr & TCSR_TINT) { pending = 1; } } LOG_DBG("%sinterrupt pending", pending ? "" : "no "); return pending; } static uint32_t xlnx_axi_timer_get_top_value(const struct device *dev) { return xlnx_axi_timer_read32(dev, TLR0_OFFSET); } static void xlnx_axi_timer_isr(const struct device *dev) { struct xlnx_axi_timer_data *data = dev->data; counter_alarm_callback_t alarm_cb; uint32_t tcsr; uint32_t now; tcsr = xlnx_axi_timer_read32(dev, TCSR1_OFFSET); if (tcsr & TCSR_TINT) { xlnx_axi_timer_write32(dev, TCSR1_DEFAULT | TCSR_TINT, TCSR1_OFFSET); if (data->alarm_callback) { now = xlnx_axi_timer_read32(dev, TCR0_OFFSET); alarm_cb = data->alarm_callback; data->alarm_callback = NULL; alarm_cb(dev, 0, now, data->alarm_user_data); } } tcsr = xlnx_axi_timer_read32(dev, TCSR0_OFFSET); if (tcsr & TCSR_TINT) { xlnx_axi_timer_write32(dev, tcsr, TCSR0_OFFSET); if (data->top_callback) { data->top_callback(dev, data->top_user_data); } } } static int xlnx_axi_timer_init(const struct device *dev) { const struct xlnx_axi_timer_config *config = dev->config; LOG_DBG("max top value = 0x%08x", config->info.max_top_value); LOG_DBG("frequency = %d", config->info.freq); LOG_DBG("channels = %d", config->info.channels); xlnx_axi_timer_write32(dev, config->info.max_top_value, TLR0_OFFSET); xlnx_axi_timer_write32(dev, TCSR0_DEFAULT | TCSR_LOAD, TCSR0_OFFSET); if (config->info.channels > 0) { xlnx_axi_timer_write32(dev, TCSR1_DEFAULT, TCSR1_OFFSET); } config->irq_config_func(dev); return 0; } static const struct counter_driver_api xlnx_axi_timer_driver_api = { .start = xlnx_axi_timer_start, .stop = xlnx_axi_timer_stop, .get_value = xlnx_axi_timer_get_value, .set_alarm = xlnx_axi_timer_set_alarm, .cancel_alarm = xlnx_axi_timer_cancel_alarm, .set_top_value = xlnx_axi_timer_set_top_value, .get_pending_int = xlnx_axi_timer_get_pending_int, .get_top_value = xlnx_axi_timer_get_top_value, }; #define XLNX_AXI_TIMER_INIT(n) \ static void xlnx_axi_timer_config_func_##n(const struct device *dev); \ \ static struct xlnx_axi_timer_config xlnx_axi_timer_config_##n = { \ .info = { \ .max_top_value = \ GENMASK(DT_INST_PROP(n, xlnx_count_width) - 1, 0), \ .freq = DT_INST_PROP(n, clock_frequency), \ .flags = 0, \ .channels = \ COND_CODE_1(DT_INST_PROP(n, xlnx_one_timer_only), \ (0), (1)), \ }, \ .base = DT_INST_REG_ADDR(n), \ .irq_config_func = xlnx_axi_timer_config_func_##n, \ }; \ \ static struct xlnx_axi_timer_data xlnx_axi_timer_data_##n; \ \ DEVICE_DT_INST_DEFINE(n, &xlnx_axi_timer_init, \ NULL, \ &xlnx_axi_timer_data_##n, \ &xlnx_axi_timer_config_##n, \ POST_KERNEL, \ CONFIG_COUNTER_INIT_PRIORITY, \ &xlnx_axi_timer_driver_api); \ \ static void xlnx_axi_timer_config_func_##n(const struct device *dev) \ { \ IRQ_CONNECT(DT_INST_IRQN(n), DT_INST_IRQ(n, priority), \ xlnx_axi_timer_isr, \ DEVICE_DT_INST_GET(n), 0); \ irq_enable(DT_INST_IRQN(n)); \ } DT_INST_FOREACH_STATUS_OKAY(XLNX_AXI_TIMER_INIT) ```
/content/code_sandbox/drivers/counter/counter_xlnx_axi_timer.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,773
```unknown # # config COUNTER_MICROCHIP_MCP7940N bool "Microchip MCP7940N RTC" default y depends on DT_HAS_MICROCHIP_MCP7940N_ENABLED select I2C help Enable RTC driver based on Microchip MCP7940N I2C device. ```
/content/code_sandbox/drivers/counter/Kconfig.mcp7940n
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
67
```c /* * */ #define DT_DRV_COMPAT nxp_tpm_timer #include <zephyr/drivers/counter.h> #include <zephyr/drivers/clock_control.h> #include <zephyr/irq.h> #include <zephyr/logging/log.h> #include <fsl_tpm.h> LOG_MODULE_REGISTER(mcux_tpm, CONFIG_COUNTER_LOG_LEVEL); #define DEV_CFG(_dev) ((const struct mcux_tpm_config *)(_dev)->config) #define DEV_DATA(_dev) ((struct mcux_tpm_data *)(_dev)->data) struct mcux_tpm_config { struct counter_config_info info; DEVICE_MMIO_NAMED_ROM(tpm_mmio); const struct device *clock_dev; clock_control_subsys_t clock_subsys; tpm_clock_source_t tpm_clock_source; tpm_clock_prescale_t prescale; }; struct mcux_tpm_data { DEVICE_MMIO_NAMED_RAM(tpm_mmio); counter_alarm_callback_t alarm_callback; counter_top_callback_t top_callback; uint32_t freq; void *alarm_user_data; void *top_user_data; }; static TPM_Type *get_base(const struct device *dev) { return (TPM_Type *)DEVICE_MMIO_NAMED_GET(dev, tpm_mmio); } static int mcux_tpm_start(const struct device *dev) { const struct mcux_tpm_config *config = dev->config; TPM_Type *base = get_base(dev); TPM_StartTimer(base, config->tpm_clock_source); return 0; } static int mcux_tpm_stop(const struct device *dev) { TPM_Type *base = get_base(dev); TPM_StopTimer(base); return 0; } static int mcux_tpm_get_value(const struct device *dev, uint32_t *ticks) { TPM_Type *base = get_base(dev); *ticks = TPM_GetCurrentTimerCount(base); return 0; } static int mcux_tpm_set_alarm(const struct device *dev, uint8_t chan_id, const struct counter_alarm_cfg *alarm_cfg) { TPM_Type *base = get_base(dev); uint32_t current = TPM_GetCurrentTimerCount(base); uint32_t top_value = base->MOD; struct mcux_tpm_data *data = dev->data; uint32_t ticks = alarm_cfg->ticks; if (chan_id != kTPM_Chnl_0) { LOG_ERR("Invalid channel id"); return -EINVAL; } if (ticks > (top_value)) return -EINVAL; if ((alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) == 0) { if (top_value - current >= ticks) ticks += current; else ticks -= top_value - current; } if (data->alarm_callback) return -EBUSY; data->alarm_callback = alarm_cfg->callback; data->alarm_user_data = alarm_cfg->user_data; TPM_SetupOutputCompare(base, kTPM_Chnl_0, kTPM_NoOutputSignal, ticks); TPM_EnableInterrupts(base, kTPM_Chnl0InterruptEnable); return 0; } static int mcux_tpm_cancel_alarm(const struct device *dev, uint8_t chan_id) { TPM_Type *base = get_base(dev); struct mcux_tpm_data *data = dev->data; if (chan_id != kTPM_Chnl_0) { LOG_ERR("Invalid channel id"); return -EINVAL; } TPM_DisableInterrupts(base, kTPM_Chnl0InterruptEnable); data->alarm_callback = NULL; return 0; } void mcux_tpm_isr(const struct device *dev) { TPM_Type *base = get_base(dev); struct mcux_tpm_data *data = dev->data; uint32_t current = TPM_GetCurrentTimerCount(base); uint32_t status; status = TPM_GetStatusFlags(base) & (kTPM_Chnl0Flag | kTPM_TimeOverflowFlag); TPM_ClearStatusFlags(base, status); barrier_dsync_fence_full(); if ((status & kTPM_Chnl0Flag) && data->alarm_callback) { TPM_DisableInterrupts(base, kTPM_Chnl0InterruptEnable); counter_alarm_callback_t alarm_cb = data->alarm_callback; data->alarm_callback = NULL; alarm_cb(dev, 0, current, data->alarm_user_data); } if ((status & kTPM_TimeOverflowFlag) && data->top_callback) { data->top_callback(dev, data->top_user_data); } } static uint32_t mcux_tpm_get_pending_int(const struct device *dev) { TPM_Type *base = get_base(dev); return (TPM_GetStatusFlags(base) & kTPM_Chnl0Flag); } static int mcux_tpm_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { const struct mcux_tpm_config *config = dev->config; TPM_Type *base = get_base(dev); struct mcux_tpm_data *data = dev->data; if (data->alarm_callback) return -EBUSY; /* Check if timer already enabled. */ #if defined(FSL_FEATURE_TPM_HAS_SC_CLKS) && FSL_FEATURE_TPM_HAS_SC_CLKS if (base->SC & TPM_SC_CLKS_MASK) { #else if (base->SC & TPM_SC_CMOD_MASK) { #endif /* Timer already enabled, check flags before resetting */ if (cfg->flags & COUNTER_TOP_CFG_DONT_RESET) return -ENOTSUP; TPM_StopTimer(base); base->CNT = 0; TPM_SetTimerPeriod(base, cfg->ticks); TPM_StartTimer(base, config->tpm_clock_source); } else { base->CNT = 0; TPM_SetTimerPeriod(base, cfg->ticks); } data->top_callback = cfg->callback; data->top_user_data = cfg->user_data; TPM_EnableInterrupts(base, kTPM_TimeOverflowInterruptEnable); return 0; } static uint32_t mcux_tpm_get_top_value(const struct device *dev) { TPM_Type *base = get_base(dev); return base->MOD; } static uint32_t mcux_tpm_get_freq(const struct device *dev) { struct mcux_tpm_data *data = dev->data; return data->freq; } static int mcux_tpm_init(const struct device *dev) { const struct mcux_tpm_config *config = dev->config; struct mcux_tpm_data *data = dev->data; tpm_config_t tpmConfig; uint32_t input_clock_freq; TPM_Type *base; DEVICE_MMIO_NAMED_MAP(dev, tpm_mmio, K_MEM_CACHE_NONE | K_MEM_DIRECT_MAP); if (!device_is_ready(config->clock_dev)) { LOG_ERR("clock control device not ready"); return -ENODEV; } if (clock_control_on(config->clock_dev, config->clock_subsys)) { LOG_ERR("Could not turn on clock"); return -EINVAL; } if (clock_control_get_rate(config->clock_dev, config->clock_subsys, &input_clock_freq)) { LOG_ERR("Could not get clock frequency"); return -EINVAL; } data->freq = input_clock_freq / (1U << config->prescale); TPM_GetDefaultConfig(&tpmConfig); tpmConfig.prescale = config->prescale; base = get_base(dev); TPM_Init(base, &tpmConfig); /* Set the modulo to max value. */ base->MOD = TPM_MAX_COUNTER_VALUE(base); return 0; } static const struct counter_driver_api mcux_tpm_driver_api = { .start = mcux_tpm_start, .stop = mcux_tpm_stop, .get_value = mcux_tpm_get_value, .set_alarm = mcux_tpm_set_alarm, .cancel_alarm = mcux_tpm_cancel_alarm, .set_top_value = mcux_tpm_set_top_value, .get_pending_int = mcux_tpm_get_pending_int, .get_top_value = mcux_tpm_get_top_value, .get_freq = mcux_tpm_get_freq, }; #define TO_TPM_PRESCALE_DIVIDE(val) _DO_CONCAT(kTPM_Prescale_Divide_, val) #define TPM_DEVICE_INIT_MCUX(n) \ static struct mcux_tpm_data mcux_tpm_data_ ## n; \ \ static const struct mcux_tpm_config mcux_tpm_config_ ## n = { \ DEVICE_MMIO_NAMED_ROM_INIT(tpm_mmio, DT_DRV_INST(n)), \ .clock_dev = DEVICE_DT_GET(DT_INST_CLOCKS_CTLR(n)), \ .clock_subsys = \ (clock_control_subsys_t)DT_INST_CLOCKS_CELL(n, name), \ .tpm_clock_source = kTPM_SystemClock, \ .prescale = TO_TPM_PRESCALE_DIVIDE(DT_INST_PROP(n, prescaler)), \ .info = { \ .max_top_value = TPM_MAX_COUNTER_VALUE(TPM(n)), \ .freq = 0, \ .channels = 1, \ .flags = COUNTER_CONFIG_INFO_COUNT_UP, \ }, \ }; \ \ static int mcux_tpm_## n ##_init(const struct device *dev); \ DEVICE_DT_INST_DEFINE(n, \ mcux_tpm_## n ##_init, \ NULL, \ &mcux_tpm_data_ ## n, \ &mcux_tpm_config_ ## n, \ POST_KERNEL, \ CONFIG_COUNTER_INIT_PRIORITY, \ &mcux_tpm_driver_api); \ \ static int mcux_tpm_## n ##_init(const struct device *dev) \ { \ IRQ_CONNECT(DT_INST_IRQN(n), \ DT_INST_IRQ(n, priority), \ mcux_tpm_isr, DEVICE_DT_INST_GET(n), 0); \ irq_enable(DT_INST_IRQN(n)); \ return mcux_tpm_init(dev); \ } \ DT_INST_FOREACH_STATUS_OKAY(TPM_DEVICE_INIT_MCUX) ```
/content/code_sandbox/drivers/counter/counter_mcux_tpm.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,260
```unknown # config ACE_V1X_ART_COUNTER bool "DSP ART Wall Clock for ACE V1X" depends on DT_HAS_INTEL_ACE_ART_COUNTER_ENABLED default y help DSP ART Wall Clock used by ACE V1X. config ACE_V1X_RTC_COUNTER bool "DSP RTC Wall Clock for ACE V1X" depends on DT_HAS_INTEL_ACE_RTC_COUNTER_ENABLED default y help DSP RTC Wall Clock used by ACE V1X. ```
/content/code_sandbox/drivers/counter/Kconfig.ace
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
102
```c /* * */ #include <zephyr/drivers/counter.h> #include <zephyr/irq.h> #include <fsl_rtc.h> #include "fsl_power.h" #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(mcux_rtc, CONFIG_COUNTER_LOG_LEVEL); struct mcux_lpc_rtc_data { counter_alarm_callback_t alarm_callback; counter_top_callback_t top_callback; void *alarm_user_data; void *top_user_data; uint32_t value; }; struct mcux_lpc_rtc_config { struct counter_config_info info; RTC_Type *base; const struct device *rtc_dev; void (*irq_config_func)(const struct device *dev); /* Device defined as wake-up source */ bool wakeup_source; }; #if CONFIG_COUNTER_MCUX_LPC_RTC_HIGHRES static int mcux_lpc_rtc_highres_start(const struct device *dev); #endif static void mcux_lpc_rtc_isr(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); struct mcux_lpc_rtc_data *data = dev->data; counter_alarm_callback_t cb; uint32_t current = RTC_GetSecondsTimerCount(config->base); LOG_DBG("Current time is %d ticks", current); if ((RTC_GetStatusFlags(config->base) & RTC_CTRL_ALARM1HZ_MASK) && (data->alarm_callback)) { cb = data->alarm_callback; data->alarm_callback = NULL; cb(dev, 0, current, data->alarm_user_data); } if (data->top_callback) { data->top_callback(dev, data->top_user_data); } /* * Clear any conditions to ack the IRQ * * callback may have already reset the alarm flag if a new * alarm value was programmed to the TAR */ if (RTC_GetStatusFlags(config->base) & RTC_CTRL_ALARM1HZ_MASK) { RTC_ClearStatusFlags(config->base, kRTC_AlarmFlag); } /* Check if the Wake counter interrupt was set */ if (RTC_GetStatusFlags(config->base) & RTC_CTRL_WAKE1KHZ_MASK) { RTC_ClearStatusFlags(config->base, kRTC_WakeupFlag); #if CONFIG_COUNTER_MCUX_LPC_RTC_HIGHRES if (config->base->CTRL & RTC_CTRL_RTC1KHZ_EN_MASK) { mcux_lpc_rtc_highres_start(dev); } #endif } } #if CONFIG_COUNTER_MCUX_LPC_RTC_1HZ #define DT_DRV_COMPAT nxp_lpc_rtc static int mcux_lpc_rtc_start(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); RTC_EnableTimer(config->base, true); return 0; } static int mcux_lpc_rtc_stop(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); RTC_EnableTimer(config->base, false); /* clear out any set alarms */ RTC_SetSecondsTimerMatch(config->base, 0); return 0; } static uint32_t mcux_lpc_rtc_read(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); uint32_t ticks = RTC_GetSecondsTimerCount(config->base); return ticks; } static int mcux_lpc_rtc_get_value(const struct device *dev, uint32_t *ticks) { *ticks = mcux_lpc_rtc_read(dev); return 0; } static int mcux_lpc_rtc_set_alarm(const struct device *dev, uint8_t chan_id, const struct counter_alarm_cfg *alarm_cfg) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); struct mcux_lpc_rtc_data *data = dev->data; uint32_t ticks = alarm_cfg->ticks; uint32_t current = mcux_lpc_rtc_read(dev); LOG_DBG("Current time is %d ticks", current); if (chan_id != 0U) { LOG_ERR("Invalid channel id"); return -EINVAL; } if (data->alarm_callback != NULL) { return -EBUSY; } if ((alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) == 0) { ticks += current; } if (ticks < current) { LOG_ERR("Alarm cannot be earlier than current time"); return -EINVAL; } data->alarm_callback = alarm_cfg->callback; data->alarm_user_data = alarm_cfg->user_data; RTC_SetSecondsTimerMatch(config->base, ticks); LOG_DBG("Alarm set to %d ticks", ticks); return 0; } static int mcux_lpc_rtc_cancel_alarm(const struct device *dev, uint8_t chan_id) { struct mcux_lpc_rtc_data *data = dev->data; if (chan_id != 0U) { LOG_ERR("Invalid channel id"); return -EINVAL; } data->alarm_callback = NULL; return 0; } static int mcux_lpc_rtc_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { return -ENOTSUP; } static uint32_t mcux_lpc_rtc_get_pending_int(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); return RTC_GetStatusFlags(config->base) & RTC_CTRL_ALARM1HZ_MASK; } static uint32_t mcux_lpc_rtc_get_top_value(const struct device *dev) { const struct counter_config_info *info = dev->config; return info->max_top_value; } static int mcux_lpc_rtc_init(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); RTC_Init(config->base); /* Issue a software reset to set the registers to init state */ RTC_Reset(config->base); config->irq_config_func(dev); if (config->wakeup_source) { /* Enable the bit to wakeup from Deep Power Down mode */ RTC_EnableAlarmTimerInterruptFromDPD(config->base, true); } return 0; } static const struct counter_driver_api mcux_rtc_driver_api = { .start = mcux_lpc_rtc_start, .stop = mcux_lpc_rtc_stop, .get_value = mcux_lpc_rtc_get_value, .set_alarm = mcux_lpc_rtc_set_alarm, .cancel_alarm = mcux_lpc_rtc_cancel_alarm, .set_top_value = mcux_lpc_rtc_set_top_value, .get_pending_int = mcux_lpc_rtc_get_pending_int, .get_top_value = mcux_lpc_rtc_get_top_value, }; #define COUNTER_LPC_RTC_DEVICE(id) \ static void mcux_lpc_rtc_irq_config_##id(const struct device *dev); \ static const struct mcux_lpc_rtc_config mcux_lpc_rtc_config_##id = { \ .base = (RTC_Type *)DT_INST_REG_ADDR(id), \ .irq_config_func = mcux_lpc_rtc_irq_config_##id, \ .rtc_dev = DEVICE_DT_GET_OR_NULL(DT_INST_CHILD(id, rtc_highres)), \ .info = { \ .max_top_value = UINT32_MAX, \ .freq = 1, \ .flags = COUNTER_CONFIG_INFO_COUNT_UP, \ .channels = 1, \ }, \ .wakeup_source = DT_INST_PROP(id, wakeup_source) \ }; \ static struct mcux_lpc_rtc_data mcux_lpc_rtc_data_##id; \ DEVICE_DT_INST_DEFINE(id, &mcux_lpc_rtc_init, NULL, \ &mcux_lpc_rtc_data_##id, &mcux_lpc_rtc_config_##id.info, \ POST_KERNEL, CONFIG_COUNTER_INIT_PRIORITY, \ &mcux_rtc_driver_api); \ static void mcux_lpc_rtc_irq_config_##id(const struct device *dev) \ { \ IRQ_CONNECT(DT_INST_IRQN(id), \ DT_INST_IRQ(id, priority), \ mcux_lpc_rtc_isr, DEVICE_DT_INST_GET(id), 0); \ irq_enable(DT_INST_IRQN(id)); \ if (DT_INST_PROP(id, wakeup_source)) { \ EnableDeepSleepIRQ(DT_INST_IRQN(id)); \ } \ } DT_INST_FOREACH_STATUS_OKAY(COUNTER_LPC_RTC_DEVICE) #endif #if CONFIG_COUNTER_MCUX_LPC_RTC_HIGHRES #undef DT_DRV_COMPAT #define DT_DRV_COMPAT nxp_lpc_rtc_highres static int mcux_lpc_rtc_highres_start(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); struct mcux_lpc_rtc_data *data = dev->data; if (config->rtc_dev) { /* We have another RTC driver enabled, check if RTC is enabled */ if ((config->base->CTRL & RTC_CTRL_RTC_EN_MASK) == 0) { /* RTC is not enabled and we do not turn it on as it will effect * the RTC counter value thereby affecting the RTC counter drivers */ LOG_ERR("RTC Wake counter cannot be started as RTC is not enabled."); return -EINVAL; } } else { if ((config->base->CTRL & RTC_CTRL_RTC_EN_MASK) == 0) { RTC_EnableTimer(config->base, true); } } if (data->value == 0) { /* Start from the max value */ RTC_SetWakeupCount(config->base, counter_get_top_value(dev)); } else { RTC_SetWakeupCount(config->base, data->value); } return 0; } static int mcux_lpc_rtc_highres_stop(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); config->base->CTRL &= ~RTC_CTRL_RTC1KHZ_EN_MASK; if (config->rtc_dev == NULL) { /* Disable RTC as no other driver is using it */ RTC_EnableTimer(config->base, false); } return 0; } static uint32_t mcux_lpc_rtc_highres_read(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); uint32_t ticks = RTC_GetWakeupCount(config->base); return ticks; } static int mcux_lpc_rtc_highres_set_alarm(const struct device *dev, uint8_t chan_id, const struct counter_alarm_cfg *alarm_cfg) { return -ENOTSUP; } static int mcux_lpc_rtc_highres_cancel_alarm(const struct device *dev, uint8_t chan_id) { return -ENOTSUP; } static int mcux_lpc_rtc_highres_get_value(const struct device *dev, uint32_t *ticks) { *ticks = mcux_lpc_rtc_highres_read(dev); return 0; } static int mcux_lpc_rtc_highres_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); struct mcux_lpc_rtc_data *data = dev->data; if (cfg->flags & COUNTER_TOP_CFG_DONT_RESET) { return -ENOTSUP; } data->value = cfg->ticks; data->top_callback = cfg->callback; data->top_user_data = cfg->user_data; if (config->base->CTRL & RTC_CTRL_RTC1KHZ_EN_MASK) { return mcux_lpc_rtc_highres_start(dev); } return 0; } static uint32_t mcux_lpc_rtc_highres_get_pending_int(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); return RTC_GetStatusFlags(config->base) & RTC_CTRL_WAKE1KHZ_MASK; } static uint32_t mcux_lpc_rtc_highres_get_top_value(const struct device *dev) { struct mcux_lpc_rtc_data *data = dev->data; const struct counter_config_info *info = dev->config; if (data->value == 0) { return info->max_top_value; } else { return data->value; } } static int mcux_lpc_rtc_highres_init(const struct device *dev) { const struct counter_config_info *info = dev->config; const struct mcux_lpc_rtc_config *config = CONTAINER_OF(info, struct mcux_lpc_rtc_config, info); /* Initialize the RTC if this is only driver using it */ if (config->rtc_dev == NULL) { RTC_Init(config->base); /* Issue a software reset to set the registers to init state */ RTC_Reset(config->base); config->irq_config_func(dev); } if (config->wakeup_source) { /* Enable the bit to wakeup from Deep Power Down mode */ RTC_EnableWakeUpTimerInterruptFromDPD(config->base, true); } return 0; } static const struct counter_driver_api mcux_rtc_highres_driver_api = { .start = mcux_lpc_rtc_highres_start, .stop = mcux_lpc_rtc_highres_stop, .get_value = mcux_lpc_rtc_highres_get_value, .set_alarm = mcux_lpc_rtc_highres_set_alarm, .cancel_alarm = mcux_lpc_rtc_highres_cancel_alarm, .set_top_value = mcux_lpc_rtc_highres_set_top_value, .get_pending_int = mcux_lpc_rtc_highres_get_pending_int, .get_top_value = mcux_lpc_rtc_highres_get_top_value, }; #define COUNTER_LPC_RTC_HIGHRES_IRQ_INIT(n) \ do { \ IRQ_CONNECT(DT_IRQN(DT_INST_PARENT(n)), \ DT_IRQ(DT_INST_PARENT(n), priority), \ mcux_lpc_rtc_isr, \ DEVICE_DT_INST_GET(n), 0); \ irq_enable(DT_IRQN(DT_INST_PARENT(n))); \ if (DT_INST_PROP(n, wakeup_source)) { \ EnableDeepSleepIRQ(DT_IRQN(DT_INST_PARENT(n))); \ } \ } while (false) #define COUNTER_LPC_RTC_HIGHRES_DEVICE(id) \ static void mcux_lpc_rtc_highres_irq_config_##id(const struct device *dev); \ static const struct mcux_lpc_rtc_config mcux_lpc_rtc_highres_config_##id = { \ .base = (RTC_Type *)DT_REG_ADDR(DT_INST_PARENT(id)), \ .rtc_dev = DEVICE_DT_GET_OR_NULL(DT_INST_PARENT(id)), \ .irq_config_func = mcux_lpc_rtc_highres_irq_config_##id, \ .info = { \ .max_top_value = UINT16_MAX, \ .freq = 1000, \ .channels = 0, \ }, \ .wakeup_source = DT_INST_PROP(id, wakeup_source) \ }; \ static struct mcux_lpc_rtc_data mcux_lpc_rtc_highres_data_##id; \ DEVICE_DT_INST_DEFINE(id, &mcux_lpc_rtc_highres_init, NULL, \ &mcux_lpc_rtc_highres_data_##id, \ &mcux_lpc_rtc_highres_config_##id.info, \ POST_KERNEL, CONFIG_COUNTER_INIT_PRIORITY, \ &mcux_rtc_highres_driver_api); \ static void mcux_lpc_rtc_highres_irq_config_##id(const struct device *dev) \ { \ COND_CODE_1(IS_ENABLED(DT_HAS_COMPAT_STATUS_OKAY(nxp_lpc_rtc)), \ (), (COUNTER_LPC_RTC_HIGHRES_IRQ_INIT(id));) \ } DT_INST_FOREACH_STATUS_OKAY(COUNTER_LPC_RTC_HIGHRES_DEVICE) #endif ```
/content/code_sandbox/drivers/counter/counter_mcux_lpc_rtc.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,865
```unknown # Infineon CAT1 counter driver # an affiliate of Cypress Semiconductor Corporation config COUNTER_INFINEON_CAT1 bool "Infineon CAT1 COUNTER driver" default y depends on DT_HAS_INFINEON_CAT1_COUNTER_ENABLED select USE_INFINEON_TIMER help This option enables the COUNTER driver for Infineon CAT1 family. ```
/content/code_sandbox/drivers/counter/Kconfig.ifx_cat1
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
79
```unknown config COUNTER_SAM0_TC32 bool "SAM0 series 32-bit basic timer driver" default y depends on DT_HAS_ATMEL_SAM0_TC32_ENABLED help Enable the SAM0 series timer counter (TC) driver in 32-bit wide mode. ```
/content/code_sandbox/drivers/counter/Kconfig.sam0
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
64
```unknown config COUNTER_NATIVE_POSIX bool "Counter on COUNTER_0" default y depends on DT_HAS_ZEPHYR_NATIVE_POSIX_COUNTER_ENABLED config COUNTER_NATIVE_POSIX_FREQUENCY int "native_posix counter frequency in Hz" default 1000 depends on COUNTER_NATIVE_POSIX config COUNTER_NATIVE_POSIX_NBR_CHANNELS int "native counter, number of channels" default 4 depends on COUNTER_NATIVE_POSIX ```
/content/code_sandbox/drivers/counter/Kconfig.native_posix
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
100
```unknown config COUNTER_NXP_MRT bool "NXP MRT driver" default y depends on DT_HAS_NXP_MRT_CHANNEL_ENABLED && \ DT_HAS_NXP_MRT_ENABLED select RESET help Enable driver for the NXP Multirate Timer (MRT). ```
/content/code_sandbox/drivers/counter/Kconfig.nxp_mrt
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
63
```c /* * * * Source file for the STM32 RTC driver * */ #define DT_DRV_COMPAT st_stm32_rtc #include <time.h> #include <zephyr/drivers/clock_control/stm32_clock_control.h> #include <zephyr/drivers/clock_control.h> #include <zephyr/sys/util.h> #include <zephyr/kernel.h> #include <soc.h> #include <stm32_ll_exti.h> #include <stm32_ll_pwr.h> #include <stm32_ll_rcc.h> #include <stm32_ll_rtc.h> #include <zephyr/drivers/counter.h> #include <zephyr/sys/timeutil.h> #include <zephyr/pm/device.h> #include <zephyr/logging/log.h> #include <zephyr/irq.h> #include "stm32_hsem.h" LOG_MODULE_REGISTER(counter_rtc_stm32, CONFIG_COUNTER_LOG_LEVEL); /* Seconds from 1970-01-01T00:00:00 to 2000-01-01T00:00:00 */ #define T_TIME_OFFSET 946684800 #if defined(CONFIG_SOC_SERIES_STM32L4X) #define RTC_EXTI_LINE LL_EXTI_LINE_18 #elif defined(CONFIG_SOC_SERIES_STM32C0X) \ || defined(CONFIG_SOC_SERIES_STM32G0X) #define RTC_EXTI_LINE LL_EXTI_LINE_19 #elif defined(CONFIG_SOC_SERIES_STM32F4X) \ || defined(CONFIG_SOC_SERIES_STM32F0X) \ || defined(CONFIG_SOC_SERIES_STM32F1X) \ || defined(CONFIG_SOC_SERIES_STM32F2X) \ || defined(CONFIG_SOC_SERIES_STM32F3X) \ || defined(CONFIG_SOC_SERIES_STM32F7X) \ || defined(CONFIG_SOC_SERIES_STM32WBX) \ || defined(CONFIG_SOC_SERIES_STM32G4X) \ || defined(CONFIG_SOC_SERIES_STM32L0X) \ || defined(CONFIG_SOC_SERIES_STM32L1X) \ || defined(CONFIG_SOC_SERIES_STM32L5X) \ || defined(CONFIG_SOC_SERIES_STM32H7X) \ || defined(CONFIG_SOC_SERIES_STM32H5X) \ || defined(CONFIG_SOC_SERIES_STM32WLX) #define RTC_EXTI_LINE LL_EXTI_LINE_17 #endif #if defined(CONFIG_SOC_SERIES_STM32F1X) #define COUNTER_NO_DATE #endif #if DT_INST_CLOCKS_CELL_BY_IDX(0, 1, bus) == STM32_SRC_LSI /* LSI */ #define RTCCLK_FREQ STM32_LSI_FREQ #else /* LSE */ #define RTCCLK_FREQ STM32_LSE_FREQ #endif /* DT_INST_CLOCKS_CELL_BY_IDX(0, 1, bus) == STM32_SRC_LSI */ #if !defined(CONFIG_SOC_SERIES_STM32F1X) #ifndef CONFIG_COUNTER_RTC_STM32_SUBSECONDS #define RTC_ASYNCPRE BIT_MASK(7) #else /* !CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ /* Get the highest possible clock for the subsecond register */ #define RTC_ASYNCPRE 1 #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ #else /* CONFIG_SOC_SERIES_STM32F1X */ #define RTC_ASYNCPRE (RTCCLK_FREQ - 1) #endif /* CONFIG_SOC_SERIES_STM32F1X */ /* Adjust the second sync prescaler to get 1Hz on ck_spre */ #define RTC_SYNCPRE ((RTCCLK_FREQ / (1 + RTC_ASYNCPRE)) - 1) #ifndef CONFIG_COUNTER_RTC_STM32_SUBSECONDS typedef uint32_t tick_t; #else typedef uint64_t tick_t; #endif struct rtc_stm32_config { struct counter_config_info counter_info; LL_RTC_InitTypeDef ll_rtc_config; const struct stm32_pclken *pclken; }; struct rtc_stm32_data { counter_alarm_callback_t callback; uint32_t ticks; void *user_data; #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS bool irq_on_late; #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ }; static inline ErrorStatus ll_func_init_alarm(RTC_TypeDef *rtc, uint32_t format, LL_RTC_AlarmTypeDef *alarmStruct) { #if defined(CONFIG_SOC_SERIES_STM32F1X) return LL_RTC_ALARM_Init(rtc, format, alarmStruct); #else return LL_RTC_ALMA_Init(rtc, format, alarmStruct); #endif } static inline void ll_func_clear_alarm_flag(RTC_TypeDef *rtc) { #if defined(CONFIG_SOC_SERIES_STM32F1X) LL_RTC_ClearFlag_ALR(rtc); #else LL_RTC_ClearFlag_ALRA(rtc); #endif } static inline uint32_t ll_func_is_active_alarm(RTC_TypeDef *rtc) { #if defined(CONFIG_SOC_SERIES_STM32F1X) return LL_RTC_IsActiveFlag_ALR(rtc); #else return LL_RTC_IsActiveFlag_ALRA(rtc); #endif } static inline void ll_func_enable_interrupt_alarm(RTC_TypeDef *rtc) { #if defined(CONFIG_SOC_SERIES_STM32F1X) LL_RTC_EnableIT_ALR(rtc); #else LL_RTC_EnableIT_ALRA(rtc); #endif } static inline void ll_func_disable_interrupt_alarm(RTC_TypeDef *rtc) { #if defined(CONFIG_SOC_SERIES_STM32F1X) LL_RTC_DisableIT_ALR(rtc); #else LL_RTC_DisableIT_ALRA(rtc); #endif } #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS static inline uint32_t ll_func_isenabled_interrupt_alarm(RTC_TypeDef *rtc) { #if defined(CONFIG_SOC_SERIES_STM32F1X) return LL_RTC_IsEnabledIT_ALR(rtc); #else return LL_RTC_IsEnabledIT_ALRA(rtc); #endif } #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ static inline void ll_func_enable_alarm(RTC_TypeDef *rtc) { #if defined(CONFIG_SOC_SERIES_STM32F1X) ARG_UNUSED(rtc); #else LL_RTC_ALMA_Enable(rtc); #endif } static inline void ll_func_disable_alarm(RTC_TypeDef *rtc) { #if defined(CONFIG_SOC_SERIES_STM32F1X) ARG_UNUSED(rtc); #else LL_RTC_ALMA_Disable(rtc); #endif } static void rtc_stm32_irq_config(const struct device *dev); static int rtc_stm32_start(const struct device *dev) { #if defined(CONFIG_SOC_SERIES_STM32WBAX) || defined(CONFIG_SOC_SERIES_STM32U5X) const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE); const struct rtc_stm32_config *cfg = dev->config; /* Enable RTC bus clock */ if (clock_control_on(clk, (clock_control_subsys_t) &cfg->pclken[0]) != 0) { LOG_ERR("RTC clock enabling failed\n"); return -EIO; } #else ARG_UNUSED(dev); z_stm32_hsem_lock(CFG_HW_RCC_SEMID, HSEM_LOCK_DEFAULT_RETRY); LL_RCC_EnableRTC(); z_stm32_hsem_unlock(CFG_HW_RCC_SEMID); #endif return 0; } static int rtc_stm32_stop(const struct device *dev) { #if defined(CONFIG_SOC_SERIES_STM32WBAX) || defined(CONFIG_SOC_SERIES_STM32U5X) const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE); const struct rtc_stm32_config *cfg = dev->config; /* Disable RTC bus clock */ if (clock_control_off(clk, (clock_control_subsys_t) &cfg->pclken[0]) != 0) { LOG_ERR("RTC clock disabling failed\n"); return -EIO; } #else ARG_UNUSED(dev); z_stm32_hsem_lock(CFG_HW_RCC_SEMID, HSEM_LOCK_DEFAULT_RETRY); LL_RCC_DisableRTC(); z_stm32_hsem_unlock(CFG_HW_RCC_SEMID); #endif return 0; } #if !defined(COUNTER_NO_DATE) tick_t rtc_stm32_read(const struct device *dev) { struct tm now = { 0 }; time_t ts; uint32_t rtc_date, rtc_time; tick_t ticks; #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS uint32_t rtc_subseconds; #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ ARG_UNUSED(dev); /* Enable Backup access */ #if defined(PWR_CR_DBP) || defined(PWR_CR1_DBP) || \ defined(PWR_DBPCR_DBP) || defined(PWR_DBPR_DBP) LL_PWR_EnableBkUpAccess(); #endif /* PWR_CR_DBP || PWR_CR1_DBP || PWR_DBPR_DBP */ /* Read time and date registers. Make sure value of the previous register * hasn't been changed while reading the next one. */ do { rtc_date = LL_RTC_DATE_Get(RTC); #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS do { rtc_time = LL_RTC_TIME_Get(RTC); rtc_subseconds = LL_RTC_TIME_GetSubSecond(RTC); } while (rtc_time != LL_RTC_TIME_Get(RTC)); #else /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ rtc_time = LL_RTC_TIME_Get(RTC); #endif } while (rtc_date != LL_RTC_DATE_Get(RTC)); /* Convert calendar datetime to UNIX timestamp */ /* RTC start time: 1st, Jan, 2000 */ /* time_t start: 1st, Jan, 1970 */ now.tm_year = 100 + __LL_RTC_CONVERT_BCD2BIN(__LL_RTC_GET_YEAR(rtc_date)); /* tm_mon allowed values are 0-11 */ now.tm_mon = __LL_RTC_CONVERT_BCD2BIN(__LL_RTC_GET_MONTH(rtc_date)) - 1; now.tm_mday = __LL_RTC_CONVERT_BCD2BIN(__LL_RTC_GET_DAY(rtc_date)); now.tm_hour = __LL_RTC_CONVERT_BCD2BIN(__LL_RTC_GET_HOUR(rtc_time)); now.tm_min = __LL_RTC_CONVERT_BCD2BIN(__LL_RTC_GET_MINUTE(rtc_time)); now.tm_sec = __LL_RTC_CONVERT_BCD2BIN(__LL_RTC_GET_SECOND(rtc_time)); ts = timeutil_timegm(&now); /* Return number of seconds since RTC init */ ts -= T_TIME_OFFSET; __ASSERT(sizeof(time_t) == 8, "unexpected time_t definition"); ticks = ts * counter_get_frequency(dev); #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS /* The RTC counts up, except for the subsecond register which counts * down starting from the sync prescaler value. Add already counted * ticks. */ ticks += RTC_SYNCPRE - rtc_subseconds; #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ return ticks; } #else /* defined(COUNTER_NO_DATE) */ tick_t rtc_stm32_read(const struct device *dev) { uint32_t rtc_time, ticks; ARG_UNUSED(dev); /* Enable Backup access */ #if defined(PWR_CR_DBP) || defined(PWR_CR1_DBP) || \ defined(PWR_DBPCR_DBP) || defined(PWR_DBPR_DBP) LL_PWR_EnableBkUpAccess(); #endif /* PWR_CR_DBP || PWR_CR1_DBP || PWR_DBPR_DBP */ rtc_time = LL_RTC_TIME_Get(RTC); ticks = rtc_time; return ticks; } #endif /* !defined(COUNTER_NO_DATE) */ static int rtc_stm32_get_value(const struct device *dev, uint32_t *ticks) { *ticks = (uint32_t)rtc_stm32_read(dev); return 0; } #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS static int rtc_stm32_get_value_64(const struct device *dev, uint64_t *ticks) { *ticks = rtc_stm32_read(dev); return 0; } #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS static void rtc_stm32_set_int_pending(void) { NVIC_SetPendingIRQ(DT_INST_IRQN(0)); } #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ static int rtc_stm32_set_alarm(const struct device *dev, uint8_t chan_id, const struct counter_alarm_cfg *alarm_cfg) { #if !defined(COUNTER_NO_DATE) struct tm alarm_tm; time_t alarm_val_s; #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS uint32_t alarm_val_ss; #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ #else uint32_t remain; #endif LL_RTC_AlarmTypeDef rtc_alarm; struct rtc_stm32_data *data = dev->data; tick_t now = rtc_stm32_read(dev); tick_t ticks = alarm_cfg->ticks; if (data->callback != NULL) { LOG_DBG("Alarm busy\n"); return -EBUSY; } data->callback = alarm_cfg->callback; data->user_data = alarm_cfg->user_data; #if !defined(COUNTER_NO_DATE) if ((alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) == 0) { /* Add +1 in order to compensate the partially started tick. * Alarm will expire between requested ticks and ticks+1. * In case only 1 tick is requested, it will avoid * that tick+1 event occurs before alarm setting is finished. */ ticks += now + 1; alarm_val_s = (time_t)(ticks / counter_get_frequency(dev)) + T_TIME_OFFSET; } else { alarm_val_s = (time_t)(ticks / counter_get_frequency(dev)); } #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS alarm_val_ss = ticks % counter_get_frequency(dev); #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ #else if ((alarm_cfg->flags & COUNTER_ALARM_CFG_ABSOLUTE) == 0) { remain = ticks + now + 1; } else { remain = ticks; } /* In F1X, an interrupt occurs when the counter expires, * not when the counter matches, so set -1 */ remain--; #endif #if !defined(COUNTER_NO_DATE) #ifndef CONFIG_COUNTER_RTC_STM32_SUBSECONDS LOG_DBG("Set Alarm: %d\n", ticks); #else /* !CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ LOG_DBG("Set Alarm: %llu\n", ticks); #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ gmtime_r(&alarm_val_s, &alarm_tm); /* Apply ALARM_A */ rtc_alarm.AlarmTime.TimeFormat = LL_RTC_TIME_FORMAT_AM_OR_24; rtc_alarm.AlarmTime.Hours = alarm_tm.tm_hour; rtc_alarm.AlarmTime.Minutes = alarm_tm.tm_min; rtc_alarm.AlarmTime.Seconds = alarm_tm.tm_sec; rtc_alarm.AlarmMask = LL_RTC_ALMA_MASK_NONE; rtc_alarm.AlarmDateWeekDaySel = LL_RTC_ALMA_DATEWEEKDAYSEL_DATE; rtc_alarm.AlarmDateWeekDay = alarm_tm.tm_mday; #else rtc_alarm.AlarmTime.Hours = remain / 3600; remain -= rtc_alarm.AlarmTime.Hours * 3600; rtc_alarm.AlarmTime.Minutes = remain / 60; remain -= rtc_alarm.AlarmTime.Minutes * 60; rtc_alarm.AlarmTime.Seconds = remain; #endif LL_RTC_DisableWriteProtection(RTC); ll_func_disable_alarm(RTC); LL_RTC_EnableWriteProtection(RTC); if (ll_func_init_alarm(RTC, LL_RTC_FORMAT_BIN, &rtc_alarm) != SUCCESS) { return -EIO; } LL_RTC_DisableWriteProtection(RTC); #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS /* Care about all bits of the subsecond register */ LL_RTC_ALMA_SetSubSecondMask(RTC, 0xF); LL_RTC_ALMA_SetSubSecond(RTC, RTC_SYNCPRE - alarm_val_ss); #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ ll_func_enable_alarm(RTC); ll_func_clear_alarm_flag(RTC); ll_func_enable_interrupt_alarm(RTC); LL_RTC_EnableWriteProtection(RTC); #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS /* The reference manual says: * "Each change of the RTC_CR register is taken into account after * 1 to 2 RTCCLK clock cycles due to clock synchronization." * It means we need at least two cycles after programming the CR * register. It is confirmed experimentally. * * It should happen only if one tick alarm is requested and a tick * occurs while processing the function. Trigger the irq manually in * this case. */ now = rtc_stm32_read(dev); if ((ticks - now < 2) || (now > ticks)) { data->irq_on_late = 1; rtc_stm32_set_int_pending(); } #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ return 0; } static int rtc_stm32_cancel_alarm(const struct device *dev, uint8_t chan_id) { struct rtc_stm32_data *data = dev->data; LL_RTC_DisableWriteProtection(RTC); ll_func_clear_alarm_flag(RTC); ll_func_disable_interrupt_alarm(RTC); ll_func_disable_alarm(RTC); LL_RTC_EnableWriteProtection(RTC); data->callback = NULL; return 0; } static uint32_t rtc_stm32_get_pending_int(const struct device *dev) { return ll_func_is_active_alarm(RTC) != 0; } static uint32_t rtc_stm32_get_top_value(const struct device *dev) { const struct counter_config_info *info = dev->config; return info->max_top_value; } static int rtc_stm32_set_top_value(const struct device *dev, const struct counter_top_cfg *cfg) { const struct counter_config_info *info = dev->config; if ((cfg->ticks != info->max_top_value) || !(cfg->flags & COUNTER_TOP_CFG_DONT_RESET)) { return -ENOTSUP; } else { return 0; } } void rtc_stm32_isr(const struct device *dev) { struct rtc_stm32_data *data = dev->data; counter_alarm_callback_t alarm_callback = data->callback; uint32_t now = rtc_stm32_read(dev); if (ll_func_is_active_alarm(RTC) != 0 #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS || (data->irq_on_late && ll_func_isenabled_interrupt_alarm(RTC)) #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ ) { LL_RTC_DisableWriteProtection(RTC); ll_func_clear_alarm_flag(RTC); ll_func_disable_interrupt_alarm(RTC); ll_func_disable_alarm(RTC); LL_RTC_EnableWriteProtection(RTC); #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS data->irq_on_late = 0; #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ if (alarm_callback != NULL) { data->callback = NULL; alarm_callback(dev, 0, now, data->user_data); } } #if defined(CONFIG_SOC_SERIES_STM32H7X) && defined(CONFIG_CPU_CORTEX_M4) LL_C2_EXTI_ClearFlag_0_31(RTC_EXTI_LINE); #elif defined(CONFIG_SOC_SERIES_STM32C0X) \ || defined(CONFIG_SOC_SERIES_STM32G0X) \ || defined(CONFIG_SOC_SERIES_STM32L5X) \ || defined(CONFIG_SOC_SERIES_STM32H5X) LL_EXTI_ClearRisingFlag_0_31(RTC_EXTI_LINE); #elif defined(CONFIG_SOC_SERIES_STM32U5X) || defined(CONFIG_SOC_SERIES_STM32WBAX) /* in STM32U5 family RTC is not connected to EXTI */ #else LL_EXTI_ClearFlag_0_31(RTC_EXTI_LINE); #endif } static int rtc_stm32_init(const struct device *dev) { const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE); const struct rtc_stm32_config *cfg = dev->config; struct rtc_stm32_data *data = dev->data; data->callback = NULL; if (!device_is_ready(clk)) { LOG_ERR("clock control device not ready"); return -ENODEV; } /* Enable RTC bus clock */ if (clock_control_on(clk, (clock_control_subsys_t) &cfg->pclken[0]) != 0) { LOG_ERR("clock op failed\n"); return -EIO; } /* Enable Backup access */ z_stm32_hsem_lock(CFG_HW_RCC_SEMID, HSEM_LOCK_DEFAULT_RETRY); #if defined(PWR_CR_DBP) || defined(PWR_CR1_DBP) || \ defined(PWR_DBPCR_DBP) || defined(PWR_DBPR_DBP) LL_PWR_EnableBkUpAccess(); #endif /* PWR_CR_DBP || PWR_CR1_DBP || PWR_DBPR_DBP */ /* Enable RTC clock source */ if (clock_control_configure(clk, (clock_control_subsys_t) &cfg->pclken[1], NULL) != 0) { LOG_ERR("clock configure failed\n"); return -EIO; } #if !defined(CONFIG_SOC_SERIES_STM32WBAX) LL_RCC_EnableRTC(); #endif z_stm32_hsem_unlock(CFG_HW_RCC_SEMID); #if !defined(CONFIG_COUNTER_RTC_STM32_SAVE_VALUE_BETWEEN_RESETS) if (LL_RTC_DeInit(RTC) != SUCCESS) { return -EIO; } #endif if (LL_RTC_Init(RTC, ((LL_RTC_InitTypeDef *) &cfg->ll_rtc_config)) != SUCCESS) { return -EIO; } #ifdef RTC_CR_BYPSHAD LL_RTC_DisableWriteProtection(RTC); LL_RTC_EnableShadowRegBypass(RTC); LL_RTC_EnableWriteProtection(RTC); #endif /* RTC_CR_BYPSHAD */ #if defined(CONFIG_SOC_SERIES_STM32H7X) && defined(CONFIG_CPU_CORTEX_M4) LL_C2_EXTI_EnableIT_0_31(RTC_EXTI_LINE); LL_EXTI_EnableRisingTrig_0_31(RTC_EXTI_LINE); #elif defined(CONFIG_SOC_SERIES_STM32U5X) || defined(CONFIG_SOC_SERIES_STM32WBAX) /* in STM32U5 family RTC is not connected to EXTI */ #else LL_EXTI_EnableIT_0_31(RTC_EXTI_LINE); LL_EXTI_EnableRisingTrig_0_31(RTC_EXTI_LINE); #endif rtc_stm32_irq_config(dev); return 0; } static struct rtc_stm32_data rtc_data; static const struct stm32_pclken rtc_clk[] = STM32_DT_INST_CLOCKS(0); static const struct rtc_stm32_config rtc_config = { .counter_info = { .max_top_value = UINT32_MAX, #ifndef CONFIG_COUNTER_RTC_STM32_SUBSECONDS /* freq = 1Hz for not subsec based driver */ .freq = RTCCLK_FREQ / ((RTC_ASYNCPRE + 1) * (RTC_SYNCPRE + 1)), #else /* !CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ .freq = RTCCLK_FREQ / (RTC_ASYNCPRE + 1), #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ .flags = COUNTER_CONFIG_INFO_COUNT_UP, .channels = 1, }, .ll_rtc_config = { .AsynchPrescaler = RTC_ASYNCPRE, #if !defined(CONFIG_SOC_SERIES_STM32F1X) .HourFormat = LL_RTC_HOURFORMAT_24HOUR, .SynchPrescaler = RTC_SYNCPRE, #else /* CONFIG_SOC_SERIES_STM32F1X */ .OutPutSource = LL_RTC_CALIB_OUTPUT_NONE, #endif /* CONFIG_SOC_SERIES_STM32F1X */ }, .pclken = rtc_clk, }; #ifdef CONFIG_PM_DEVICE static int rtc_stm32_pm_action(const struct device *dev, enum pm_device_action action) { const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE); const struct rtc_stm32_config *cfg = dev->config; switch (action) { case PM_DEVICE_ACTION_RESUME: /* Enable RTC bus clock */ if (clock_control_on(clk, (clock_control_subsys_t) &cfg->pclken[0]) != 0) { LOG_ERR("clock op failed\n"); return -EIO; } break; case PM_DEVICE_ACTION_SUSPEND: break; default: return -ENOTSUP; } return 0; } #endif /* CONFIG_PM_DEVICE */ static const struct counter_driver_api rtc_stm32_driver_api = { .start = rtc_stm32_start, .stop = rtc_stm32_stop, .get_value = rtc_stm32_get_value, #ifdef CONFIG_COUNTER_RTC_STM32_SUBSECONDS .get_value_64 = rtc_stm32_get_value_64, #endif /* CONFIG_COUNTER_RTC_STM32_SUBSECONDS */ .set_alarm = rtc_stm32_set_alarm, .cancel_alarm = rtc_stm32_cancel_alarm, .set_top_value = rtc_stm32_set_top_value, .get_pending_int = rtc_stm32_get_pending_int, .get_top_value = rtc_stm32_get_top_value, }; PM_DEVICE_DT_INST_DEFINE(0, rtc_stm32_pm_action); DEVICE_DT_INST_DEFINE(0, &rtc_stm32_init, PM_DEVICE_DT_INST_GET(0), &rtc_data, &rtc_config, PRE_KERNEL_1, CONFIG_COUNTER_INIT_PRIORITY, &rtc_stm32_driver_api); static void rtc_stm32_irq_config(const struct device *dev) { IRQ_CONNECT(DT_INST_IRQN(0), DT_INST_IRQ(0, priority), rtc_stm32_isr, DEVICE_DT_INST_GET(0), 0); irq_enable(DT_INST_IRQN(0)); } ```
/content/code_sandbox/drivers/counter/counter_ll_stm32_rtc.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
5,630
```unknown # MCUXpresso SDK QTMR config COUNTER_MCUX_QTMR bool "MCUX QTMR driver" default y depends on DT_HAS_NXP_IMX_TMR_ENABLED help Enable support for mcux Quad Timer (QTMR) driver. ```
/content/code_sandbox/drivers/counter/Kconfig.mcux_qtmr
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
58
```unknown config COUNTER_TIMER_RPI_PICO def_bool y select PICOSDK_USE_TIMER select PICOSDK_USE_CLAIM depends on DT_HAS_RASPBERRYPI_PICO_TIMER_ENABLED ```
/content/code_sandbox/drivers/counter/Kconfig.rpi_pico
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
45
```unknown # WiFi drivers configuration options menuconfig WIFI bool "Wi-Fi drivers" if WIFI module = WIFI module-dep = LOG module-str = Log level for Wi-Fi driver module-help = Sets log level for Wi-Fi Device Drivers. source "subsys/net/Kconfig.template.log_config.net" config WIFI_INIT_PRIORITY int "Wi-Fi driver init priority" default 80 help Wi-Fi device driver initialization priority. Do not mess with it unless you know what you are doing. Note that the priority needs to be lower than the net stack so that it can start before the networking sub-system. config WIFI_OFFLOAD bool "Support offloaded Wi-Fi device drivers" select NET_OFFLOAD help Enable support for Full-MAC Wi-Fi devices. config WIFI_USE_NATIVE_NETWORKING bool help When selected, this hidden configuration enables Wi-Fi driver to use native ethernet stack interface. source "drivers/wifi/winc1500/Kconfig.winc1500" source "drivers/wifi/simplelink/Kconfig.simplelink" source "drivers/wifi/eswifi/Kconfig.eswifi" source "drivers/wifi/esp_at/Kconfig.esp_at" source "drivers/wifi/esp32/Kconfig.esp32" source "drivers/wifi/nxp/Kconfig.nxp" source "drivers/wifi/infineon/Kconfig.airoc" source "drivers/wifi/nrfwifi/Kconfig.nrfwifi" endif # WIFI ```
/content/code_sandbox/drivers/wifi/Kconfig
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
306
```c /* * * This barebones driver enables the use of the PC AT-style RTC * (the so-called "CMOS" clock) as a primitive, 1Hz monotonic counter. * * Reading a reliable value from the RTC is a fairly slow process, because * we use legacy I/O ports and do a lot of iterations with spinlocks to read * the RTC state. Plus we have to read the state multiple times because we're * crossing clock domains (no pun intended). Use accordingly. */ #define DT_DRV_COMPAT motorola_mc146818 #include <zephyr/drivers/counter.h> #include <zephyr/device.h> #include <soc.h> /* The "CMOS" device is accessed via an address latch and data port. */ #define X86_CMOS_ADDR (DT_INST_REG_ADDR_BY_IDX(0, 0)) #define X86_CMOS_DATA (DT_INST_REG_ADDR_BY_IDX(0, 1)) /* * A snapshot of the RTC state, or at least the state we're * interested in. This struct should not be modified without * serious consideration, for two reasons: * * 1. Order of the element is important, and must correlate * with addrs[] and NR_BCD_VALS (see below), and * 2. if it doesn't remain exactly 8 bytes long, the * type-punning to compare states will break. */ struct state { uint8_t second, minute, hour, day, month, year, status_a, status_b; }; /* * If the clock is in BCD mode, the first NR_BCD_VALS * values in 'struct state' are BCD-encoded. */ #define NR_BCD_VALS 6 /* * Indices into the CMOS address space that correspond to * the members of 'struct state'. */ const uint8_t addrs[] = { 0, 2, 4, 7, 8, 9, 10, 11 }; /* * Interesting bits in 'struct state'. */ #define STATUS_B_24HR 0x02 /* 24-hour (vs 12-hour) mode */ #define STATUS_B_BIN 0x01 /* binary (vs BCD) mode */ #define HOUR_PM 0x80 /* high bit of hour set = PM */ /* * Read a value from the CMOS. Because of the address latch, * we have to spinlock to make the access atomic. */ static uint8_t read_register(uint8_t addr) { static struct k_spinlock lock; k_spinlock_key_t k; uint8_t val; k = k_spin_lock(&lock); sys_out8(addr, X86_CMOS_ADDR); val = sys_in8(X86_CMOS_DATA); k_spin_unlock(&lock, k); return val; } /* Populate 'state' with current RTC state. */ void read_state(struct state *state) { int i; uint8_t *p; p = (uint8_t *) state; for (i = 0; i < sizeof(*state); ++i) { *p++ = read_register(addrs[i]); } } /* Convert 8-bit (2-digit) BCD to binary equivalent. */ static inline uint8_t decode_bcd(uint8_t val) { return (((val >> 4) & 0x0F) * 10) + (val & 0x0F); } /* * Hinnant's algorithm to calculate the number of days offset from the epoch. */ static uint32_t hinnant(int y, int m, int d) { unsigned yoe; unsigned doy; unsigned doe; int era; y -= (m <= 2); era = ((y >= 0) ? y : (y - 399)) / 400; yoe = y - era * 400; doy = (153 * (m + ((m > 2) ? -3 : 9)) + 2)/5 + d - 1; doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; return era * 146097 + ((int) doe) - 719468; } /* * Get the Unix epoch time (assuming UTC) read from the CMOS RTC. * This function is long, but linear and easy to follow. */ int get_value(const struct device *dev, uint32_t *ticks) { struct state state, state2; uint64_t *pun = (uint64_t *) &state; uint64_t *pun2 = (uint64_t *) &state2; bool pm; uint32_t epoch; ARG_UNUSED(dev); /* * Read the state until we see the same state twice in a row. */ read_state(&state2); do { state = state2; read_state(&state2); } while (*pun != *pun2); /* * Normalize the state; 12hr -> 24hr, BCD -> decimal. * The order is a bit awkward because we need to interpret * the HOUR_PM flag before we adjust for BCD. */ if ((state.status_b & STATUS_B_24HR) != 0U) { pm = false; } else { pm = ((state.hour & HOUR_PM) == HOUR_PM); state.hour &= ~HOUR_PM; } if ((state.status_b & STATUS_B_BIN) == 0U) { uint8_t *cp = (uint8_t *) &state; int i; for (i = 0; i < NR_BCD_VALS; ++i) { *cp = decode_bcd(*cp); ++cp; } } if (pm) { state.hour = (state.hour + 12) % 24; } /* * Convert date/time to epoch time. We don't care about * timezones here, because we're just creating a mapping * that results in a monotonic clock; the absolute value * is irrelevant. */ epoch = hinnant(state.year + 2000, state.month, state.day); epoch *= 86400; /* seconds per day */ epoch += state.hour * 3600; /* seconds per hour */ epoch += state.minute * 60; /* seconds per minute */ epoch += state.second; *ticks = epoch; return 0; } static const struct counter_config_info info = { .max_top_value = UINT_MAX, .freq = 1 }; static const struct counter_driver_api api = { .get_value = get_value }; DEVICE_DT_INST_DEFINE(0, NULL, NULL, NULL, &info, POST_KERNEL, CONFIG_COUNTER_INIT_PRIORITY, &api); ```
/content/code_sandbox/drivers/counter/counter_cmos.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,435
```objective-c /* * */ #ifndef ZEPHYR_INCLUDE_DRIVERS_WIFI_ESP_AT_ESP_H_ #define ZEPHYR_INCLUDE_DRIVERS_WIFI_ESP_AT_ESP_H_ #include <zephyr/kernel.h> #include <zephyr/net/net_context.h> #include <zephyr/net/net_if.h> #include <zephyr/net/net_ip.h> #include <zephyr/net/net_pkt.h> #include <zephyr/net/wifi_mgmt.h> #include "modem_context.h" #include "modem_cmd_handler.h" #include "modem_iface_uart.h" #ifdef __cplusplus extern "C" { #endif /* Define the commands that differ between the AT versions */ #if defined(CONFIG_WIFI_ESP_AT_VERSION_1_7) #define _CWMODE "CWMODE_CUR" #define _CWSAP "CWSAP_CUR" #define _CWJAP "CWJAP_CUR" #define _CIPSTA "CIPSTA_CUR" #define _CIPSTAMAC "CIPSTAMAC_CUR" #define _CIPRECVDATA "+CIPRECVDATA," #define _CIPRECVDATA_END ':' #else #define _CWMODE "CWMODE" #define _CWSAP "CWSAP" #define _CWJAP "CWJAP" #define _CIPSTA "CIPSTA" #define _CIPSTAMAC "CIPSTAMAC" #define _CIPRECVDATA "+CIPRECVDATA:" #define _CIPRECVDATA_END ',' #endif /* * Passive mode differs a bit between firmware versions and the macro * ESP_PROTO_PASSIVE is therefore used to determine what protocol operates in * passive mode. For AT version 1.7 passive mode only affects TCP but in AT * version 2.0 it affects both TCP and UDP. */ #if defined(CONFIG_WIFI_ESP_AT_PASSIVE_MODE) #if defined(CONFIG_WIFI_ESP_AT_VERSION_1_7) #define ESP_PROTO_PASSIVE(proto) (proto == IPPROTO_TCP) #else #define ESP_PROTO_PASSIVE(proto) \ (proto == IPPROTO_TCP || proto == IPPROTO_UDP) #endif /* CONFIG_WIFI_ESP_AT_VERSION_1_7 */ #else #define ESP_PROTO_PASSIVE(proto) 0 #endif /* CONFIG_WIFI_ESP_AT_PASSIVE_MODE */ #define ESP_BUS DT_INST_BUS(0) #if DT_PROP(ESP_BUS, hw_flow_control) == 1 #define _FLOW_CONTROL "3" #else #define _FLOW_CONTROL "0" #endif #if DT_INST_NODE_HAS_PROP(0, target_speed) #define _UART_BAUD DT_INST_PROP(0, target_speed) #else #define _UART_BAUD DT_PROP(ESP_BUS, current_speed) #endif #define _UART_CUR \ STRINGIFY(_UART_BAUD)",8,1,0,"_FLOW_CONTROL #define CONN_CMD_MAX_LEN (sizeof("AT+"_CWJAP"=\"\",\"\"") + \ WIFI_SSID_MAX_LEN * 2 + WIFI_PSK_MAX_LEN * 2) #if defined(CONFIG_WIFI_ESP_AT_DNS_USE) #define ESP_MAX_DNS MIN(3, CONFIG_DNS_RESOLVER_MAX_SERVERS) #endif #define ESP_MAX_SOCKETS 5 /* Maximum amount that can be sent with CIPSEND and read with CIPRECVDATA */ #define ESP_MTU 2048 #define CIPRECVDATA_MAX_LEN ESP_MTU #define INVALID_LINK_ID 255 #define MDM_RING_BUF_SIZE CONFIG_WIFI_ESP_AT_MDM_RING_BUF_SIZE #define MDM_RECV_MAX_BUF CONFIG_WIFI_ESP_AT_MDM_RX_BUF_COUNT #define MDM_RECV_BUF_SIZE CONFIG_WIFI_ESP_AT_MDM_RX_BUF_SIZE #define ESP_CMD_TIMEOUT K_SECONDS(10) #define ESP_SCAN_TIMEOUT K_SECONDS(10) #define ESP_CONNECT_TIMEOUT K_SECONDS(20) #define ESP_IFACE_STATUS_TIMEOUT K_SECONDS(10) #define ESP_INIT_TIMEOUT K_SECONDS(10) #define ESP_MODE_NONE 0 #define ESP_MODE_STA 1 #define ESP_MODE_AP 2 #define ESP_MODE_STA_AP 3 #if defined(CONFIG_WIFI_ESP_AT_VERSION_1_7) || defined(CONFIG_WIFI_ESP_AT_VERSION_2_0) #define ESP_CMD_CWMODE(mode) "AT+"_CWMODE"="STRINGIFY(_CONCAT(ESP_MODE_, mode)) #else #define ESP_CMD_CWMODE(mode) "AT+"_CWMODE"="STRINGIFY(_CONCAT(ESP_MODE_, mode))",0" #endif #define ESP_CWDHCP_MODE_STATION "1" #if defined(CONFIG_WIFI_ESP_AT_VERSION_1_7) #define ESP_CWDHCP_MODE_SOFTAP "0" #else #define ESP_CWDHCP_MODE_SOFTAP "2" #endif #if defined(CONFIG_WIFI_ESP_AT_VERSION_1_7) #define _ESP_CMD_DHCP_ENABLE(mode, enable) \ "AT+CWDHCP_CUR=" mode "," STRINGIFY(enable) #else #define _ESP_CMD_DHCP_ENABLE(mode, enable) \ "AT+CWDHCP=" STRINGIFY(enable) "," mode #endif #define ESP_CMD_DHCP_ENABLE(mode, enable) \ _ESP_CMD_DHCP_ENABLE(_CONCAT(ESP_CWDHCP_MODE_, mode), enable) #define ESP_CMD_SET_IP(ip, gateway, mask) "AT+"_CIPSTA"=\"" \ ip "\",\"" gateway "\",\"" mask "\"" #if defined(CONFIG_WIFI_ESP_AT_SCAN_PASSIVE) #define ESP_CMD_CWLAP "AT+CWLAP=,,,1,," #else #define ESP_CMD_CWLAP "AT+CWLAP" #endif #if defined(CONFIG_WIFI_ESP_AT_SCAN_RESULT_RSSI_ORDERED) #define ESP_CMD_CWLAPOPT_ORDERED "1" #else #define ESP_CMD_CWLAPOPT_ORDERED "0" #endif #if defined(CONFIG_WIFI_ESP_AT_SCAN_MAC_ADDRESS) /* We need ecn,ssid,rssi,mac,channel */ #define ESP_CMD_CWLAPOPT_MASK "31" #else /* no mac: only need ecn,ssid,rssi,channel */ #define ESP_CMD_CWLAPOPT_MASK "23" #endif #define ESP_CMD_CWLAPOPT(sort, mask) "AT+CWLAPOPT=" sort "," mask extern struct esp_data esp_driver_data; enum esp_socket_flags { ESP_SOCK_IN_USE = BIT(1), ESP_SOCK_CONNECTING = BIT(2), ESP_SOCK_CONNECTED = BIT(3), ESP_SOCK_CLOSE_PENDING = BIT(4), ESP_SOCK_WORKQ_STOPPED = BIT(5), }; struct esp_socket { /* internal */ struct k_mutex lock; atomic_t refcount; uint8_t idx; uint8_t link_id; atomic_t flags; /* socket info */ struct sockaddr src; struct sockaddr dst; /* sem */ union { /* handles blocking receive */ struct k_sem sem_data_ready; /* notifies about reaching 0 refcount */ struct k_sem sem_free; }; /* work */ struct k_work connect_work; struct k_work recvdata_work; struct k_work send_work; struct k_work close_work; /* TX packets fifo */ struct k_fifo tx_fifo; /* net context */ struct net_context *context; net_context_connect_cb_t connect_cb; net_context_recv_cb_t recv_cb; /* callback data */ void *conn_user_data; void *recv_user_data; }; enum esp_data_flag { EDF_STA_CONNECTING = BIT(1), EDF_STA_CONNECTED = BIT(2), EDF_STA_LOCK = BIT(3), EDF_AP_ENABLED = BIT(4), }; /* driver data */ struct esp_data { struct net_if *net_iface; uint8_t flags; uint8_t mode; char conn_cmd[CONN_CMD_MAX_LEN]; /* addresses */ struct in_addr ip; struct in_addr gw; struct in_addr nm; uint8_t mac_addr[6]; #if defined(ESP_MAX_DNS) struct sockaddr_in dns_addresses[ESP_MAX_DNS]; #endif /* modem context */ struct modem_context mctx; /* modem interface */ struct modem_iface_uart_data iface_data; uint8_t iface_rb_buf[MDM_RING_BUF_SIZE]; /* modem cmds */ struct modem_cmd_handler_data cmd_handler_data; uint8_t cmd_match_buf[MDM_RECV_BUF_SIZE]; /* socket data */ struct esp_socket sockets[ESP_MAX_SOCKETS]; struct esp_socket *rx_sock; /* work */ struct k_work_q workq; struct k_work init_work; struct k_work_delayable ip_addr_work; struct k_work scan_work; struct k_work connect_work; struct k_work disconnect_work; struct k_work iface_status_work; struct k_work mode_switch_work; struct k_work dns_work; scan_result_cb_t scan_cb; struct wifi_iface_status *wifi_status; struct k_sem wifi_status_sem; /* semaphores */ struct k_sem sem_tx_ready; struct k_sem sem_response; struct k_sem sem_if_ready; struct k_sem sem_if_up; }; int esp_offload_init(struct net_if *iface); struct esp_socket *esp_socket_get(struct esp_data *data, struct net_context *context); int esp_socket_put(struct esp_socket *sock); void esp_socket_init(struct esp_data *data); void esp_socket_close(struct esp_socket *sock); void esp_socket_rx(struct esp_socket *sock, struct net_buf *buf, size_t offset, size_t len); void esp_socket_workq_stop_and_flush(struct esp_socket *sock); struct esp_socket *esp_socket_ref(struct esp_socket *sock); void esp_socket_unref(struct esp_socket *sock); static inline struct esp_socket *esp_socket_ref_from_link_id(struct esp_data *data, uint8_t link_id) { if (link_id >= ARRAY_SIZE(data->sockets)) { return NULL; } return esp_socket_ref(&data->sockets[link_id]); } static inline atomic_val_t esp_socket_flags_update(struct esp_socket *sock, atomic_val_t value, atomic_val_t mask) { atomic_val_t flags; do { flags = atomic_get(&sock->flags); } while (!atomic_cas(&sock->flags, flags, (flags & ~mask) | value)); return flags; } static inline atomic_val_t esp_socket_flags_clear_and_set(struct esp_socket *sock, atomic_val_t clear_flags, atomic_val_t set_flags) { return esp_socket_flags_update(sock, set_flags, clear_flags | set_flags); } static inline atomic_val_t esp_socket_flags_set(struct esp_socket *sock, atomic_val_t flags) { return atomic_or(&sock->flags, flags); } static inline bool esp_socket_flags_test_and_clear(struct esp_socket *sock, atomic_val_t flags) { return (atomic_and(&sock->flags, ~flags) & flags); } static inline bool esp_socket_flags_test_and_set(struct esp_socket *sock, atomic_val_t flags) { return (atomic_or(&sock->flags, flags) & flags); } static inline atomic_val_t esp_socket_flags_clear(struct esp_socket *sock, atomic_val_t flags) { return atomic_and(&sock->flags, ~flags); } static inline atomic_val_t esp_socket_flags(struct esp_socket *sock) { return atomic_get(&sock->flags); } static inline struct esp_data *esp_socket_to_dev(struct esp_socket *sock) { return CONTAINER_OF(sock - sock->idx, struct esp_data, sockets[0]); } static inline void __esp_socket_work_submit(struct esp_socket *sock, struct k_work *work) { struct esp_data *data = esp_socket_to_dev(sock); k_work_submit_to_queue(&data->workq, work); } static inline int esp_socket_work_submit(struct esp_socket *sock, struct k_work *work) { int ret = -EBUSY; k_mutex_lock(&sock->lock, K_FOREVER); if (!(esp_socket_flags(sock) & ESP_SOCK_WORKQ_STOPPED)) { __esp_socket_work_submit(sock, work); ret = 0; } k_mutex_unlock(&sock->lock); return ret; } static inline int esp_socket_queue_tx(struct esp_socket *sock, struct net_pkt *pkt) { int ret = -EBUSY; k_mutex_lock(&sock->lock, K_FOREVER); if (!(esp_socket_flags(sock) & ESP_SOCK_WORKQ_STOPPED)) { k_fifo_put(&sock->tx_fifo, pkt); __esp_socket_work_submit(sock, &sock->send_work); ret = 0; } k_mutex_unlock(&sock->lock); return ret; } static inline bool esp_socket_connected(struct esp_socket *sock) { return (esp_socket_flags(sock) & ESP_SOCK_CONNECTED) != 0; } static inline void esp_flags_set(struct esp_data *dev, uint8_t flags) { dev->flags |= flags; } static inline void esp_flags_clear(struct esp_data *dev, uint8_t flags) { dev->flags &= (~flags); } static inline bool esp_flags_are_set(struct esp_data *dev, uint8_t flags) { return (dev->flags & flags) != 0; } static inline enum net_sock_type esp_socket_type(struct esp_socket *sock) { return net_context_get_type(sock->context); } static inline enum net_ip_protocol esp_socket_ip_proto(struct esp_socket *sock) { return net_context_get_proto(sock->context); } static inline int esp_cmd_send(struct esp_data *data, const struct modem_cmd *handlers, size_t handlers_len, const char *buf, k_timeout_t timeout) { return modem_cmd_send(&data->mctx.iface, &data->mctx.cmd_handler, handlers, handlers_len, buf, &data->sem_response, timeout); } void esp_connect_work(struct k_work *work); void esp_recvdata_work(struct k_work *work); void esp_close_work(struct k_work *work); void esp_send_work(struct k_work *work); #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_DRIVERS_WIFI_ESP_AT_ESP_H_ */ ```
/content/code_sandbox/drivers/wifi/esp_at/esp.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,963
```unknown menuconfig WIFI_ESP_AT bool "Espressif AT Command support" default y depends on DT_HAS_ESPRESSIF_ESP_AT_ENABLED select MODEM select MODEM_CONTEXT select MODEM_CMD_HANDLER select MODEM_IFACE_UART select NET_L2_WIFI_MGMT select WIFI_OFFLOAD imply UART_USE_RUNTIME_CONFIGURE help Enable Espressif AT Command offloaded WiFi driver. It is supported on any serial capable platform and communicates with Espressif chips running ESP-AT firmware (path_to_url if WIFI_ESP_AT config WIFI_ESP_AT_SCAN_PASSIVE bool "Passive scan" help Use passive scanning. config WIFI_ESP_AT_SCAN_MAC_ADDRESS bool "MAC address in scan response" help Get mac address in scan response. config WIFI_ESP_AT_SCAN_RESULT_RSSI_ORDERED bool "Scan result ordering based on RSSI" help Order based on RSSI. config WIFI_ESP_AT_RX_STACK_SIZE int "Stack size for the Espressif esp wifi driver RX thread" default 1024 help This stack is used by the Espressif ESP RX thread. config WIFI_ESP_AT_RX_THREAD_PRIORITY int "Priority of RX thread" default 7 help Priority of thread used for processing RX data. config WIFI_ESP_AT_WORKQ_STACK_SIZE int "Stack size for the esp driver work queue" default 2048 help This stack is used by the work queue to pass off net_pkt data to the rest of the network stack, letting the rx thread continue processing data. config WIFI_ESP_AT_WORKQ_THREAD_PRIORITY int "Priority of work queue thread" default 7 help Priority of thread used for processing driver work queue items. config WIFI_ESP_AT_MDM_RING_BUF_SIZE int "Modem ring buffer size" default 1024 help Ring buffer size used by modem UART interface handler. config WIFI_ESP_AT_MDM_RX_BUF_COUNT int "Modem RX buffer count" default 30 help Number of preallocated RX buffers used by modem command handler. config WIFI_ESP_AT_MDM_RX_BUF_SIZE int "Modem RX buffer size" default 128 help Size of preallocated RX buffers used by modem command handler. config WIFI_ESP_AT_PASSIVE_MODE bool "Use passive mode" help This lets the ESP handle the TCP window so that data can flow at a rate that the driver can handle. Without this, data might get lost if the driver cannot empty the device buffer quickly enough. config WIFI_ESP_AT_RESET_TIMEOUT int "Reset timeout" default 3000 help How long to wait for device to become ready after AT+RST has been sent. This can vary with chipset (ESP8266/ESP32) and firmware version. This is ignored if a reset pin is configured. config WIFI_ESP_AT_RX_NET_PKT_ALLOC_TIMEOUT int "Network interface RX packet allocation timeout" default 5000 help Network interface RX net_pkt allocation timeout in milliseconds. choice prompt "ESP IP Address configuration" default WIFI_ESP_AT_IP_DHCP help Choose whether to use an IP assigned by DHCP Server or configure a static IP Address. config WIFI_ESP_AT_IP_DHCP bool "DHCP" help Use DHCP to get an IP Address. config WIFI_ESP_AT_IP_STATIC bool "Static" help Setup Static IP Address. endchoice if WIFI_ESP_AT_IP_STATIC config WIFI_ESP_AT_IP_ADDRESS string "ESP Station mode IP Address" config WIFI_ESP_AT_IP_GATEWAY string "Gateway Address" config WIFI_ESP_AT_IP_MASK string "Network Mask" endif choice WIFI_ESP_AT_VERSION prompt "AT version" default WIFI_ESP_AT_VERSION_2_1 help Select which version of AT command set should be used. config WIFI_ESP_AT_VERSION_1_7 bool "AT version 1.7" help Use AT command set version 1.7. config WIFI_ESP_AT_VERSION_2_0 bool "AT version 2.0" help Use AT command set version 2.0. config WIFI_ESP_AT_VERSION_2_1 bool "AT version 2.1" help Use AT command set version 2.1. endchoice config WIFI_ESP_AT_DNS_USE bool "Use DNS from ESP" depends on DNS_RESOLVER help Fetch DNS servers from ESP chip with AT+CIPDNS? command and apply that list to system DNS resolver. config WIFI_ESP_AT_CIPDINFO_USE bool "Use CIPDINFO to get peer ip and port" help Enable AT+CIPDINFO got get peer ip-address and port. config WIFI_ESP_AT_FETCH_VERSION bool "Fetch and log ESP-AT firmware version" default y depends on LOG help Fetch information about ESP-AT firmware version. This includes AT command version, SDK (ESP-IDF), board and compile time. endif # WIFI_ESP_AT ```
/content/code_sandbox/drivers/wifi/esp_at/Kconfig.esp_at
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,105
```c /* * */ #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(wifi_esp_at_offload, CONFIG_WIFI_LOG_LEVEL); #include <zephyr/kernel.h> #include <zephyr/device.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <zephyr/net/net_pkt.h> #include <zephyr/net/net_if.h> #include <zephyr/net/net_offload.h> #include "esp.h" static int esp_listen(struct net_context *context, int backlog) { return -ENOTSUP; } static int _sock_connect(struct esp_data *dev, struct esp_socket *sock) { /* Calculate the largest possible AT command length based on both TCP and UDP variants. */ char connect_msg[MAX(sizeof("AT+CIPSTART=000,\"TCP\",\"\",65535,7200") + NET_IPV4_ADDR_LEN, sizeof("AT+CIPSTART=000,\"UDP\",\"\",65535,65535,0,\"\"") + 2 * NET_IPV4_ADDR_LEN)]; char dst_addr_str[NET_IPV4_ADDR_LEN]; char src_addr_str[NET_IPV4_ADDR_LEN]; struct sockaddr src; struct sockaddr dst; int ret; if (!esp_flags_are_set(dev, EDF_STA_CONNECTED | EDF_AP_ENABLED)) { return -ENETUNREACH; } k_mutex_lock(&sock->lock, K_FOREVER); src = sock->src; dst = sock->dst; k_mutex_unlock(&sock->lock); if (dst.sa_family == AF_INET) { net_addr_ntop(dst.sa_family, &net_sin(&dst)->sin_addr, dst_addr_str, sizeof(dst_addr_str)); } else { strcpy(dst_addr_str, "0.0.0.0"); } if (esp_socket_ip_proto(sock) == IPPROTO_TCP) { snprintk(connect_msg, sizeof(connect_msg), "AT+CIPSTART=%d,\"TCP\",\"%s\",%d,7200", sock->link_id, dst_addr_str, ntohs(net_sin(&dst)->sin_port)); } else { if (src.sa_family == AF_INET && net_sin(&src)->sin_port != 0) { net_addr_ntop(src.sa_family, &net_sin(&src)->sin_addr, src_addr_str, sizeof(src_addr_str)); snprintk(connect_msg, sizeof(connect_msg), "AT+CIPSTART=%d,\"UDP\",\"%s\",%d,%d,0,\"%s\"", sock->link_id, dst_addr_str, ntohs(net_sin(&dst)->sin_port), ntohs(net_sin(&src)->sin_port), src_addr_str); } else { snprintk(connect_msg, sizeof(connect_msg), "AT+CIPSTART=%d,\"UDP\",\"%s\",%d", sock->link_id, dst_addr_str, ntohs(net_sin(&dst)->sin_port)); } } LOG_DBG("link %d, ip_proto %s, addr %s", sock->link_id, esp_socket_ip_proto(sock) == IPPROTO_TCP ? "TCP" : "UDP", dst_addr_str); ret = esp_cmd_send(dev, NULL, 0, connect_msg, ESP_CMD_TIMEOUT); if (ret == 0) { esp_socket_flags_set(sock, ESP_SOCK_CONNECTED); if (esp_socket_type(sock) == SOCK_STREAM) { net_context_set_state(sock->context, NET_CONTEXT_CONNECTED); } } else if (ret == -ETIMEDOUT) { /* FIXME: * What if the connection finishes after we return from * here? The caller might think that it can discard the * socket. Set some flag to indicate that the link should * be closed if it ever connects? */ } return ret; } void esp_connect_work(struct k_work *work) { struct esp_socket *sock = CONTAINER_OF(work, struct esp_socket, connect_work); struct esp_data *dev = esp_socket_to_dev(sock); int ret; ret = _sock_connect(dev, sock); k_mutex_lock(&sock->lock, K_FOREVER); if (sock->connect_cb) { sock->connect_cb(sock->context, ret, sock->conn_user_data); } k_mutex_unlock(&sock->lock); } static int esp_bind(struct net_context *context, const struct sockaddr *addr, socklen_t addrlen) { struct esp_socket *sock; struct esp_data *dev; sock = (struct esp_socket *)context->offload_context; dev = esp_socket_to_dev(sock); if (esp_socket_ip_proto(sock) == IPPROTO_TCP) { return 0; } if (IS_ENABLED(CONFIG_NET_IPV4) && addr->sa_family == AF_INET) { LOG_DBG("link %d", sock->link_id); if (esp_socket_connected(sock)) { return -EISCONN; } k_mutex_lock(&sock->lock, K_FOREVER); sock->src = *addr; k_mutex_unlock(&sock->lock); return 0; } return -EAFNOSUPPORT; } static int esp_connect(struct net_context *context, const struct sockaddr *addr, socklen_t addrlen, net_context_connect_cb_t cb, int32_t timeout, void *user_data) { struct esp_socket *sock; struct esp_data *dev; int ret; sock = (struct esp_socket *)context->offload_context; dev = esp_socket_to_dev(sock); LOG_DBG("link %d, timeout %d", sock->link_id, timeout); if (!IS_ENABLED(CONFIG_NET_IPV4) || addr->sa_family != AF_INET) { return -EAFNOSUPPORT; } if (esp_socket_connected(sock)) { return -EISCONN; } k_mutex_lock(&sock->lock, K_FOREVER); sock->dst = *addr; sock->connect_cb = cb; sock->conn_user_data = user_data; k_mutex_unlock(&sock->lock); if (timeout == 0) { esp_socket_work_submit(sock, &sock->connect_work); return 0; } ret = _sock_connect(dev, sock); if (ret != -ETIMEDOUT && cb) { cb(context, ret, user_data); } return ret; } static int esp_accept(struct net_context *context, net_tcp_accept_cb_t cb, int32_t timeout, void *user_data) { return -ENOTSUP; } MODEM_CMD_DIRECT_DEFINE(on_cmd_tx_ready) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); k_sem_give(&dev->sem_tx_ready); return len; } MODEM_CMD_DEFINE(on_cmd_send_ok) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); modem_cmd_handler_set_error(data, 0); k_sem_give(&dev->sem_response); return 0; } MODEM_CMD_DEFINE(on_cmd_send_fail) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); modem_cmd_handler_set_error(data, -EIO); k_sem_give(&dev->sem_response); return 0; } static int _sock_send(struct esp_socket *sock, struct net_pkt *pkt) { struct esp_data *dev = esp_socket_to_dev(sock); char cmd_buf[sizeof("AT+CIPSEND=0,,\"\",") + sizeof(STRINGIFY(ESP_MTU)) - 1 + NET_IPV4_ADDR_LEN + sizeof("65535") - 1]; char addr_str[NET_IPV4_ADDR_LEN]; int ret, write_len, pkt_len; struct net_buf *frag; static const struct modem_cmd cmds[] = { MODEM_CMD_DIRECT(">", on_cmd_tx_ready), MODEM_CMD("SEND OK", on_cmd_send_ok, 0U, ""), MODEM_CMD("SEND FAIL", on_cmd_send_fail, 0U, ""), }; struct sockaddr dst; if (!esp_flags_are_set(dev, EDF_STA_CONNECTED | EDF_AP_ENABLED)) { return -ENETUNREACH; } pkt_len = net_pkt_get_len(pkt); LOG_DBG("link %d, len %d", sock->link_id, pkt_len); if (esp_socket_ip_proto(sock) == IPPROTO_TCP) { snprintk(cmd_buf, sizeof(cmd_buf), "AT+CIPSEND=%d,%d", sock->link_id, pkt_len); } else { k_mutex_lock(&sock->lock, K_FOREVER); dst = sock->dst; k_mutex_unlock(&sock->lock); net_addr_ntop(dst.sa_family, &net_sin(&dst)->sin_addr, addr_str, sizeof(addr_str)); snprintk(cmd_buf, sizeof(cmd_buf), "AT+CIPSEND=%d,%d,\"%s\",%d", sock->link_id, pkt_len, addr_str, ntohs(net_sin(&dst)->sin_port)); } k_sem_take(&dev->cmd_handler_data.sem_tx_lock, K_FOREVER); k_sem_reset(&dev->sem_tx_ready); ret = modem_cmd_send_ext(&dev->mctx.iface, &dev->mctx.cmd_handler, cmds, ARRAY_SIZE(cmds), cmd_buf, &dev->sem_response, ESP_CMD_TIMEOUT, MODEM_NO_TX_LOCK | MODEM_NO_UNSET_CMDS); if (ret < 0) { LOG_DBG("Failed to send command"); goto out; } /* Reset semaphore that will be released by 'SEND OK' or 'SEND FAIL' */ k_sem_reset(&dev->sem_response); /* Wait for '>' */ ret = k_sem_take(&dev->sem_tx_ready, K_MSEC(5000)); if (ret < 0) { LOG_DBG("Timeout waiting for tx"); goto out; } frag = pkt->frags; while (frag && pkt_len) { write_len = MIN(pkt_len, frag->len); dev->mctx.iface.write(&dev->mctx.iface, frag->data, write_len); pkt_len -= write_len; frag = frag->frags; } /* Wait for 'SEND OK' or 'SEND FAIL' */ ret = k_sem_take(&dev->sem_response, ESP_CMD_TIMEOUT); if (ret < 0) { LOG_DBG("No send response"); goto out; } ret = modem_cmd_handler_get_error(&dev->cmd_handler_data); if (ret != 0) { LOG_DBG("Failed to send data"); } out: (void)modem_cmd_handler_update_cmds(&dev->cmd_handler_data, NULL, 0U, false); k_sem_give(&dev->cmd_handler_data.sem_tx_lock); return ret; } static bool esp_socket_can_send(struct esp_socket *sock) { atomic_val_t flags = esp_socket_flags(sock); if ((flags & ESP_SOCK_CONNECTED) && !(flags & ESP_SOCK_CLOSE_PENDING)) { return true; } return false; } static int esp_socket_send_one_pkt(struct esp_socket *sock) { struct net_context *context = sock->context; struct net_pkt *pkt; int ret; pkt = k_fifo_get(&sock->tx_fifo, K_NO_WAIT); if (!pkt) { return -ENOMSG; } if (!esp_socket_can_send(sock)) { goto pkt_unref; } ret = _sock_send(sock, pkt); if (ret < 0) { LOG_ERR("Failed to send data: link %d, ret %d", sock->link_id, ret); /* * If this is stream data, then we should stop pushing anything * more to this socket, as there will be a hole in the data * stream, which application layer is not expecting. */ if (esp_socket_type(sock) == SOCK_STREAM) { if (!esp_socket_flags_test_and_set(sock, ESP_SOCK_CLOSE_PENDING)) { esp_socket_work_submit(sock, &sock->close_work); } } } else if (context->send_cb) { context->send_cb(context, ret, context->user_data); } pkt_unref: net_pkt_unref(pkt); return 0; } void esp_send_work(struct k_work *work) { struct esp_socket *sock = CONTAINER_OF(work, struct esp_socket, send_work); int err; do { err = esp_socket_send_one_pkt(sock); } while (err != -ENOMSG); } static int esp_sendto(struct net_pkt *pkt, const struct sockaddr *dst_addr, socklen_t addrlen, net_context_send_cb_t cb, int32_t timeout, void *user_data) { struct net_context *context; struct esp_socket *sock; struct esp_data *dev; int ret = 0; context = pkt->context; sock = (struct esp_socket *)context->offload_context; dev = esp_socket_to_dev(sock); LOG_DBG("link %d, timeout %d", sock->link_id, timeout); if (!esp_flags_are_set(dev, EDF_STA_CONNECTED | EDF_AP_ENABLED)) { return -ENETUNREACH; } if (esp_socket_type(sock) == SOCK_STREAM) { atomic_val_t flags = esp_socket_flags(sock); if (!(flags & ESP_SOCK_CONNECTED) || (flags & ESP_SOCK_CLOSE_PENDING)) { return -ENOTCONN; } } else { if (!esp_socket_connected(sock)) { if (!dst_addr) { return -ENOTCONN; } /* Use a timeout of 5000 ms here even though the * timeout parameter might be different. We want to * have a valid link id before proceeding. */ ret = esp_connect(context, dst_addr, addrlen, NULL, (5 * MSEC_PER_SEC), NULL); if (ret < 0) { return ret; } } else if (esp_socket_type(sock) == SOCK_DGRAM) { memcpy(&sock->dst, dst_addr, addrlen); } } return esp_socket_queue_tx(sock, pkt); } static int esp_send(struct net_pkt *pkt, net_context_send_cb_t cb, int32_t timeout, void *user_data) { return esp_sendto(pkt, NULL, 0, cb, timeout, user_data); } #define CIPRECVDATA_CMD_MIN_LEN (sizeof("+CIPRECVDATA,L:") - 1) #if defined(CONFIG_WIFI_ESP_AT_CIPDINFO_USE) #define CIPRECVDATA_CMD_MAX_LEN (sizeof("+CIPRECVDATA,LLLL,\"255.255.255.255\",65535:") - 1) #else #define CIPRECVDATA_CMD_MAX_LEN (sizeof("+CIPRECVDATA,LLLL:") - 1) #endif static int cmd_ciprecvdata_parse(struct esp_socket *sock, struct net_buf *buf, uint16_t len, int *data_offset, int *data_len, char *ip_str, int *port) { char cmd_buf[CIPRECVDATA_CMD_MAX_LEN + 1]; char *endptr; size_t frags_len; size_t match_len; frags_len = net_buf_frags_len(buf); if (frags_len < CIPRECVDATA_CMD_MIN_LEN) { return -EAGAIN; } match_len = net_buf_linearize(cmd_buf, CIPRECVDATA_CMD_MAX_LEN, buf, 0, CIPRECVDATA_CMD_MAX_LEN); cmd_buf[match_len] = 0; *data_len = strtol(&cmd_buf[len], &endptr, 10); #if defined(CONFIG_WIFI_ESP_AT_CIPDINFO_USE) char *strstart = endptr + 1; char *strend = strchr(strstart, ','); if (strstart == NULL || strend == NULL) { return -EAGAIN; } memcpy(ip_str, strstart, strend - strstart); ip_str[strend - strstart] = '\0'; *port = strtol(strend + 1, &endptr, 10); #else ARG_UNUSED(ip_str); ARG_UNUSED(port); #endif if (endptr == &cmd_buf[len] || (*endptr == 0 && match_len >= CIPRECVDATA_CMD_MAX_LEN) || *data_len > CIPRECVDATA_MAX_LEN) { LOG_ERR("Invalid cmd: %s", cmd_buf); return -EBADMSG; } else if (*endptr == 0) { return -EAGAIN; } else if (*endptr != _CIPRECVDATA_END) { LOG_ERR("Invalid end of cmd: 0x%02x != 0x%02x", *endptr, _CIPRECVDATA_END); return -EBADMSG; } /* data_offset is the offset to where the actual data starts */ *data_offset = (endptr - cmd_buf) + 1; /* FIXME: Inefficient way of waiting for data */ if (*data_offset + *data_len > frags_len) { return -EAGAIN; } *endptr = 0; return 0; } MODEM_CMD_DIRECT_DEFINE(on_cmd_ciprecvdata) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); struct esp_socket *sock = dev->rx_sock; int data_offset, data_len; int err; #if defined(CONFIG_WIFI_ESP_AT_CIPDINFO_USE) char raw_remote_ip[INET_ADDRSTRLEN + 3] = {0}; int port = 0; err = cmd_ciprecvdata_parse(sock, data->rx_buf, len, &data_offset, &data_len, raw_remote_ip, &port); #else err = cmd_ciprecvdata_parse(sock, data->rx_buf, len, &data_offset, &data_len, NULL, NULL); #endif if (err) { if (err == -EAGAIN) { return -EAGAIN; } return err; } #if defined(CONFIG_WIFI_ESP_AT_CIPDINFO_USE) struct sockaddr_in *recv_addr = (struct sockaddr_in *) &sock->context->remote; recv_addr->sin_port = htons(port); recv_addr->sin_family = AF_INET; /* IP addr comes within quotation marks, which is disliked by * conv function. So we remove them by subtraction 2 from * raw_remote_ip length and index from &raw_remote_ip[1]. */ char remote_ip_addr[INET_ADDRSTRLEN]; size_t remote_ip_str_len; remote_ip_str_len = MIN(sizeof(remote_ip_addr) - 1, strlen(raw_remote_ip) - 2); strncpy(remote_ip_addr, &raw_remote_ip[1], remote_ip_str_len); remote_ip_addr[remote_ip_str_len] = '\0'; if (net_addr_pton(AF_INET, remote_ip_addr, &recv_addr->sin_addr) < 0) { LOG_ERR("Invalid src addr %s", remote_ip_addr); err = -EIO; return err; } #endif esp_socket_rx(sock, data->rx_buf, data_offset, data_len); return data_offset + data_len; } void esp_recvdata_work(struct k_work *work) { struct esp_socket *sock = CONTAINER_OF(work, struct esp_socket, recvdata_work); struct esp_data *data = esp_socket_to_dev(sock); char cmd[sizeof("AT+CIPRECVDATA=000,"STRINGIFY(CIPRECVDATA_MAX_LEN))]; static const struct modem_cmd cmds[] = { MODEM_CMD_DIRECT(_CIPRECVDATA, on_cmd_ciprecvdata), }; int ret; LOG_DBG("reading available data on link %d", sock->link_id); data->rx_sock = sock; snprintk(cmd, sizeof(cmd), "AT+CIPRECVDATA=%d,%d", sock->link_id, CIPRECVDATA_MAX_LEN); ret = esp_cmd_send(data, cmds, ARRAY_SIZE(cmds), cmd, ESP_CMD_TIMEOUT); if (ret < 0) { LOG_ERR("Error during rx: link %d, ret %d", sock->link_id, ret); } } void esp_close_work(struct k_work *work) { struct esp_socket *sock = CONTAINER_OF(work, struct esp_socket, close_work); atomic_val_t old_flags; old_flags = esp_socket_flags_clear(sock, (ESP_SOCK_CONNECTED | ESP_SOCK_CLOSE_PENDING)); if ((old_flags & ESP_SOCK_CONNECTED) && (old_flags & ESP_SOCK_CLOSE_PENDING)) { esp_socket_close(sock); } /* Should we notify that the socket has been closed? */ if (old_flags & ESP_SOCK_CLOSE_PENDING) { k_mutex_lock(&sock->lock, K_FOREVER); if (sock->recv_cb) { sock->recv_cb(sock->context, NULL, NULL, NULL, 0, sock->recv_user_data); k_sem_give(&sock->sem_data_ready); } k_mutex_unlock(&sock->lock); } } static int esp_recv(struct net_context *context, net_context_recv_cb_t cb, int32_t timeout, void *user_data) { struct esp_socket *sock = context->offload_context; struct esp_data *dev = esp_socket_to_dev(sock); int ret; LOG_DBG("link_id %d, timeout %d, cb %p, data %p", sock->link_id, timeout, cb, user_data); /* * UDP "listening" socket needs to be bound using AT+CIPSTART before any * traffic can be received. */ if (!esp_socket_connected(sock) && esp_socket_ip_proto(sock) == IPPROTO_UDP && sock->src.sa_family == AF_INET && net_sin(&sock->src)->sin_port != 0) { _sock_connect(dev, sock); } k_mutex_lock(&sock->lock, K_FOREVER); sock->recv_cb = cb; sock->recv_user_data = user_data; k_sem_reset(&sock->sem_data_ready); k_mutex_unlock(&sock->lock); if (timeout == 0) { return 0; } ret = k_sem_take(&sock->sem_data_ready, K_MSEC(timeout)); k_mutex_lock(&sock->lock, K_FOREVER); sock->recv_cb = NULL; sock->recv_user_data = NULL; k_mutex_unlock(&sock->lock); return ret; } static int esp_put(struct net_context *context) { struct esp_socket *sock = context->offload_context; esp_socket_workq_stop_and_flush(sock); if (esp_socket_flags_test_and_clear(sock, ESP_SOCK_CONNECTED)) { esp_socket_close(sock); } k_mutex_lock(&sock->lock, K_FOREVER); sock->connect_cb = NULL; sock->recv_cb = NULL; k_mutex_unlock(&sock->lock); k_sem_reset(&sock->sem_free); esp_socket_unref(sock); /* * Let's get notified when refcount reaches 0. Call to * esp_socket_unref() in this function might or might not be the last * one. The reason is that there might be still some work in progress in * esp_rx thread (parsing unsolicited AT command), so we want to wait * until it finishes. */ k_sem_take(&sock->sem_free, K_FOREVER); sock->context = NULL; esp_socket_put(sock); return 0; } static int esp_get(sa_family_t family, enum net_sock_type type, enum net_ip_protocol ip_proto, struct net_context **context) { struct esp_socket *sock; struct esp_data *dev; LOG_DBG(""); if (family != AF_INET) { return -EAFNOSUPPORT; } /* FIXME: * iface has not yet been assigned to context so there is currently * no way to know which interface to operate on. Therefore this driver * only supports one device node. */ dev = &esp_driver_data; sock = esp_socket_get(dev, *context); if (!sock) { LOG_ERR("No socket available!"); return -ENOMEM; } return 0; } static struct net_offload esp_offload = { .get = esp_get, .bind = esp_bind, .listen = esp_listen, .connect = esp_connect, .accept = esp_accept, .send = esp_send, .sendto = esp_sendto, .recv = esp_recv, .put = esp_put, }; int esp_offload_init(struct net_if *iface) { iface->if_dev->offload = &esp_offload; return 0; } ```
/content/code_sandbox/drivers/wifi/esp_at/esp_offload.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
5,305
```c /* * */ #include "esp.h" #include <zephyr/logging/log.h> LOG_MODULE_DECLARE(wifi_esp_at, CONFIG_WIFI_LOG_LEVEL); #define RX_NET_PKT_ALLOC_TIMEOUT \ K_MSEC(CONFIG_WIFI_ESP_AT_RX_NET_PKT_ALLOC_TIMEOUT) struct esp_workq_flush_data { struct k_work work; struct k_sem sem; }; struct esp_socket *esp_socket_get(struct esp_data *data, struct net_context *context) { struct esp_socket *sock = data->sockets; struct esp_socket *sock_end = sock + ARRAY_SIZE(data->sockets); for (; sock < sock_end; sock++) { if (!esp_socket_flags_test_and_set(sock, ESP_SOCK_IN_USE)) { /* here we should configure all the stuff needed */ sock->context = context; context->offload_context = sock; sock->connect_cb = NULL; sock->recv_cb = NULL; memset(&sock->src, 0x0, sizeof(sock->src)); memset(&sock->dst, 0x0, sizeof(sock->dst)); atomic_inc(&sock->refcount); return sock; } } return NULL; } int esp_socket_put(struct esp_socket *sock) { atomic_clear(&sock->flags); return 0; } struct esp_socket *esp_socket_ref(struct esp_socket *sock) { atomic_val_t ref; do { ref = atomic_get(&sock->refcount); if (!ref) { return NULL; } } while (!atomic_cas(&sock->refcount, ref, ref + 1)); return sock; } void esp_socket_unref(struct esp_socket *sock) { atomic_val_t ref; do { ref = atomic_get(&sock->refcount); if (!ref) { return; } } while (!atomic_cas(&sock->refcount, ref, ref - 1)); k_sem_give(&sock->sem_free); } void esp_socket_init(struct esp_data *data) { struct esp_socket *sock; int i; for (i = 0; i < ARRAY_SIZE(data->sockets); ++i) { sock = &data->sockets[i]; sock->idx = i; sock->link_id = i; atomic_clear(&sock->refcount); atomic_clear(&sock->flags); k_mutex_init(&sock->lock); k_sem_init(&sock->sem_data_ready, 0, 1); k_work_init(&sock->connect_work, esp_connect_work); k_work_init(&sock->recvdata_work, esp_recvdata_work); k_work_init(&sock->close_work, esp_close_work); k_work_init(&sock->send_work, esp_send_work); k_fifo_init(&sock->tx_fifo); } } static struct net_pkt *esp_socket_prepare_pkt(struct esp_socket *sock, struct net_buf *src, size_t offset, size_t len) { struct esp_data *data = esp_socket_to_dev(sock); struct net_buf *frag; struct net_pkt *pkt; size_t to_copy; pkt = net_pkt_rx_alloc_with_buffer(data->net_iface, len, AF_UNSPEC, 0, RX_NET_PKT_ALLOC_TIMEOUT); if (!pkt) { return NULL; } frag = src; /* find the right fragment to start copying from */ while (frag && offset >= frag->len) { offset -= frag->len; frag = frag->frags; } /* traverse the fragment chain until len bytes are copied */ while (frag && len > 0) { to_copy = MIN(len, frag->len - offset); if (net_pkt_write(pkt, frag->data + offset, to_copy) != 0) { net_pkt_unref(pkt); return NULL; } /* to_copy is always <= len */ len -= to_copy; frag = frag->frags; /* after the first iteration, this value will be 0 */ offset = 0; } net_pkt_set_context(pkt, sock->context); net_pkt_cursor_init(pkt); #if defined(CONFIG_WIFI_ESP_AT_CIPDINFO_USE) memcpy(&pkt->remote, &sock->context->remote, sizeof(pkt->remote)); pkt->family = sock->src.sa_family; #endif return pkt; } void esp_socket_rx(struct esp_socket *sock, struct net_buf *buf, size_t offset, size_t len) { struct net_pkt *pkt; atomic_val_t flags; flags = esp_socket_flags(sock); #ifdef CONFIG_WIFI_ESP_AT_PASSIVE_MODE /* In Passive Receive mode, ESP modem will buffer rx data and make it still * available even though the peer has closed the connection. */ if (!(flags & ESP_SOCK_CONNECTED) && !(flags & ESP_SOCK_CLOSE_PENDING)) { #else if (!(flags & ESP_SOCK_CONNECTED) || (flags & ESP_SOCK_CLOSE_PENDING)) { #endif LOG_DBG("Received data on closed link %d", sock->link_id); return; } pkt = esp_socket_prepare_pkt(sock, buf, offset, len); if (!pkt) { LOG_ERR("Failed to get net_pkt: len %zu", len); if (esp_socket_type(sock) == SOCK_STREAM) { if (!esp_socket_flags_test_and_set(sock, ESP_SOCK_CLOSE_PENDING)) { esp_socket_work_submit(sock, &sock->close_work); } } return; } #ifdef CONFIG_NET_SOCKETS /* We need to claim the net_context mutex here so that the ordering of * net_context and socket mutex claims matches the TX code path. Failure * to do so can lead to deadlocks. */ if (sock->context->cond.lock) { k_mutex_lock(sock->context->cond.lock, K_FOREVER); } #endif /* CONFIG_NET_SOCKETS */ k_mutex_lock(&sock->lock, K_FOREVER); if (sock->recv_cb) { sock->recv_cb(sock->context, pkt, NULL, NULL, 0, sock->recv_user_data); k_sem_give(&sock->sem_data_ready); } else { /* Discard */ net_pkt_unref(pkt); } k_mutex_unlock(&sock->lock); #ifdef CONFIG_NET_SOCKETS if (sock->context->cond.lock) { k_mutex_unlock(sock->context->cond.lock); } #endif /* CONFIG_NET_SOCKETS */ } void esp_socket_close(struct esp_socket *sock) { struct esp_data *dev = esp_socket_to_dev(sock); char cmd_buf[sizeof("AT+CIPCLOSE=000")]; int ret; snprintk(cmd_buf, sizeof(cmd_buf), "AT+CIPCLOSE=%d", sock->link_id); ret = esp_cmd_send(dev, NULL, 0, cmd_buf, ESP_CMD_TIMEOUT); if (ret < 0) { /* FIXME: * If link doesn't close correctly here, esp_get could * allocate a socket with an already open link. */ LOG_ERR("Failed to close link %d, ret %d", sock->link_id, ret); } } static void esp_workq_flush_work(struct k_work *work) { struct esp_workq_flush_data *flush = CONTAINER_OF(work, struct esp_workq_flush_data, work); k_sem_give(&flush->sem); } void esp_socket_workq_stop_and_flush(struct esp_socket *sock) { struct esp_workq_flush_data flush; k_work_init(&flush.work, esp_workq_flush_work); k_sem_init(&flush.sem, 0, 1); k_mutex_lock(&sock->lock, K_FOREVER); esp_socket_flags_set(sock, ESP_SOCK_WORKQ_STOPPED); __esp_socket_work_submit(sock, &flush.work); k_mutex_unlock(&sock->lock); k_sem_take(&flush.sem, K_FOREVER); } ```
/content/code_sandbox/drivers/wifi/esp_at/esp_socket.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,676
```unknown # Nordic Wi-Fi driver for nRF70 series SoCs # # # menuconfig WIFI_NRF70 bool "nRF70 driver" select NET_L2_WIFI_MGMT if NETWORKING select NET_L2_ETHERNET_MGMT if NETWORKING && NET_L2_ETHERNET select WIFI_USE_NATIVE_NETWORKING if NETWORKING select EXPERIMENTAL if !SOC_SERIES_NRF53X && !SOC_SERIES_NRF91X default y depends on \ DT_HAS_NORDIC_NRF7002_SPI_ENABLED || DT_HAS_NORDIC_NRF7002_QSPI_ENABLED || \ DT_HAS_NORDIC_NRF7001_SPI_ENABLED || DT_HAS_NORDIC_NRF7001_QSPI_ENABLED || \ DT_HAS_NORDIC_NRF7000_SPI_ENABLED || DT_HAS_NORDIC_NRF7000_QSPI_ENABLED help Nordic Wi-Fi Driver if WIFI_NRF70 # Hidden symbols for internal use config WIFI_NRF7002 bool default y if DT_HAS_NORDIC_NRF7002_SPI_ENABLED || DT_HAS_NORDIC_NRF7002_QSPI_ENABLED config WIFI_NRF7001 bool default y if DT_HAS_NORDIC_NRF7001_SPI_ENABLED || DT_HAS_NORDIC_NRF7001_QSPI_ENABLED config WIFI_NRF7000 bool default y if DT_HAS_NORDIC_NRF7000_SPI_ENABLED || DT_HAS_NORDIC_NRF7000_QSPI_ENABLED module = WIFI_NRF70_BUS module-dep = LOG module-str = Log level for Wi-Fi nRF70 bus layers module-help = Sets log level for Wi-Fi nRF70 bus layers source "subsys/net/Kconfig.template.log_config.net" config WIFI_NRF70_BUS_LOG_LEVEL # Enable error by default default 1 choice NRF70_OPER_MODES bool "nRF70 operating modes" default NRF70_SYSTEM_WITH_RAW_MODES if !WIFI_NRF7000 && \ (NRF70_RAW_DATA_TX || NRF70_RAW_DATA_RX || NRF70_PROMISC_DATA_RX) default NRF70_SYSTEM_MODE if !WIFI_NRF7000 default NRF70_SCAN_ONLY if WIFI_NRF7000 help Select the operating mode of the nRF70 driver config NRF70_SYSTEM_MODE bool "nRF70 system mode" depends on WIFI_NRF7002 || WIFI_NRF7001 select WIFI_NM_WPA_SUPPLICANT help Select this option to enable system mode of the nRF70 driver config NRF70_SCAN_ONLY bool "nRF70 scan only mode" depends on WIFI_NRF7000 help Select this option to enable scan only mode of the nRF70 driver config NRF70_RADIO_TEST bool "Radio test mode of the nRF70 driver" config NRF70_SYSTEM_WITH_RAW_MODES bool "nRF70 system mode with raw modes" depends on WIFI_NRF7002 || WIFI_NRF7001 select WIFI_NM_WPA_SUPPLICANT help Select this option to enable system mode of the nRF70 driver with raw modes endchoice config NET_L2_ETHERNET default y if !NRF70_RADIO_TEST config HEAP_MEM_POOL_ADD_SIZE_NRF70 # Use a maximum that works for typical usecases and boards, each sample/app can override # this value if needed by using CONFIG_HEAP_MEM_POOL_IGNORE_MIN def_int 25000 if NRF70_SCAN_ONLY def_int 150000 if NRF70_SYSTEM_MODE || NRF70_SYSTEM_WITH_RAW_MODES config NRF70_STA_MODE bool "nRF70 STA mode" default y help Select this option to enable STA mode of the nRF70 driver config NRF70_AP_MODE bool "Access point mode" depends on WIFI_NM_WPA_SUPPLICANT_AP config NRF70_P2P_MODE bool "P2P support in driver" endif # NRF70_SYSTEM_MODE || NRF70_SYSTEM_WITH_RAW_MODES config NRF70_RAW_DATA_TX bool "RAW TX data path in the driver" select EXPERIMENTAL config NRF70_RAW_DATA_RX bool "RAW RX sniffer operation in the driver" select EXPERIMENTAL config NRF70_PROMISC_DATA_RX bool "promiscuous RX sniffer operation in the driver" select WIFI_NM_WPA_SUPPLICANT select EXPERIMENTAL select NET_PROMISCUOUS_MODE config NRF70_DATA_TX bool "TX data path in the driver" default y if NRF70_SYSTEM_MODE || NRF70_SYSTEM_WITH_RAW_MODES config NRF_WIFI_IF_AUTO_START bool "Wi-Fi interface auto start on boot" default y config NRF_WIFI_PATCHES_BUILTIN bool "Store nRF70 FW patches as part of the driver" default y help Select this option to store nRF70 FW patches as part of the driver. This option impacts the code memory footprint of the driver. config CUSTOM_LINKER_SCRIPT string "Custom linker script for nRF70 FW patches" default "${ZEPHYR_BASE}/../nrf/drivers/wifi/nrf70/rpu_fw_patches.ld" config NRF_WIFI_LOW_POWER bool "low power mode in nRF Wi-Fi chipsets" default y config NRF70_TCP_IP_CHECKSUM_OFFLOAD bool "TCP/IP checksum offload" default y config NRF70_REG_DOMAIN string "The ISO/IEC alpha2 country code for the country in which this device is currently operating. Default 00 (World regulatory)" # 00 is used for World regulatory default "00" # Making calls to RPU from net_mgmt callbacks. # # If WPA supplicant is enabled, then don't override as it has higher # stack requirements. config NET_MGMT_EVENT_STACK_SIZE default 2048 if !WIFI_NM_WPA_SUPPLICANT config NRF70_LOG_VERBOSE bool "Maintains the verbosity of information in logs" default y module = WIFI_NRF70 module-dep = LOG module-str = Log level for Wi-Fi nRF70 driver module-help = Sets log level for Wi-Fi nRF70 driver source "subsys/logging/Kconfig.template.log_config" config WIFI_NRF70_LOG_LEVEL # Enable error by default default 1 config NRF70_ON_QSPI def_bool DT_HAS_NORDIC_NRF7002_QSPI_ENABLED || \ DT_HAS_NORDIC_NRF7001_QSPI_ENABLED || \ DT_HAS_NORDIC_NRF7000_QSPI_ENABLED select NRFX_QSPI config NRF70_ON_SPI def_bool DT_HAS_NORDIC_NRF7002_SPI_ENABLED || \ DT_HAS_NORDIC_NRF7001_SPI_ENABLED || \ DT_HAS_NORDIC_NRF7000_SPI_ENABLED select SPI config NRF70_2_4G_ONLY def_bool y if WIFI_NRF7001 # Wi-Fi and SR Coexistence Hardware configuration. config NRF70_SR_COEX bool "Wi-Fi and SR coexistence support" config NRF70_SR_COEX_RF_SWITCH bool "GPIO configuration to control SR side RF switch position" config NRF70_WORKQ_STACK_SIZE int "Stack size for workqueue" default 4096 config NRF70_WORKQ_MAX_ITEMS int "Maximum work items for all workqueues" default 100 config NRF70_MAX_TX_PENDING_QLEN int "Maximum number of pending TX packets" default 18 config NRF70_UTIL depends on SHELL bool "Utility shell in nRF70 driver" config NRF70_QSPI_LOW_POWER bool "low power mode in QSPI" default y if NRF_WIFI_LOW_POWER config NRF70_PCB_LOSS_2G int "PCB loss for 2.4 GHz band" default 0 range 0 4 help Specifies PCB loss from the antenna connector to the RF pin. The values are in dB scale in steps of 1dB and range of 0-4dB. The loss is considered in the RX path only. config NRF70_PCB_LOSS_5G_BAND1 int "PCB loss for 5 GHz band (5150 MHz - 5350 MHz, Channel-32 - Channel-68)" default 0 range 0 4 help Specifies PCB loss from the antenna connector to the RF pin. The values are in dB scale in steps of 1dB and range of 0-4dB. The loss is considered in the RX path only. config NRF70_PCB_LOSS_5G_BAND2 int "PCB loss for 5 GHz band (5470 MHz - 5730 MHz, Channel-96 - Channel-144)" default 0 range 0 4 help Specifies PCB loss from the antenna connector to the RF pin. The values are in dB scale in steps of 1dB and range of 0-4dB. The loss is considered in the RX path only. config NRF70_PCB_LOSS_5G_BAND3 int "PCB loss for 5 GHz band (5730 MHz - 5895 MHz, Channel-149 - Channel-177)" default 0 range 0 4 help Specifies PCB loss from the antenna connector to the RF pin. The values are in dB scale in steps of 1dB and range of 0-4dB. The loss is considered in the RX path only. config NRF70_ANT_GAIN_2G int "Antenna gain for 2.4 GHz band" default 0 range 0 6 config NRF70_ANT_GAIN_5G_BAND1 int "Antenna gain for 5 GHz band (5150 MHz - 5350 MHz)" default 0 range 0 6 config NRF70_ANT_GAIN_5G_BAND2 int "Antenna gain for 5 GHz band (5470 MHz - 5730 MHz)" default 0 range 0 6 config NRF70_ANT_GAIN_5G_BAND3 int "Antenna gain for 5 GHz band (5730 MHz - 5895 MHz)" default 0 range 0 6 config NRF70_BAND_2G_LOWER_EDGE_BACKOFF_DSSS int "DSSS Transmit power backoff (in dB) for lower edge of 2.4 GHz frequency band" default 0 range 0 10 config NRF70_BAND_2G_LOWER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for lower edge of 2.4 GHz frequency band" default 0 range 0 10 config NRF70_BAND_2G_LOWER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for lower edge of 2.4 GHz frequency band" default 0 range 0 10 config NRF70_BAND_2G_UPPER_EDGE_BACKOFF_DSSS int "DSSS Transmit power backoff (in dB) for upper edge of 2.4 GHz frequency band" default 0 range 0 10 config NRF70_BAND_2G_UPPER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for upper edge of 2.4 GHz frequency band" default 0 range 0 10 config NRF70_BAND_2G_UPPER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for upper edge of 2.4 GHz frequency band" default 0 range 0 10 config NRF70_BAND_UNII_1_LOWER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for lower edge of UNII-1 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_1_LOWER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for lower edge of UNII-1 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_1_UPPER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for upper edge of UNII-1 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_1_UPPER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for upper edge of UNII-1 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_2A_LOWER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for lower edge of UNII-2A frequency band" default 0 range 0 10 config NRF70_BAND_UNII_2A_LOWER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for lower edge of UNII-2A frequency band" default 0 range 0 10 config NRF70_BAND_UNII_2A_UPPER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for upper edge of UNII-2A frequency band" default 0 range 0 10 config NRF70_BAND_UNII_2A_UPPER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for upper edge of UNII-2A frequency band" default 0 range 0 10 config NRF70_BAND_UNII_2C_LOWER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for lower edge of UNII-2C frequency band" default 0 range 0 10 config NRF70_BAND_UNII_2C_LOWER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for lower edge of UNII-2C frequency band" default 0 range 0 10 config NRF70_BAND_UNII_2C_UPPER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for upper edge of UNII-2C frequency band" default 0 range 0 10 config NRF70_BAND_UNII_2C_UPPER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for upper edge of UNII-2C frequency band" default 0 range 0 10 config NRF70_BAND_UNII_3_LOWER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for lower edge of UNII-3 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_3_LOWER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for lower edge of UNII-3 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_3_UPPER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for upper edge of UNII-3 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_3_UPPER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for upper edge of UNII-3 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_4_LOWER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for lower edge of UNII-4 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_4_LOWER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for lower edge of UNII-4 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_4_UPPER_EDGE_BACKOFF_HT int "HT/VHT Transmit power backoff (in dB) for upper edge of UNII-4 frequency band" default 0 range 0 10 config NRF70_BAND_UNII_4_UPPER_EDGE_BACKOFF_HE int "HE Transmit power backoff (in dB) for upper edge of UNII-4 frequency band" default 0 range 0 10 # Performance fine tuning options config NRF70_RX_NUM_BUFS int "Number of RX buffers" default 48 config NRF70_MAX_TX_AGGREGATION int "Maximum number of TX packets to aggregate" default 12 config NRF70_MAX_TX_TOKENS int "Maximum number of TX tokens" range 5 12 if !NRF70_RADIO_TEST default 10 config NRF70_TX_MAX_DATA_SIZE int "Maximum size of TX data" default 1600 config NRF70_RX_MAX_DATA_SIZE int "Maximum size of RX data" default 1600 config NRF70_TX_DONE_WQ_ENABLED bool "TX done workqueue (impacts performance negatively)" config NRF70_RX_WQ_ENABLED bool "RX workqueue" # Use for IRQ processing (TODO: using for BH processing causes issues) config NUM_METAIRQ_PRIORITIES default 1 config NRF70_IRQ_WQ_PRIORITY int "Priority of the workqueue for handling IRQs" default -15 config NRF70_BH_WQ_PRIORITY int "Priority of the workqueue for handling bottom half" default 0 config NRF70_IRQ_WQ_STACK_SIZE int "Stack size of the workqueue for handling IRQs" default 2048 config NRF70_BH_WQ_STACK_SIZE int "Stack size of the workqueue for handling bottom half" default 2048 if NRF70_TX_DONE_WQ_ENABLED config NRF70_TX_DONE_WQ_PRIORITY int "Priority of the workqueue for handling TX done" default 0 config NRF70_TX_DONE_WQ_STACK_SIZE int "Stack size of the workqueue for handling TX done" default 2048 endif # NRF70_TX_DONE_WQ_ENABLED if NRF70_RX_WQ_ENABLED config NRF70_RX_WQ_PRIORITY int "Priority of the workqueue for handling RX" default 0 config NRF70_RX_WQ_STACK_SIZE int "Stack size of the workqueue for handling RX" default 2048 endif # NRF70_RX_WQ_ENABLED if NRF_WIFI_LOW_POWER config NRF70_RPU_PS_IDLE_TIMEOUT_MS int "RPU power save idle timeout in milliseconds" default 10 config NRF70_RPU_EXTEND_TWT_SP bool "extending TWT service period" help In case frames accepted before beginning of SP are not transmitted before the SP completes then typically they are dropped to conform to SP window as per specification i.e., no transmission outside SP window. This feature mitigates the frame loss by transmitting even after SP completion by using standard contention mechanism which is allowed in specification but not recommended. As the device is actively transmitting beyond SP, the power consumption increases depending on the amount of traffic available at the start of SP. Please note that if a frame is sent after SP starts it will be queued and this mechanism is not used. endif # NRF_WIFI_LOW_POWER config WIFI_FIXED_MAC_ADDRESS string "WiFi Fixed MAC address in format XX:XX:XX:XX:XX:XX" help This overrides the MAC address read from OTP. Strictly for testing purposes only. choice prompt "Wi-Fi MAC address type" default WIFI_OTP_MAC_ADDRESS if WIFI_FIXED_MAC_ADDRESS = "" default WIFI_FIXED_MAC_ADDRESS_ENABLED if WIFI_FIXED_MAC_ADDRESS != "" help Select the type of MAC address to be used by the Wi-Fi driver config WIFI_OTP_MAC_ADDRESS bool "Use MAC address from OTP" help This option uses the MAC address stored in the OTP memory of the nRF70. config WIFI_FIXED_MAC_ADDRESS_ENABLED bool "fixed MAC address" help Enable fixed MAC address config WIFI_RANDOM_MAC_ADDRESS bool "random MAC address generation at runtime" depends on ENTROPY_GENERATOR help This option enables random MAC address generation at runtime. The random MAC address is generated using the entropy device random generator. endchoice config NRF70_RSSI_STALE_TIMEOUT_MS int "RSSI stale timeout in milliseconds" default 1000 help RSSI stale timeout is the period after which driver queries RPU to get the RSSI the value. If data is active (e.g. ping), driver stores the RSSI value from the received frames and provides this stored information to wpa_supplicant. In this case a higher value will be suitable as stored RSSI value at driver will be updated regularly. If data is not active or after the stale timeout duration, driver queries the RPU to get the RSSI value and provides it to wpa_supplicant. The value should be set to lower value as driver does not store it and requires RPU to provide the info. if NETWORKING # Finetune defaults for certain system components used by the driver config SYSTEM_WORKQUEUE_STACK_SIZE default 4096 config NET_TX_STACK_SIZE default 4096 config NET_RX_STACK_SIZE default 4096 config NET_TC_TX_COUNT default 1 endif # NETWORKING config MAIN_STACK_SIZE default 4096 config SHELL_STACK_SIZE default 4096 # Override the Wi-Fi subsytems WIFI_MGMT_SCAN_SSID_FILT_MAX parameter, # since we support a maximum of 2 SSIDs for scan result filtering. config WIFI_MGMT_SCAN_SSID_FILT_MAX default 2 config NRF_WIFI_SCAN_MAX_BSS_CNT int "Maximum number of scan results to return." default 0 range 0 65535 help Maximum number of scan results to return. 0 represents unlimited number of BSSes. config NRF_WIFI_BEAMFORMING bool "Wi-Fi beamforming. Enabling beamforming can provide slight improvement in performance where as disabling it can provide better power saving in low network activity applications" default y config WIFI_NRF70_SCAN_TIMEOUT_S int "Scan timeout in seconds" default 30 menu "nRF Wi-Fi operation band(s)" visible if !NRF70_2_4G_ONLY config NRF_WIFI_2G_BAND bool "Set operation band to 2.4GHz" default y if NRF70_2_4G_ONLY config NRF_WIFI_5G_BAND bool "Set operation band to 5GHz" depends on !NRF70_2_4G_ONLY config NRF_WIFI_OP_BAND int "Options to set operation band" default 1 if NRF_WIFI_2G_BAND default 2 if NRF_WIFI_5G_BAND default 3 help Set this option to select frequency band 1 - 2.4GHz 2 - 5GHz 3 - All ( 2.4GHz and 5GHz ) endmenu config NRF_WIFI_IFACE_MTU int "MTU for Wi-Fi interface" range 576 2304 if NET_IPV4 range 1280 2304 if NET_IPV6 default 1500 config WIFI_NRF70_SKIP_LOCAL_ADMIN_MAC bool "Suppress networks with non-individual MAC address as BSSID in the scan results" help Wi-Fi access points use locally administered MAC address to manage multiple virtual interfaces, for geo-location usecase these networks from the virtual interfaces do not help in anyway as they are co-located with the primary interface that has globally unique MAC address. So, to save resources, this option drops such networks from the scan results. config WIFI_NRF70_SCAN_DISABLE_DFS_CHANNELS bool "Disables DFS channels in scan operation" help This option disables inclusion of DFS channels in scan operation. This is useful to reduce the scan time, as DFS channels are seldom used. config NET_INTERFACE_NAME_LEN # nordic_wlanN default 15 config NRF_WIFI_AP_DEAD_DETECT_TIMEOUT int "Access point dead detection timeout in seconds" range 1 30 default 20 help The number of seconds after which AP is declared dead if no beacons are received from the AP. Used to detect AP silently going down e.g., power off. config NRF_WIFI_RPU_RECOVERY bool "RPU recovery mechanism" select EXPERIMENTAL help Enable RPU recovery mechanism to recover from RPU (nRF70) hang. This feature performs an interface reset (down and up) which triggers a RPU coldboot. Application's network connection will be lost during the recovery process and it is application's responsibility to re-establish the network connection. if NRF_WIFI_RPU_RECOVERY config NRF_WIFI_RPU_RECOVERY_PROPAGATION_DELAY_MS int "RPU recovery propagation delay in milliseconds" default 10 help Propagation delay in milliseconds to wait after RPU is powered down before powering it up. This delay is required to ensure that the recovery is propagted to all the applications and stack and have enough time to clean up the resources. config NET_MGMT_EVENT_QUEUE_SIZE # Doing interface down and up even with delay puts a lot of events in the queue default 16 endif # NRF_WIFI_RPU_RECOVERY config NRF_WIFI_COMBINED_BUCKEN_IOVDD_GPIO bool help Enable this option to use a single GPIO to control both buck enable and IOVDD enable, there will be a internal hardware switch to add delay between the two operations. This is typically 4ms delay for nRF70. endif # WIFI_NRF70 ```
/content/code_sandbox/drivers/wifi/nrfwifi/Kconfig.nrfwifi
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
5,404
```linker script /* * */ /** * @file * @brief Custom Linker command/script file * * Custom Linker script for the Cortex-M platforms. */ #include <zephyr/linker/sections.h> #include <zephyr/devicetree.h> #include <zephyr/linker/linker-defs.h> #include <zephyr/linker/linker-tool.h> #if CONFIG_BOARD_NRF5340DK_NRF5340_CPUAPP || CONFIG_BOARD_NRF52840DK_NRF52840 /* * nRF53/52 series ship an external flash that can be used for XIP using QSPI/SPI. * * Note: In nRF7002 external flash using is accessible only using SPI but there is no * support for XIP, so, relocation cannot be used. */ #if CONFIG_BOARD_NRF5340DK_NRF5340_CPUAPP #define EXTFLASH_BASE_ADDR 0x10000000 #define EXTFLASH_SIZE 0x800000 #elif CONFIG_BOARD_NRF52840DK_NRF52840 #define EXTFLASH_BASE_ADDR 0x12000000 #define EXTFLASH_SIZE 0x800000 #endif /* CONFIG_BOARD_NRF5340DK_NRF5340_CPUAPP */ #if USE_PARTITION_MANAGER && PM_EXTERNAL_FLASH_ADDRESS #include <pm_config.h> #define EXTFLASH_ADDRESS (EXTFLASH_BASE_ADDR + PM_EXTERNAL_FLASH_ADDRESS) #undef EXTFLASH_SIZE #define EXTFLASH_SIZE (PM_EXTERNAL_FLASH_SIZE) #else #define EXTFLASH_ADDRESS (EXTFLASH_BASE_ADDR) #endif /* USE_PARTITION_MANAGER && PM_EXTERNAL_FLASH_ADDRESS */ MEMORY { EXTFLASH (wx) : ORIGIN = EXTFLASH_ADDRESS, LENGTH = EXTFLASH_SIZE } #endif /* CONFIG_BOARD_NRF5340DK_NRF5340_CPUAPP || CONFIG_BOARD_NRF52840DK_NRF52840 */ #include <zephyr/arch/arm/cortex_m/scripts/linker.ld> ```
/content/code_sandbox/drivers/wifi/nrfwifi/rpu_fw_patches.ld
linker script
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
392
```c /* * */ /** * @brief File containing work specific definitions for the * Zephyr OS layer of the Wi-Fi driver. */ #include <zephyr/kernel.h> #include <zephyr/init.h> #include <zephyr/sys/printk.h> #include <zephyr/logging/log.h> #include "work.h" LOG_MODULE_DECLARE(wifi_nrf, CONFIG_WIFI_NRF70_LOG_LEVEL); K_THREAD_STACK_DEFINE(bh_wq_stack_area, CONFIG_NRF70_BH_WQ_STACK_SIZE); struct k_work_q zep_wifi_bh_q; K_THREAD_STACK_DEFINE(irq_wq_stack_area, CONFIG_NRF70_IRQ_WQ_STACK_SIZE); struct k_work_q zep_wifi_intr_q; #ifdef CONFIG_NRF70_TX_DONE_WQ_ENABLED K_THREAD_STACK_DEFINE(tx_done_wq_stack_area, CONFIG_NRF70_TX_DONE_WQ_STACK_SIZE); struct k_work_q zep_wifi_tx_done_q; #endif /* CONFIG_NRF70_TX_DONE_WQ_ENABLED */ #ifdef CONFIG_NRF70_RX_WQ_ENABLED K_THREAD_STACK_DEFINE(rx_wq_stack_area, CONFIG_NRF70_RX_WQ_STACK_SIZE); struct k_work_q zep_wifi_rx_q; #endif /* CONFIG_NRF70_RX_WQ_ENABLED */ struct zep_work_item zep_work_item[CONFIG_NRF70_WORKQ_MAX_ITEMS]; int get_free_work_item_index(void) { int i; for (i = 0; i < CONFIG_NRF70_WORKQ_MAX_ITEMS; i++) { if (zep_work_item[i].in_use) continue; return i; } return -1; } void workqueue_callback(struct k_work *work) { struct zep_work_item *item = CONTAINER_OF(work, struct zep_work_item, work); item->callback(item->data); } struct zep_work_item *work_alloc(enum zep_work_type type) { int free_work_index = get_free_work_item_index(); if (free_work_index < 0) { LOG_ERR("%s: Reached maximum work items", __func__); return NULL; } zep_work_item[free_work_index].in_use = true; zep_work_item[free_work_index].type = type; return &zep_work_item[free_work_index]; } static int workqueue_init(void) { k_work_queue_init(&zep_wifi_bh_q); k_work_queue_start(&zep_wifi_bh_q, bh_wq_stack_area, K_THREAD_STACK_SIZEOF(bh_wq_stack_area), CONFIG_NRF70_BH_WQ_PRIORITY, NULL); k_thread_name_set(&zep_wifi_bh_q.thread, "nrf70_bh_wq"); k_work_queue_init(&zep_wifi_intr_q); k_work_queue_start(&zep_wifi_intr_q, irq_wq_stack_area, K_THREAD_STACK_SIZEOF(irq_wq_stack_area), CONFIG_NRF70_IRQ_WQ_PRIORITY, NULL); k_thread_name_set(&zep_wifi_intr_q.thread, "nrf70_intr_wq"); #ifdef CONFIG_NRF70_TX_DONE_WQ_ENABLED k_work_queue_init(&zep_wifi_tx_done_q); k_work_queue_start(&zep_wifi_tx_done_q, tx_done_wq_stack_area, K_THREAD_STACK_SIZEOF(tx_done_wq_stack_area), CONFIG_NRF70_TX_DONE_WQ_PRIORITY, NULL); k_thread_name_set(&zep_wifi_tx_done_q.thread, "nrf70_tx_done_wq"); #endif /* CONFIG_NRF70_TX_DONE_WQ_ENABLED */ #ifdef CONFIG_NRF70_RX_WQ_ENABLED k_work_queue_init(&zep_wifi_rx_q); k_work_queue_start(&zep_wifi_rx_q, rx_wq_stack_area, K_THREAD_STACK_SIZEOF(rx_wq_stack_area), CONFIG_NRF70_RX_WQ_PRIORITY, NULL); k_thread_name_set(&zep_wifi_rx_q.thread, "nrf70_rx_wq"); #endif /* CONFIG_NRF70_RX_WQ_ENABLED */ return 0; } void work_init(struct zep_work_item *item, void (*callback)(unsigned long), unsigned long data) { item->callback = callback; item->data = data; k_work_init(&item->work, workqueue_callback); } void work_schedule(struct zep_work_item *item) { if (item->type == ZEP_WORK_TYPE_IRQ) k_work_submit_to_queue(&zep_wifi_intr_q, &item->work); else if (item->type == ZEP_WORK_TYPE_BH) k_work_submit_to_queue(&zep_wifi_bh_q, &item->work); #ifdef CONFIG_NRF70_TX_DONE_WQ_ENABLED else if (item->type == ZEP_WORK_TYPE_TX_DONE) k_work_submit_to_queue(&zep_wifi_tx_done_q, &item->work); #endif /* CONFIG_NRF70_TX_DONE_WQ_ENABLED */ #ifdef CONFIG_NRF70_RX_WQ_ENABLED else if (item->type == ZEP_WORK_TYPE_RX) k_work_submit_to_queue(&zep_wifi_rx_q, &item->work); #endif /* CONFIG_NRF70_RX_WQ_ENABLED */ } void work_kill(struct zep_work_item *item) { /* TODO: Based on context, use _sync version */ k_work_cancel(&item->work); } void work_free(struct zep_work_item *item) { item->in_use = 0; } SYS_INIT(workqueue_init, POST_KERNEL, 0); ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/work.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,131
```c /* * */ #define DT_DRV_COMPAT espressif_esp_at #undef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 200809L #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(wifi_esp_at, CONFIG_WIFI_LOG_LEVEL); #include <zephyr/kernel.h> #include <ctype.h> #include <errno.h> #include <zephyr/device.h> #include <zephyr/init.h> #include <stdlib.h> #include <string.h> #include <zephyr/drivers/gpio.h> #include <zephyr/drivers/uart.h> #include <zephyr/net/dns_resolve.h> #include <zephyr/net/net_if.h> #include <zephyr/net/net_ip.h> #include <zephyr/net/net_offload.h> #include <zephyr/net/wifi_mgmt.h> #include <zephyr/net/conn_mgr/connectivity_wifi_mgmt.h> #include "esp.h" struct esp_config { #if DT_INST_NODE_HAS_PROP(0, power_gpios) const struct gpio_dt_spec power; #endif #if DT_INST_NODE_HAS_PROP(0, reset_gpios) const struct gpio_dt_spec reset; #endif }; NET_BUF_POOL_DEFINE(mdm_recv_pool, MDM_RECV_MAX_BUF, MDM_RECV_BUF_SIZE, 0, NULL); /* RX thread structures */ K_KERNEL_STACK_DEFINE(esp_rx_stack, CONFIG_WIFI_ESP_AT_RX_STACK_SIZE); struct k_thread esp_rx_thread; /* RX thread work queue */ K_KERNEL_STACK_DEFINE(esp_workq_stack, CONFIG_WIFI_ESP_AT_WORKQ_STACK_SIZE); static const struct esp_config esp_driver_config = { #if DT_INST_NODE_HAS_PROP(0, power_gpios) .power = GPIO_DT_SPEC_INST_GET(0, power_gpios), #endif #if DT_INST_NODE_HAS_PROP(0, reset_gpios) .reset = GPIO_DT_SPEC_INST_GET(0, reset_gpios), #endif }; struct esp_data esp_driver_data; static void esp_configure_hostname(struct esp_data *data) { #if defined(CONFIG_NET_HOSTNAME_ENABLE) char cmd[sizeof("AT+CWHOSTNAME=\"\"") + NET_HOSTNAME_MAX_LEN]; snprintk(cmd, sizeof(cmd), "AT+CWHOSTNAME=\"%s\"", net_hostname_get()); cmd[sizeof(cmd) - 1] = '\0'; esp_cmd_send(data, NULL, 0, cmd, ESP_CMD_TIMEOUT); #else ARG_UNUSED(data); #endif } static inline uint8_t esp_mode_from_flags(struct esp_data *data) { uint8_t flags = data->flags; uint8_t mode = 0; if (flags & (EDF_STA_CONNECTED | EDF_STA_LOCK)) { mode |= ESP_MODE_STA; } if (flags & EDF_AP_ENABLED) { mode |= ESP_MODE_AP; } /* * ESP AT 1.7 does not allow to disable radio, so enter STA mode * instead. */ if (IS_ENABLED(CONFIG_WIFI_ESP_AT_VERSION_1_7) && mode == ESP_MODE_NONE) { mode = ESP_MODE_STA; } return mode; } static int esp_mode_switch(struct esp_data *data, uint8_t mode) { char cmd[] = "AT+"_CWMODE"=X"; int err; cmd[sizeof(cmd) - 2] = ('0' + mode); LOG_DBG("Switch to mode %hhu", mode); err = esp_cmd_send(data, NULL, 0, cmd, ESP_CMD_TIMEOUT); if (err) { LOG_WRN("Failed to switch to mode %d: %d", (int) mode, err); } return err; } static int esp_mode_switch_if_needed(struct esp_data *data) { uint8_t new_mode = esp_mode_from_flags(data); uint8_t old_mode = data->mode; int err; if (old_mode == new_mode) { return 0; } data->mode = new_mode; err = esp_mode_switch(data, new_mode); if (err) { return err; } if (!(old_mode & ESP_MODE_STA) && (new_mode & ESP_MODE_STA)) { /* * Hostname change is applied only when STA is enabled. */ esp_configure_hostname(data); } return 0; } static void esp_mode_switch_submit_if_needed(struct esp_data *data) { if (data->mode != esp_mode_from_flags(data)) { k_work_submit_to_queue(&data->workq, &data->mode_switch_work); } } static void esp_mode_switch_work(struct k_work *work) { struct esp_data *data = CONTAINER_OF(work, struct esp_data, mode_switch_work); (void)esp_mode_switch_if_needed(data); } static inline int esp_mode_flags_set(struct esp_data *data, uint8_t flags) { esp_flags_set(data, flags); return esp_mode_switch_if_needed(data); } static inline int esp_mode_flags_clear(struct esp_data *data, uint8_t flags) { esp_flags_clear(data, flags); return esp_mode_switch_if_needed(data); } /* * Modem Response Command Handlers */ /* Handler: OK */ MODEM_CMD_DEFINE(on_cmd_ok) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); modem_cmd_handler_set_error(data, 0); k_sem_give(&dev->sem_response); return 0; } /* Handler: ERROR */ MODEM_CMD_DEFINE(on_cmd_error) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); modem_cmd_handler_set_error(data, -EIO); k_sem_give(&dev->sem_response); return 0; } /* RX thread */ static void esp_rx(void *p1, void *p2, void *p3) { ARG_UNUSED(p2); ARG_UNUSED(p3); struct esp_data *data = p1; while (true) { /* wait for incoming data */ modem_iface_uart_rx_wait(&data->mctx.iface, K_FOREVER); modem_cmd_handler_process(&data->mctx.cmd_handler, &data->mctx.iface); /* give up time if we have a solid stream of data */ k_yield(); } } static char *str_unquote(char *str) { char *end; if (str[0] != '"') { return str; } str++; end = strrchr(str, '"'); if (end != NULL) { *end = 0; } return str; } /* +CIPSTAMAC:"xx:xx:xx:xx:xx:xx" */ MODEM_CMD_DEFINE(on_cmd_cipstamac) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); char *mac; int err; mac = str_unquote(argv[0]); err = net_bytes_from_str(dev->mac_addr, sizeof(dev->mac_addr), mac); if (err) { LOG_ERR("Failed to parse MAC address"); } return 0; } static int esp_pull_quoted(char **str, char *str_end, char **unquoted) { if (**str != '"') { return -EAGAIN; } (*str)++; *unquoted = *str; while (*str < str_end) { if (**str == '"') { **str = '\0'; (*str)++; if (**str == ',') { (*str)++; } return 0; } (*str)++; } return -EAGAIN; } static int esp_pull(char **str, char *str_end) { while (*str < str_end) { if (**str == ',' || **str == ':' || **str == '\r' || **str == '\n') { char last_c = **str; **str = '\0'; if (last_c == ',' || last_c == ':') { (*str)++; } return 0; } (*str)++; } return -EAGAIN; } static int esp_pull_raw(char **str, char *str_end, char **raw) { *raw = *str; return esp_pull(str, str_end); } static int esp_pull_long(char **str, char *str_end, long *value) { char *str_begin = *str; int err; char *endptr; err = esp_pull(str, str_end); if (err) { return err; } *value = strtol(str_begin, &endptr, 10); if (endptr == str_begin) { LOG_ERR("endptr == str_begin"); return -EBADMSG; } return 0; } /* +CWLAP:(sec,ssid,rssi,channel) */ /* with: CONFIG_WIFI_ESP_AT_SCAN_MAC_ADDRESS: +CWLAP:<ecn>,<ssid>,<rssi>,<mac>,<ch>*/ MODEM_CMD_DIRECT_DEFINE(on_cmd_cwlap) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); struct wifi_scan_result res = { 0 }; char cwlap_buf[sizeof("\"0\",\"\",-100,\"xx:xx:xx:xx:xx:xx\",12") + WIFI_SSID_MAX_LEN * 2 + 1]; char *ecn; char *ssid; char *mac; char *channel; long rssi; long ecn_id; int err; len = net_buf_linearize(cwlap_buf, sizeof(cwlap_buf) - 1, data->rx_buf, 0, sizeof(cwlap_buf) - 1); cwlap_buf[len] = '\0'; char *str = &cwlap_buf[sizeof("+CWJAP:(") - 1]; char *str_end = cwlap_buf + len; err = esp_pull_raw(&str, str_end, &ecn); if (err) { return err; } ecn_id = strtol(ecn, NULL, 10); if (ecn_id == 0) { res.security = WIFI_SECURITY_TYPE_NONE; } else { res.security = WIFI_SECURITY_TYPE_PSK; } err = esp_pull_quoted(&str, str_end, &ssid); if (err) { return err; } err = esp_pull_long(&str, str_end, &rssi); if (err) { return err; } if (strlen(ssid) > WIFI_SSID_MAX_LEN) { return -EBADMSG; } res.ssid_length = MIN(sizeof(res.ssid), strlen(ssid)); memcpy(res.ssid, ssid, res.ssid_length); res.rssi = rssi; if (IS_ENABLED(CONFIG_WIFI_ESP_AT_SCAN_MAC_ADDRESS)) { err = esp_pull_quoted(&str, str_end, &mac); if (err) { return err; } res.mac_length = WIFI_MAC_ADDR_LEN; if (net_bytes_from_str(res.mac, sizeof(res.mac), mac) < 0) { LOG_ERR("Invalid MAC address"); res.mac_length = 0; } } err = esp_pull_raw(&str, str_end, &channel); if (err) { return err; } res.channel = strtol(channel, NULL, 10); if (dev->scan_cb) { dev->scan_cb(dev->net_iface, 0, &res); } return str - cwlap_buf; } /* +CWJAP:(ssid,bssid,channel,rssi) */ MODEM_CMD_DIRECT_DEFINE(on_cmd_cwjap) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); struct wifi_iface_status *status = dev->wifi_status; char cwjap_buf[sizeof("\"\",\"xx:xx:xx:xx:xx:xx\",12,-100") + WIFI_SSID_MAX_LEN * 2 + 1]; uint8_t flags = dev->flags; char *ssid; char *bssid; char *channel; char *rssi; int err; len = net_buf_linearize(cwjap_buf, sizeof(cwjap_buf) - 1, data->rx_buf, 0, sizeof(cwjap_buf) - 1); cwjap_buf[len] = '\0'; char *str = &cwjap_buf[sizeof("+CWJAP:") - 1]; char *str_end = cwjap_buf + len; status->band = WIFI_FREQ_BAND_2_4_GHZ; status->iface_mode = WIFI_MODE_INFRA; if (flags & EDF_STA_CONNECTED) { status->state = WIFI_STATE_COMPLETED; } else if (flags & EDF_STA_CONNECTING) { status->state = WIFI_STATE_SCANNING; } else { status->state = WIFI_STATE_DISCONNECTED; } err = esp_pull_quoted(&str, str_end, &ssid); if (err) { return err; } err = esp_pull_quoted(&str, str_end, &bssid); if (err) { return err; } err = esp_pull_raw(&str, str_end, &channel); if (err) { return err; } err = esp_pull_raw(&str, str_end, &rssi); if (err) { return err; } strncpy(status->ssid, ssid, sizeof(status->ssid)); status->ssid_len = strnlen(status->ssid, sizeof(status->ssid)); err = net_bytes_from_str(status->bssid, sizeof(status->bssid), bssid); if (err) { LOG_WRN("Invalid MAC address"); memset(status->bssid, 0x0, sizeof(status->bssid)); } status->channel = strtol(channel, NULL, 10); status->rssi = strtol(rssi, NULL, 10); return str - cwjap_buf; } static void esp_dns_work(struct k_work *work) { #if defined(ESP_MAX_DNS) struct esp_data *data = CONTAINER_OF(work, struct esp_data, dns_work); struct dns_resolve_context *dnsctx; struct sockaddr_in *addrs = data->dns_addresses; const struct sockaddr *dns_servers[ESP_MAX_DNS + 1] = {}; size_t i; int err; for (i = 0; i < ESP_MAX_DNS; i++) { if (!addrs[i].sin_addr.s_addr) { break; } dns_servers[i] = (struct sockaddr *) &addrs[i]; } dnsctx = dns_resolve_get_default(); err = dns_resolve_reconfigure(dnsctx, NULL, dns_servers); if (err) { LOG_ERR("Could not set DNS servers: %d", err); } LOG_DBG("DNS resolver reconfigured"); #endif } /* +CIPDNS:enable[,"DNS IP1"[,"DNS IP2"[,"DNS IP3"]]] */ MODEM_CMD_DEFINE(on_cmd_cipdns) { #if defined(ESP_MAX_DNS) struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); struct sockaddr_in *addrs = dev->dns_addresses; char **servers = (char **)argv + 1; size_t num_servers = argc - 1; size_t valid_servers = 0; size_t i; int err; for (i = 0; i < ESP_MAX_DNS; i++) { if (i >= num_servers) { addrs[i].sin_addr.s_addr = 0; break; } servers[i] = str_unquote(servers[i]); LOG_DBG("DNS[%zu]: %s", i, servers[i]); err = net_addr_pton(AF_INET, servers[i], &addrs[i].sin_addr); if (err) { LOG_ERR("Invalid DNS address: %s", servers[i]); addrs[i].sin_addr.s_addr = 0; break; } addrs[i].sin_family = AF_INET; addrs[i].sin_port = htons(53); valid_servers++; } if (valid_servers) { k_work_submit(&dev->dns_work); } #endif return 0; } static const struct modem_cmd response_cmds[] = { MODEM_CMD("OK", on_cmd_ok, 0U, ""), /* 3GPP */ MODEM_CMD("ERROR", on_cmd_error, 0U, ""), /* 3GPP */ }; MODEM_CMD_DEFINE(on_cmd_wifi_connected) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); if (esp_flags_are_set(dev, EDF_STA_CONNECTED)) { return 0; } esp_flags_set(dev, EDF_STA_CONNECTED); wifi_mgmt_raise_connect_result_event(dev->net_iface, 0); net_if_dormant_off(dev->net_iface); return 0; } static void esp_mgmt_disconnect_work(struct k_work *work) { struct esp_socket *sock; struct esp_data *dev; dev = CONTAINER_OF(work, struct esp_data, disconnect_work); /* Cleanup any sockets that weren't closed */ for (int i = 0; i < ARRAY_SIZE(dev->sockets); i++) { sock = &dev->sockets[i]; if (esp_socket_connected(sock)) { LOG_WRN("Socket %d left open, manually closing", i); esp_socket_close(sock); } } esp_flags_clear(dev, EDF_STA_CONNECTED); esp_mode_switch_submit_if_needed(dev); #if defined(CONFIG_NET_NATIVE_IPV4) net_if_ipv4_addr_rm(dev->net_iface, &dev->ip); #endif if (!esp_flags_are_set(dev, EDF_AP_ENABLED)) { net_if_dormant_on(dev->net_iface); } wifi_mgmt_raise_disconnect_result_event(dev->net_iface, 0); } MODEM_CMD_DEFINE(on_cmd_wifi_disconnected) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); if (esp_flags_are_set(dev, EDF_STA_CONNECTED)) { k_work_submit_to_queue(&dev->workq, &dev->disconnect_work); } return 0; } /* * +CIPSTA:ip:"<ip>" * +CIPSTA:gateway:"<ip>" * +CIPSTA:netmask:"<ip>" */ MODEM_CMD_DEFINE(on_cmd_cipsta) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); char *ip; ip = str_unquote(argv[1]); if (!strcmp(argv[0], "ip")) { net_addr_pton(AF_INET, ip, &dev->ip); } else if (!strcmp(argv[0], "gateway")) { net_addr_pton(AF_INET, ip, &dev->gw); } else if (!strcmp(argv[0], "netmask")) { net_addr_pton(AF_INET, ip, &dev->nm); } else { LOG_WRN("Unknown IP type %s", argv[0]); } return 0; } static void esp_ip_addr_work(struct k_work *work) { struct k_work_delayable *dwork = k_work_delayable_from_work(work); struct esp_data *dev = CONTAINER_OF(dwork, struct esp_data, ip_addr_work); int ret; static const struct modem_cmd cmds[] = { MODEM_CMD("+"_CIPSTA":", on_cmd_cipsta, 2U, ":"), }; static const struct modem_cmd dns_cmds[] = { MODEM_CMD_ARGS_MAX("+CIPDNS:", on_cmd_cipdns, 1U, 3U, ","), }; ret = esp_cmd_send(dev, cmds, ARRAY_SIZE(cmds), "AT+"_CIPSTA"?", ESP_CMD_TIMEOUT); if (ret < 0) { LOG_WRN("Failed to query IP settings: ret %d", ret); k_work_reschedule_for_queue(&dev->workq, &dev->ip_addr_work, K_SECONDS(5)); return; } #if defined(CONFIG_NET_NATIVE_IPV4) /* update interface addresses */ #if defined(CONFIG_WIFI_ESP_AT_IP_STATIC) net_if_ipv4_addr_add(dev->net_iface, &dev->ip, NET_ADDR_MANUAL, 0); #else net_if_ipv4_addr_add(dev->net_iface, &dev->ip, NET_ADDR_DHCP, 0); #endif net_if_ipv4_set_gw(dev->net_iface, &dev->gw); net_if_ipv4_set_netmask_by_addr(dev->net_iface, &dev->ip, &dev->nm); #endif if (IS_ENABLED(CONFIG_WIFI_ESP_AT_DNS_USE)) { ret = esp_cmd_send(dev, dns_cmds, ARRAY_SIZE(dns_cmds), "AT+CIPDNS?", ESP_CMD_TIMEOUT); if (ret) { LOG_WRN("DNS fetch failed: %d", ret); } } } MODEM_CMD_DEFINE(on_cmd_got_ip) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); k_work_reschedule_for_queue(&dev->workq, &dev->ip_addr_work, K_SECONDS(1)); return 0; } MODEM_CMD_DEFINE(on_cmd_connect) { struct esp_socket *sock; struct esp_data *dev; uint8_t link_id; link_id = data->match_buf[0] - '0'; dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); sock = esp_socket_ref_from_link_id(dev, link_id); if (!sock) { LOG_ERR("No socket for link %d", link_id); return 0; } esp_socket_unref(sock); return 0; } MODEM_CMD_DEFINE(on_cmd_closed) { struct esp_socket *sock; struct esp_data *dev; uint8_t link_id; atomic_val_t old_flags; link_id = data->match_buf[0] - '0'; LOG_DBG("Link %d closed", link_id); dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); sock = esp_socket_ref_from_link_id(dev, link_id); if (!sock) { LOG_ERR("No socket for link %d", link_id); return 0; } old_flags = esp_socket_flags_clear_and_set(sock, ESP_SOCK_CONNECTED, ESP_SOCK_CLOSE_PENDING); if (!(old_flags & ESP_SOCK_CONNECTED)) { LOG_DBG("Link %d already closed", link_id); goto socket_unref; } if (!(old_flags & ESP_SOCK_CLOSE_PENDING)) { esp_socket_work_submit(sock, &sock->close_work); } socket_unref: esp_socket_unref(sock); return 0; } /* * Passive mode: "+IPD,<id>,<len>\r\n" * Other: "+IPD,<id>,<len>:<data>" */ #define MIN_IPD_LEN (sizeof("+IPD,I,0E") - 1) #define MAX_IPD_LEN (sizeof("+IPD,I,4294967295,\"\",65535E") - 1) + NET_IPV4_ADDR_LEN static int cmd_ipd_parse_hdr(struct esp_data *dev, struct esp_socket **sock, struct net_buf *buf, uint16_t len, int *data_offset, long *data_len) { char ipd_buf[MAX_IPD_LEN + 1]; char *str; char *str_end; long link_id; size_t frags_len; size_t match_len; int err; frags_len = net_buf_frags_len(buf); /* Wait until minimum cmd length is available */ if (frags_len < MIN_IPD_LEN) { return -EAGAIN; } match_len = net_buf_linearize(ipd_buf, MAX_IPD_LEN, buf, 0, MAX_IPD_LEN); ipd_buf[match_len] = 0; if (ipd_buf[len] != ',' || ipd_buf[len + 2] != ',') { LOG_ERR("Invalid IPD: %s", ipd_buf); return -EBADMSG; } str = &ipd_buf[len + 1]; str_end = &ipd_buf[match_len]; err = esp_pull_long(&str, str_end, &link_id); if (err) { if (err == -EAGAIN && match_len >= MAX_IPD_LEN) { LOG_ERR("Failed to pull %s", "link_id"); return -EBADMSG; } return err; } err = esp_pull_long(&str, str_end, data_len); if (err) { if (err == -EAGAIN && match_len >= MAX_IPD_LEN) { LOG_ERR("Failed to pull %s", "data_len"); return -EBADMSG; } return err; } *sock = esp_socket_ref_from_link_id(dev, link_id); if (!sock) { LOG_ERR("No socket for link %ld", link_id); return str - ipd_buf; } if (!ESP_PROTO_PASSIVE(esp_socket_ip_proto(*sock)) && IS_ENABLED(CONFIG_WIFI_ESP_AT_CIPDINFO_USE)) { struct sockaddr_in *recv_addr = (struct sockaddr_in *) &(*sock)->context->remote; char *remote_ip; long port; err = esp_pull_quoted(&str, str_end, &remote_ip); if (err) { LOG_ERR("Failed to pull remote_ip"); goto socket_unref; } err = esp_pull_long(&str, str_end, &port); if (err) { LOG_ERR("Failed to pull port"); goto socket_unref; } err = net_addr_pton(AF_INET, remote_ip, &recv_addr->sin_addr); if (err) { LOG_ERR("Invalid IP address"); err = -EBADMSG; goto socket_unref; } recv_addr->sin_family = AF_INET; recv_addr->sin_port = htons(port); } *data_offset = (str - ipd_buf); return 0; socket_unref: esp_socket_unref(*sock); return err; } MODEM_CMD_DIRECT_DEFINE(on_cmd_ipd) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); struct esp_socket *sock; int data_offset; long data_len; int err; int ret; err = cmd_ipd_parse_hdr(dev, &sock, data->rx_buf, len, &data_offset, &data_len); if (err) { if (err == -EAGAIN) { return -EAGAIN; } return len; } /* * When using passive TCP, the data itself is not included in the +IPD * command but must be polled with AT+CIPRECVDATA. */ if (ESP_PROTO_PASSIVE(esp_socket_ip_proto(sock))) { esp_socket_work_submit(sock, &sock->recvdata_work); ret = data_offset; goto socket_unref; } /* Do we have the whole message? */ if (data_offset + data_len > net_buf_frags_len(data->rx_buf)) { ret = -EAGAIN; goto socket_unref; } esp_socket_rx(sock, data->rx_buf, data_offset, data_len); ret = data_offset + data_len; socket_unref: esp_socket_unref(sock); return ret; } MODEM_CMD_DEFINE(on_cmd_busy_sending) { LOG_WRN("Busy sending"); return 0; } MODEM_CMD_DEFINE(on_cmd_busy_processing) { LOG_WRN("Busy processing"); return 0; } /* * The 'ready' command is sent when device has booted and is ready to receive * commands. It is only expected after a reset of the device. */ MODEM_CMD_DEFINE(on_cmd_ready) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); k_sem_give(&dev->sem_if_ready); if (net_if_is_carrier_ok(dev->net_iface)) { net_if_dormant_on(dev->net_iface); net_if_carrier_off(dev->net_iface); LOG_ERR("Unexpected reset"); } if (esp_flags_are_set(dev, EDF_STA_CONNECTING)) { wifi_mgmt_raise_connect_result_event(dev->net_iface, -1); } else if (esp_flags_are_set(dev, EDF_STA_CONNECTED)) { wifi_mgmt_raise_disconnect_result_event(dev->net_iface, 0); } dev->flags = 0; dev->mode = 0; #if defined(CONFIG_NET_NATIVE_IPV4) net_if_ipv4_addr_rm(dev->net_iface, &dev->ip); #endif k_work_submit_to_queue(&dev->workq, &dev->init_work); return 0; } #if defined(CONFIG_WIFI_ESP_AT_FETCH_VERSION) static int cmd_version_log(struct modem_cmd_handler_data *data, const char *type, const char *version) { LOG_INF("%s: %s", type, version); return 0; } MODEM_CMD_DEFINE(on_cmd_at_version) { return cmd_version_log(data, "AT version", argv[0]); } MODEM_CMD_DEFINE(on_cmd_sdk_version) { return cmd_version_log(data, "SDK version", argv[0]); } MODEM_CMD_DEFINE(on_cmd_compile_time) { return cmd_version_log(data, "compile time", argv[0]); } MODEM_CMD_DEFINE(on_cmd_bin_version) { return cmd_version_log(data, "Bin version", argv[0]); } #endif /* CONFIG_WIFI_ESP_AT_FETCH_VERSION */ static const struct modem_cmd unsol_cmds[] = { MODEM_CMD("WIFI CONNECTED", on_cmd_wifi_connected, 0U, ""), MODEM_CMD("WIFI DISCONNECT", on_cmd_wifi_disconnected, 0U, ""), MODEM_CMD("WIFI GOT IP", on_cmd_got_ip, 0U, ""), MODEM_CMD("0,CONNECT", on_cmd_connect, 0U, ""), MODEM_CMD("1,CONNECT", on_cmd_connect, 0U, ""), MODEM_CMD("2,CONNECT", on_cmd_connect, 0U, ""), MODEM_CMD("3,CONNECT", on_cmd_connect, 0U, ""), MODEM_CMD("4,CONNECT", on_cmd_connect, 0U, ""), MODEM_CMD("0,CLOSED", on_cmd_closed, 0U, ""), MODEM_CMD("1,CLOSED", on_cmd_closed, 0U, ""), MODEM_CMD("2,CLOSED", on_cmd_closed, 0U, ""), MODEM_CMD("3,CLOSED", on_cmd_closed, 0U, ""), MODEM_CMD("4,CLOSED", on_cmd_closed, 0U, ""), MODEM_CMD("busy s...", on_cmd_busy_sending, 0U, ""), MODEM_CMD("busy p...", on_cmd_busy_processing, 0U, ""), MODEM_CMD("ready", on_cmd_ready, 0U, ""), #if defined(CONFIG_WIFI_ESP_AT_FETCH_VERSION) MODEM_CMD("AT version:", on_cmd_at_version, 1U, ""), MODEM_CMD("SDK version:", on_cmd_sdk_version, 1U, ""), MODEM_CMD("Compile time", on_cmd_compile_time, 1U, ""), MODEM_CMD("Bin version:", on_cmd_bin_version, 1U, ""), #endif MODEM_CMD_DIRECT("+IPD", on_cmd_ipd), }; static void esp_mgmt_iface_status_work(struct k_work *work) { struct esp_data *data = CONTAINER_OF(work, struct esp_data, iface_status_work); struct wifi_iface_status *status = data->wifi_status; int ret; static const struct modem_cmd cmds[] = { MODEM_CMD_DIRECT("+CWJAP:", on_cmd_cwjap), }; ret = esp_cmd_send(data, cmds, ARRAY_SIZE(cmds), "AT+CWJAP?", ESP_IFACE_STATUS_TIMEOUT); if (ret < 0) { LOG_WRN("Failed to request STA status: ret %d", ret); status->state = WIFI_STATE_UNKNOWN; } k_sem_give(&data->wifi_status_sem); } static int esp_mgmt_iface_status(const struct device *dev, struct wifi_iface_status *status) { struct esp_data *data = dev->data; memset(status, 0x0, sizeof(*status)); status->state = WIFI_STATE_UNKNOWN; status->band = WIFI_FREQ_BAND_UNKNOWN; status->iface_mode = WIFI_MODE_UNKNOWN; status->link_mode = WIFI_LINK_MODE_UNKNOWN; status->security = WIFI_SECURITY_TYPE_UNKNOWN; status->mfp = WIFI_MFP_UNKNOWN; if (!net_if_is_carrier_ok(data->net_iface)) { status->state = WIFI_STATE_INTERFACE_DISABLED; return 0; } data->wifi_status = status; k_sem_init(&data->wifi_status_sem, 0, 1); k_work_submit_to_queue(&data->workq, &data->iface_status_work); k_sem_take(&data->wifi_status_sem, K_FOREVER); return 0; } static void esp_mgmt_scan_work(struct k_work *work) { struct esp_data *dev; int ret; static const struct modem_cmd cmds[] = { MODEM_CMD_DIRECT("+CWLAP:", on_cmd_cwlap), }; dev = CONTAINER_OF(work, struct esp_data, scan_work); ret = esp_mode_flags_set(dev, EDF_STA_LOCK); if (ret < 0) { goto out; } ret = esp_cmd_send(dev, cmds, ARRAY_SIZE(cmds), ESP_CMD_CWLAP, ESP_SCAN_TIMEOUT); esp_mode_flags_clear(dev, EDF_STA_LOCK); LOG_DBG("ESP Wi-Fi scan: cmd = %s", ESP_CMD_CWLAP); if (ret < 0) { LOG_ERR("Failed to scan: ret %d", ret); } out: dev->scan_cb(dev->net_iface, 0, NULL); dev->scan_cb = NULL; } static int esp_mgmt_scan(const struct device *dev, struct wifi_scan_params *params, scan_result_cb_t cb) { struct esp_data *data = dev->data; ARG_UNUSED(params); if (data->scan_cb != NULL) { return -EINPROGRESS; } if (!net_if_is_carrier_ok(data->net_iface)) { return -EIO; } data->scan_cb = cb; k_work_submit_to_queue(&data->workq, &data->scan_work); return 0; }; MODEM_CMD_DEFINE(on_cmd_fail) { struct esp_data *dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data); modem_cmd_handler_set_error(data, -EIO); k_sem_give(&dev->sem_response); return 0; } static void esp_mgmt_connect_work(struct k_work *work) { struct esp_data *dev; int ret; static const struct modem_cmd cmds[] = { MODEM_CMD("FAIL", on_cmd_fail, 0U, ""), }; dev = CONTAINER_OF(work, struct esp_data, connect_work); ret = esp_mode_flags_set(dev, EDF_STA_LOCK); if (ret < 0) { goto out; } ret = esp_cmd_send(dev, cmds, ARRAY_SIZE(cmds), dev->conn_cmd, ESP_CONNECT_TIMEOUT); memset(dev->conn_cmd, 0, sizeof(dev->conn_cmd)); if (ret < 0) { net_if_dormant_on(dev->net_iface); if (esp_flags_are_set(dev, EDF_STA_CONNECTED)) { esp_flags_clear(dev, EDF_STA_CONNECTED); wifi_mgmt_raise_disconnect_result_event(dev->net_iface, 0); } else { wifi_mgmt_raise_connect_result_event(dev->net_iface, ret); } } else if (!esp_flags_are_set(dev, EDF_STA_CONNECTED)) { esp_flags_set(dev, EDF_STA_CONNECTED); wifi_mgmt_raise_connect_result_event(dev->net_iface, 0); net_if_dormant_off(dev->net_iface); } esp_mode_flags_clear(dev, EDF_STA_LOCK); out: esp_flags_clear(dev, EDF_STA_CONNECTING); } static int esp_conn_cmd_append(struct esp_data *data, size_t *off, const char *chunk, size_t chunk_len) { char *str_end = &data->conn_cmd[sizeof(data->conn_cmd)]; char *str = &data->conn_cmd[*off]; const char *chunk_end = chunk + chunk_len; for (; chunk < chunk_end; chunk++) { if (str_end - str < 1) { return -ENOSPC; } *str = *chunk; str++; } *off = str - data->conn_cmd; return 0; } #define esp_conn_cmd_append_literal(data, off, chunk) \ esp_conn_cmd_append(data, off, chunk, sizeof(chunk) - 1) static int esp_conn_cmd_escape_and_append(struct esp_data *data, size_t *off, const char *chunk, size_t chunk_len) { char *str_end = &data->conn_cmd[sizeof(data->conn_cmd)]; char *str = &data->conn_cmd[*off]; const char *chunk_end = chunk + chunk_len; for (; chunk < chunk_end; chunk++) { switch (*chunk) { case ',': case '\\': case '"': if (str_end - str < 2) { return -ENOSPC; } *str = '\\'; str++; break; } if (str_end - str < 1) { return -ENOSPC; } *str = *chunk; str++; } *off = str - data->conn_cmd; return 0; } static int esp_mgmt_connect(const struct device *dev, struct wifi_connect_req_params *params) { struct esp_data *data = dev->data; size_t off = 0; int err; if (!net_if_is_carrier_ok(data->net_iface) || !net_if_is_admin_up(data->net_iface)) { return -EIO; } if (esp_flags_are_set(data, EDF_STA_CONNECTED | EDF_STA_CONNECTING)) { return -EALREADY; } esp_flags_set(data, EDF_STA_CONNECTING); err = esp_conn_cmd_append_literal(data, &off, "AT+"_CWJAP"=\""); if (err) { return err; } err = esp_conn_cmd_escape_and_append(data, &off, params->ssid, params->ssid_length); if (err) { return err; } err = esp_conn_cmd_append_literal(data, &off, "\",\""); if (err) { return err; } if (params->security == WIFI_SECURITY_TYPE_PSK) { err = esp_conn_cmd_escape_and_append(data, &off, params->psk, params->psk_length); if (err) { return err; } } err = esp_conn_cmd_append_literal(data, &off, "\""); if (err) { return err; } k_work_submit_to_queue(&data->workq, &data->connect_work); return 0; } static int esp_mgmt_disconnect(const struct device *dev) { struct esp_data *data = dev->data; int ret; ret = esp_cmd_send(data, NULL, 0, "AT+CWQAP", ESP_CMD_TIMEOUT); return ret; } static int esp_mgmt_ap_enable(const struct device *dev, struct wifi_connect_req_params *params) { char cmd[sizeof("AT+"_CWSAP"=\"\",\"\",xx,x") + WIFI_SSID_MAX_LEN + WIFI_PSK_MAX_LEN]; struct esp_data *data = dev->data; int ecn = 0, len, ret; ret = esp_mode_flags_set(data, EDF_AP_ENABLED); if (ret < 0) { LOG_ERR("Failed to enable AP mode, ret %d", ret); return ret; } len = snprintk(cmd, sizeof(cmd), "AT+"_CWSAP"=\""); memcpy(&cmd[len], params->ssid, params->ssid_length); len += params->ssid_length; if (params->security == WIFI_SECURITY_TYPE_PSK) { len += snprintk(&cmd[len], sizeof(cmd) - len, "\",\""); memcpy(&cmd[len], params->psk, params->psk_length); len += params->psk_length; ecn = 3; } else { len += snprintk(&cmd[len], sizeof(cmd) - len, "\",\""); } snprintk(&cmd[len], sizeof(cmd) - len, "\",%d,%d", params->channel, ecn); ret = esp_cmd_send(data, NULL, 0, cmd, ESP_CMD_TIMEOUT); net_if_dormant_off(data->net_iface); return ret; } static int esp_mgmt_ap_disable(const struct device *dev) { struct esp_data *data = dev->data; if (!esp_flags_are_set(data, EDF_STA_CONNECTED)) { net_if_dormant_on(data->net_iface); } return esp_mode_flags_clear(data, EDF_AP_ENABLED); } static void esp_init_work(struct k_work *work) { struct esp_data *dev; int ret; static const struct setup_cmd setup_cmds[] = { SETUP_CMD_NOHANDLE("AT"), /* turn off echo */ SETUP_CMD_NOHANDLE("ATE0"), SETUP_CMD_NOHANDLE("AT+UART_CUR="_UART_CUR), #if DT_INST_NODE_HAS_PROP(0, target_speed) }; static const struct setup_cmd setup_cmds_target_baudrate[] = { SETUP_CMD_NOHANDLE("AT"), #endif #if defined(CONFIG_WIFI_ESP_AT_FETCH_VERSION) SETUP_CMD_NOHANDLE("AT+GMR"), #endif #if defined(CONFIG_WIFI_ESP_AT_VERSION_1_7) SETUP_CMD_NOHANDLE(ESP_CMD_CWMODE(STA)), #endif #if defined(CONFIG_WIFI_ESP_AT_IP_STATIC) /* enable Static IP Config */ SETUP_CMD_NOHANDLE(ESP_CMD_DHCP_ENABLE(STATION, 0)), SETUP_CMD_NOHANDLE(ESP_CMD_SET_IP(CONFIG_WIFI_ESP_AT_IP_ADDRESS, CONFIG_WIFI_ESP_AT_IP_GATEWAY, CONFIG_WIFI_ESP_AT_IP_MASK)), #else /* enable DHCP */ SETUP_CMD_NOHANDLE(ESP_CMD_DHCP_ENABLE(STATION, 1)), #endif /* enable multiple socket support */ SETUP_CMD_NOHANDLE("AT+CIPMUX=1"), SETUP_CMD_NOHANDLE( ESP_CMD_CWLAPOPT(ESP_CMD_CWLAPOPT_ORDERED, ESP_CMD_CWLAPOPT_MASK)), #if !defined(CONFIG_WIFI_ESP_AT_VERSION_1_7) SETUP_CMD_NOHANDLE(ESP_CMD_CWMODE(STA)), SETUP_CMD_NOHANDLE("AT+CWAUTOCONN=0"), SETUP_CMD_NOHANDLE(ESP_CMD_CWMODE(NONE)), #endif #if defined(CONFIG_WIFI_ESP_AT_PASSIVE_MODE) SETUP_CMD_NOHANDLE("AT+CIPRECVMODE=1"), #endif #if defined(CONFIG_WIFI_ESP_AT_CIPDINFO_USE) SETUP_CMD_NOHANDLE("AT+CIPDINFO=1"), #endif SETUP_CMD("AT+"_CIPSTAMAC"?", "+"_CIPSTAMAC":", on_cmd_cipstamac, 1U, ""), }; dev = CONTAINER_OF(work, struct esp_data, init_work); ret = modem_cmd_handler_setup_cmds(&dev->mctx.iface, &dev->mctx.cmd_handler, setup_cmds, ARRAY_SIZE(setup_cmds), &dev->sem_response, ESP_INIT_TIMEOUT); if (ret < 0) { LOG_ERR("Init failed %d", ret); return; } #if DT_INST_NODE_HAS_PROP(0, target_speed) static const struct uart_config uart_config = { .baudrate = DT_INST_PROP(0, target_speed), .parity = UART_CFG_PARITY_NONE, .stop_bits = UART_CFG_STOP_BITS_1, .data_bits = UART_CFG_DATA_BITS_8, .flow_ctrl = DT_PROP(ESP_BUS, hw_flow_control) ? UART_CFG_FLOW_CTRL_RTS_CTS : UART_CFG_FLOW_CTRL_NONE, }; ret = uart_configure(DEVICE_DT_GET(DT_INST_BUS(0)), &uart_config); if (ret < 0) { LOG_ERR("Baudrate change failed %d", ret); return; } /* arbitrary sleep period to give ESP enough time to reconfigure */ k_sleep(K_MSEC(100)); ret = modem_cmd_handler_setup_cmds(&dev->mctx.iface, &dev->mctx.cmd_handler, setup_cmds_target_baudrate, ARRAY_SIZE(setup_cmds_target_baudrate), &dev->sem_response, ESP_INIT_TIMEOUT); if (ret < 0) { LOG_ERR("Init failed %d", ret); return; } #endif net_if_set_link_addr(dev->net_iface, dev->mac_addr, sizeof(dev->mac_addr), NET_LINK_ETHERNET); if (IS_ENABLED(CONFIG_WIFI_ESP_AT_VERSION_1_7)) { /* This is the mode entered in above setup commands */ dev->mode = ESP_MODE_STA; /* * In case of ESP 1.7 this is the first time CWMODE is entered * STA mode, so request hostname change now. */ esp_configure_hostname(dev); } LOG_INF("ESP Wi-Fi ready"); /* L1 network layer (physical layer) is up */ net_if_carrier_on(dev->net_iface); k_sem_give(&dev->sem_if_up); } static int esp_reset(const struct device *dev) { struct esp_data *data = dev->data; int ret = -EAGAIN; if (net_if_is_carrier_ok(data->net_iface)) { net_if_carrier_off(data->net_iface); } #if DT_INST_NODE_HAS_PROP(0, power_gpios) const struct esp_config *config = dev->config; gpio_pin_set_dt(&config->power, 0); k_sleep(K_MSEC(100)); gpio_pin_set_dt(&config->power, 1); #elif DT_INST_NODE_HAS_PROP(0, reset_gpios) const struct esp_config *config = dev->config; gpio_pin_set_dt(&config->reset, 1); k_sleep(K_MSEC(100)); gpio_pin_set_dt(&config->reset, 0); #else #if DT_INST_NODE_HAS_PROP(0, external_reset) /* Wait to see if the interface comes up by itself */ ret = k_sem_take(&data->sem_if_ready, K_MSEC(CONFIG_WIFI_ESP_AT_RESET_TIMEOUT)); #endif int retries = 3; /* Don't need to run this if the interface came up by itself */ while ((ret != 0) && retries--) { ret = modem_cmd_send(&data->mctx.iface, &data->mctx.cmd_handler, NULL, 0, "AT+RST", &data->sem_if_ready, K_MSEC(CONFIG_WIFI_ESP_AT_RESET_TIMEOUT)); if (ret == 0 || ret != -ETIMEDOUT) { break; } } if (ret < 0) { LOG_ERR("Failed to reset device: %d", ret); return -EAGAIN; } #endif LOG_INF("Waiting for interface to come up"); ret = k_sem_take(&data->sem_if_up, ESP_INIT_TIMEOUT); if (ret == -EAGAIN) { LOG_ERR("Timeout waiting for interface"); } return ret; } static void esp_iface_init(struct net_if *iface) { esp_offload_init(iface); /* Not currently connected to a network */ net_if_dormant_on(iface); } static enum offloaded_net_if_types esp_offload_get_type(void) { return L2_OFFLOADED_NET_IF_TYPE_WIFI; } static const struct wifi_mgmt_ops esp_mgmt_ops = { .scan = esp_mgmt_scan, .connect = esp_mgmt_connect, .disconnect = esp_mgmt_disconnect, .ap_enable = esp_mgmt_ap_enable, .ap_disable = esp_mgmt_ap_disable, .iface_status = esp_mgmt_iface_status, }; static const struct net_wifi_mgmt_offload esp_api = { .wifi_iface.iface_api.init = esp_iface_init, .wifi_iface.get_type = esp_offload_get_type, .wifi_mgmt_api = &esp_mgmt_ops, }; static int esp_init(const struct device *dev); /* The network device must be instantiated above the init function in order * for the struct net_if that the macro declares to be visible inside the * function. An `extern` declaration does not work as the struct is static. */ NET_DEVICE_DT_INST_OFFLOAD_DEFINE(0, esp_init, NULL, &esp_driver_data, &esp_driver_config, CONFIG_WIFI_INIT_PRIORITY, &esp_api, ESP_MTU); CONNECTIVITY_WIFI_MGMT_BIND(Z_DEVICE_DT_DEV_ID(DT_DRV_INST(0))); static int esp_init(const struct device *dev) { #if DT_INST_NODE_HAS_PROP(0, power_gpios) || DT_INST_NODE_HAS_PROP(0, reset_gpios) const struct esp_config *config = dev->config; #endif struct esp_data *data = dev->data; int ret = 0; k_sem_init(&data->sem_tx_ready, 0, 1); k_sem_init(&data->sem_response, 0, 1); k_sem_init(&data->sem_if_ready, 0, 1); k_sem_init(&data->sem_if_up, 0, 1); k_work_init(&data->init_work, esp_init_work); k_work_init_delayable(&data->ip_addr_work, esp_ip_addr_work); k_work_init(&data->scan_work, esp_mgmt_scan_work); k_work_init(&data->connect_work, esp_mgmt_connect_work); k_work_init(&data->disconnect_work, esp_mgmt_disconnect_work); k_work_init(&data->iface_status_work, esp_mgmt_iface_status_work); k_work_init(&data->mode_switch_work, esp_mode_switch_work); if (IS_ENABLED(CONFIG_WIFI_ESP_AT_DNS_USE)) { k_work_init(&data->dns_work, esp_dns_work); } esp_socket_init(data); /* initialize the work queue */ k_work_queue_start(&data->workq, esp_workq_stack, K_KERNEL_STACK_SIZEOF(esp_workq_stack), K_PRIO_COOP(CONFIG_WIFI_ESP_AT_WORKQ_THREAD_PRIORITY), NULL); k_thread_name_set(&data->workq.thread, "esp_workq"); /* cmd handler */ const struct modem_cmd_handler_config cmd_handler_config = { .match_buf = &data->cmd_match_buf[0], .match_buf_len = sizeof(data->cmd_match_buf), .buf_pool = &mdm_recv_pool, .alloc_timeout = K_NO_WAIT, .eol = "\r\n", .user_data = NULL, .response_cmds = response_cmds, .response_cmds_len = ARRAY_SIZE(response_cmds), .unsol_cmds = unsol_cmds, .unsol_cmds_len = ARRAY_SIZE(unsol_cmds), }; ret = modem_cmd_handler_init(&data->mctx.cmd_handler, &data->cmd_handler_data, &cmd_handler_config); if (ret < 0) { goto error; } /* modem interface */ const struct modem_iface_uart_config uart_config = { .rx_rb_buf = &data->iface_rb_buf[0], .rx_rb_buf_len = sizeof(data->iface_rb_buf), .dev = DEVICE_DT_GET(DT_INST_BUS(0)), .hw_flow_control = DT_PROP(ESP_BUS, hw_flow_control), }; ret = modem_iface_uart_init(&data->mctx.iface, &data->iface_data, &uart_config); if (ret < 0) { goto error; } /* pin setup */ #if DT_INST_NODE_HAS_PROP(0, power_gpios) ret = gpio_pin_configure_dt(&config->power, GPIO_OUTPUT_INACTIVE); if (ret < 0) { LOG_ERR("Failed to configure %s pin", "power"); goto error; } #endif #if DT_INST_NODE_HAS_PROP(0, reset_gpios) ret = gpio_pin_configure_dt(&config->reset, GPIO_OUTPUT_INACTIVE); if (ret < 0) { LOG_ERR("Failed to configure %s pin", "reset"); goto error; } #endif data->mctx.driver_data = data; ret = modem_context_register(&data->mctx); if (ret < 0) { LOG_ERR("Error registering modem context: %d", ret); goto error; } /* start RX thread */ k_thread_create(&esp_rx_thread, esp_rx_stack, K_KERNEL_STACK_SIZEOF(esp_rx_stack), esp_rx, data, NULL, NULL, K_PRIO_COOP(CONFIG_WIFI_ESP_AT_RX_THREAD_PRIORITY), 0, K_NO_WAIT); k_thread_name_set(&esp_rx_thread, "esp_rx"); /* Retrieve associated network interface so asynchronous messages can be processed early */ data->net_iface = NET_IF_GET(Z_DEVICE_DT_DEV_ID(DT_DRV_INST(0)), 0); /* Reset the modem */ ret = esp_reset(dev); error: return ret; } ```
/content/code_sandbox/drivers/wifi/esp_at/esp.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
11,405
```c /* * */ /** * @brief File containing netowrk stack interface specific definitions for the * Zephyr OS layer of the Wi-Fi driver. */ #include <stdlib.h> #ifdef CONFIG_WIFI_RANDOM_MAC_ADDRESS #include <zephyr/random/random.h> #endif #include <zephyr/logging/log.h> LOG_MODULE_DECLARE(wifi_nrf, CONFIG_WIFI_NRF70_LOG_LEVEL); #include "net_private.h" #include "util.h" #include "fmac_api.h" #include "fmac_util.h" #include "shim.h" #include "fmac_main.h" #include "wpa_supp_if.h" #include "net_if.h" extern char *net_sprint_ll_addr_buf(const uint8_t *ll, uint8_t ll_len, char *buf, int buflen); #ifdef CONFIG_NRF70_STA_MODE static struct net_if_mcast_monitor mcast_monitor; #endif /* CONFIG_NRF70_STA_MODE */ void nrf_wifi_set_iface_event_handler(void *os_vif_ctx, struct nrf_wifi_umac_event_set_interface *event, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; if (!os_vif_ctx) { LOG_ERR("%s: Invalid parameters", __func__); goto out; } if (!event) { LOG_ERR("%s: event is NULL", __func__); goto out; } (void)event_len; vif_ctx_zep = os_vif_ctx; vif_ctx_zep->set_if_event_received = true; vif_ctx_zep->set_if_status = event->return_value; out: return; } #ifdef CONFIG_NRF_WIFI_RPU_RECOVERY static void nrf_wifi_rpu_recovery_work_handler(struct k_work *work) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = CONTAINER_OF(work, struct nrf_wifi_vif_ctx_zep, nrf_wifi_rpu_recovery_work); struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return; } if (!vif_ctx_zep->zep_net_if_ctx) { LOG_ERR("%s: zep_net_if_ctx is NULL", __func__); return; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep || !rpu_ctx_zep->rpu_ctx) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return; } k_mutex_lock(&rpu_ctx_zep->rpu_lock, K_FOREVER); LOG_DBG("%s: Bringing the interface down", __func__); /* This indirectly does a cold-boot of RPU */ net_if_down(vif_ctx_zep->zep_net_if_ctx); k_msleep(CONFIG_NRF_WIFI_RPU_RECOVERY_PROPAGATION_DELAY_MS); LOG_DBG("%s: Bringing the interface up", __func__); net_if_up(vif_ctx_zep->zep_net_if_ctx); k_mutex_unlock(&rpu_ctx_zep->rpu_lock); } void nrf_wifi_rpu_recovery_cb(void *vif_ctx_handle, void *event_data, unsigned int event_len) { struct nrf_wifi_fmac_vif_ctx *vif_ctx = vif_ctx_handle; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; if (!vif_ctx) { LOG_ERR("%s: vif_ctx is NULL", __func__); goto out; } fmac_dev_ctx = vif_ctx->fmac_dev_ctx; def_dev_ctx = wifi_dev_priv(fmac_dev_ctx); if (!def_dev_ctx) { LOG_ERR("%s: def_dev_ctx is NULL", __func__); goto out; } vif_ctx_zep = vif_ctx->os_vif_ctx; (void)event_data; k_work_submit(&vif_ctx_zep->nrf_wifi_rpu_recovery_work); out: return; } #endif /* CONFIG_NRF_WIFI_RPU_RECOVERY */ #ifdef CONFIG_NRF70_DATA_TX static void nrf_wifi_net_iface_work_handler(struct k_work *work) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = CONTAINER_OF(work, struct nrf_wifi_vif_ctx_zep, nrf_wifi_net_iface_work); if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return; } if (!vif_ctx_zep->zep_net_if_ctx) { LOG_ERR("%s: zep_net_if_ctx is NULL", __func__); return; } if (vif_ctx_zep->if_carr_state == NRF_WIFI_FMAC_IF_CARR_STATE_ON) { net_if_dormant_off(vif_ctx_zep->zep_net_if_ctx); } else if (vif_ctx_zep->if_carr_state == NRF_WIFI_FMAC_IF_CARR_STATE_OFF) { net_if_dormant_on(vif_ctx_zep->zep_net_if_ctx); } } #if defined(CONFIG_NRF70_RAW_DATA_RX) || defined(CONFIG_NRF70_PROMISC_DATA_RX) void nrf_wifi_if_sniffer_rx_frm(void *os_vif_ctx, void *frm, struct raw_rx_pkt_header *raw_rx_hdr, bool pkt_free) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = os_vif_ctx; struct net_if *iface = vif_ctx_zep->zep_net_if_ctx; struct net_pkt *pkt; struct nrf_wifi_ctx_zep *rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; int ret; def_dev_ctx = wifi_dev_priv(fmac_dev_ctx); pkt = net_raw_pkt_from_nbuf(iface, frm, sizeof(struct raw_rx_pkt_header), raw_rx_hdr, pkt_free); if (!pkt) { LOG_DBG("Failed to allocate net_pkt"); return; } net_capture_pkt(iface, pkt); ret = net_recv_data(iface, pkt); if (ret < 0) { LOG_DBG("RCV Packet dropped by NET stack: %d", ret); net_pkt_unref(pkt); } } #endif /* CONFIG_NRF70_RAW_DATA_RX || CONFIG_NRF70_PROMISC_DATA_RX */ void nrf_wifi_if_rx_frm(void *os_vif_ctx, void *frm) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = os_vif_ctx; struct net_if *iface = vif_ctx_zep->zep_net_if_ctx; struct net_pkt *pkt; int status; struct nrf_wifi_ctx_zep *rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; struct rpu_host_stats *host_stats = NULL; def_dev_ctx = wifi_dev_priv(fmac_dev_ctx); host_stats = &def_dev_ctx->host_stats; host_stats->total_rx_pkts++; pkt = net_pkt_from_nbuf(iface, frm); if (!pkt) { LOG_DBG("Failed to allocate net_pkt"); host_stats->total_rx_drop_pkts++; return; } status = net_recv_data(iface, pkt); if (status < 0) { LOG_DBG("RCV Packet dropped by NET stack: %d", status); host_stats->total_rx_drop_pkts++; net_pkt_unref(pkt); } } enum nrf_wifi_status nrf_wifi_if_carr_state_chg(void *os_vif_ctx, enum nrf_wifi_fmac_if_carr_state carr_state) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; if (!os_vif_ctx) { LOG_ERR("%s: Invalid parameters", __func__); goto out; } vif_ctx_zep = os_vif_ctx; vif_ctx_zep->if_carr_state = carr_state; LOG_DBG("%s: Carrier state: %d", __func__, carr_state); k_work_submit(&vif_ctx_zep->nrf_wifi_net_iface_work); status = NRF_WIFI_STATUS_SUCCESS; out: return status; } static bool is_eapol(struct net_pkt *pkt) { struct net_eth_hdr *hdr; uint16_t ethertype; hdr = NET_ETH_HDR(pkt); ethertype = ntohs(hdr->type); return ethertype == NET_ETH_PTYPE_EAPOL; } #endif /* CONFIG_NRF70_DATA_TX */ enum ethernet_hw_caps nrf_wifi_if_caps_get(const struct device *dev) { enum ethernet_hw_caps caps = (ETHERNET_LINK_10BASE_T | ETHERNET_LINK_100BASE_T | ETHERNET_LINK_1000BASE_T); #ifdef CONFIG_NRF70_TCP_IP_CHECKSUM_OFFLOAD caps |= ETHERNET_HW_TX_CHKSUM_OFFLOAD | ETHERNET_HW_RX_CHKSUM_OFFLOAD; #endif /* CONFIG_NRF70_TCP_IP_CHECKSUM_OFFLOAD */ #ifdef CONFIG_NRF70_RAW_DATA_TX caps |= ETHERNET_TXINJECTION_MODE; #endif #ifdef CONFIG_NRF70_PROMISC_DATA_RX caps |= ETHERNET_PROMISC_MODE; #endif return caps; } int nrf_wifi_if_send(const struct device *dev, struct net_pkt *pkt) { int ret = -1; #ifdef CONFIG_NRF70_DATA_TX struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; if (!dev || !pkt) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto out; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto out; } ret = k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (ret != 0) { LOG_ERR("%s: Failed to lock vif_lock", __func__); goto out; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep || !rpu_ctx_zep->rpu_ctx) { goto unlock; } #ifdef CONFIG_NRF70_RAW_DATA_TX if ((*(unsigned int *)pkt->frags->data) == NRF_WIFI_MAGIC_NUM_RAWTX) { if (vif_ctx_zep->if_carr_state != NRF_WIFI_FMAC_IF_CARR_STATE_ON) { goto unlock; } ret = nrf_wifi_fmac_start_rawpkt_xmit(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, net_pkt_to_nbuf(pkt)); } else { #endif /* CONFIG_NRF70_RAW_DATA_TX */ if ((vif_ctx_zep->if_carr_state != NRF_WIFI_FMAC_IF_CARR_STATE_ON) || (!vif_ctx_zep->authorized && !is_eapol(pkt))) { goto unlock; } ret = nrf_wifi_fmac_start_xmit(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, net_pkt_to_nbuf(pkt)); #ifdef CONFIG_NRF70_RAW_DATA_TX } #endif /* CONFIG_NRF70_RAW_DATA_TX */ unlock: k_mutex_unlock(&vif_ctx_zep->vif_lock); #else ARG_UNUSED(dev); ARG_UNUSED(pkt); goto out; #endif /* CONFIG_NRF70_DATA_TX */ out: return ret; } #ifdef CONFIG_NRF70_STA_MODE static void ip_maddr_event_handler(struct net_if *iface, const struct net_addr *addr, bool is_joined) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct net_eth_addr mac_addr; struct nrf_wifi_umac_mcast_cfg *mcast_info = NULL; enum nrf_wifi_status status; uint8_t mac_string_buf[sizeof("xx:xx:xx:xx:xx:xx")]; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; int ret; vif_ctx_zep = nrf_wifi_get_vif_ctx(iface); if (!vif_ctx_zep) { return; } ret = k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (ret != 0) { LOG_ERR("%s: Failed to lock vif_lock", __func__); goto out; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep || !rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: rpu_ctx_zep or rpu_ctx is NULL", __func__); goto unlock; } mcast_info = k_calloc(sizeof(*mcast_info), sizeof(char)); if (!mcast_info) { LOG_ERR("%s: Unable to allocate memory of size %d " "for mcast_info", __func__, sizeof(*mcast_info)); return; } switch (addr->family) { case AF_INET: net_eth_ipv4_mcast_to_mac_addr(&addr->in_addr, &mac_addr); break; case AF_INET6: net_eth_ipv6_mcast_to_mac_addr(&addr->in6_addr, &mac_addr); break; default: LOG_ERR("%s: Invalid address family %d", __func__, addr->family); break; } if (is_joined) { mcast_info->type = MCAST_ADDR_ADD; } else { mcast_info->type = MCAST_ADDR_DEL; } memcpy(((char *)(mcast_info->mac_addr)), &mac_addr, NRF_WIFI_ETH_ADDR_LEN); status = nrf_wifi_fmac_set_mcast_addr(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, mcast_info); if (status == NRF_WIFI_STATUS_FAIL) { LOG_ERR("%s: nrf_wifi_fmac_set_multicast failed for" " mac addr=%s", __func__, net_sprint_ll_addr_buf(mac_addr.addr, WIFI_MAC_ADDR_LEN, mac_string_buf, sizeof(mac_string_buf))); } unlock: k_mutex_unlock(&vif_ctx_zep->vif_lock); out: k_free(mcast_info); } #endif /* CONFIG_NRF70_STA_MODE */ #ifdef CONFIG_WIFI_FIXED_MAC_ADDRESS_ENABLED BUILD_ASSERT(sizeof(CONFIG_WIFI_FIXED_MAC_ADDRESS) - 1 == ((WIFI_MAC_ADDR_LEN * 2) + 5), "Invalid fixed MAC address length"); #endif enum nrf_wifi_status nrf_wifi_get_mac_addr(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; int ret; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto out; } ret = k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (ret != 0) { LOG_ERR("%s: Failed to lock vif_lock", __func__); goto out; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep || !rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: rpu_ctx_zep or rpu_ctx is NULL", __func__); goto unlock; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; #ifdef CONFIG_WIFI_FIXED_MAC_ADDRESS_ENABLED char fixed_mac_addr[WIFI_MAC_ADDR_LEN]; ret = net_bytes_from_str(fixed_mac_addr, WIFI_MAC_ADDR_LEN, CONFIG_WIFI_FIXED_MAC_ADDRESS); if (ret < 0) { LOG_ERR("%s: Failed to parse MAC address: %s", __func__, CONFIG_WIFI_FIXED_MAC_ADDRESS); goto unlock; } memcpy(vif_ctx_zep->mac_addr.addr, fixed_mac_addr, WIFI_MAC_ADDR_LEN); #elif CONFIG_WIFI_RANDOM_MAC_ADDRESS char random_mac_addr[WIFI_MAC_ADDR_LEN]; sys_rand_get(random_mac_addr, WIFI_MAC_ADDR_LEN); random_mac_addr[0] = (random_mac_addr[0] & UNICAST_MASK) | LOCAL_BIT; memcpy(vif_ctx_zep->mac_addr.addr, random_mac_addr, WIFI_MAC_ADDR_LEN); #elif CONFIG_WIFI_OTP_MAC_ADDRESS status = nrf_wifi_fmac_otp_mac_addr_get(fmac_dev_ctx, vif_ctx_zep->vif_idx, vif_ctx_zep->mac_addr.addr); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Fetching of MAC address from OTP failed", __func__); goto unlock; } #endif if (!nrf_wifi_utils_is_mac_addr_valid(fmac_dev_ctx->fpriv->opriv, vif_ctx_zep->mac_addr.addr)) { LOG_ERR("%s: Invalid MAC address: %s", __func__, net_sprint_ll_addr(vif_ctx_zep->mac_addr.addr, WIFI_MAC_ADDR_LEN)); status = NRF_WIFI_STATUS_FAIL; memset(vif_ctx_zep->mac_addr.addr, 0, WIFI_MAC_ADDR_LEN); goto unlock; } status = NRF_WIFI_STATUS_SUCCESS; unlock: k_mutex_unlock(&vif_ctx_zep->vif_lock); out: return status; } void nrf_wifi_if_init_zep(struct net_if *iface) { const struct device *dev = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct ethernet_context *eth_ctx = net_if_l2_data(iface); if (!iface) { LOG_ERR("%s: Invalid parameters", __func__); return; } dev = net_if_get_device(iface); if (!dev) { LOG_ERR("%s: Invalid dev", __func__); return; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return; } vif_ctx_zep->zep_net_if_ctx = iface; vif_ctx_zep->zep_dev_ctx = dev; eth_ctx->eth_if_type = L2_ETH_IF_TYPE_WIFI; ethernet_init(iface); net_eth_carrier_on(iface); net_if_dormant_on(iface); #ifdef CONFIG_NRF70_STA_MODE net_if_mcast_mon_register(&mcast_monitor, iface, ip_maddr_event_handler); #endif /* CONFIG_NRF70_STA_MODE */ #ifdef CONFIG_NRF70_DATA_TX k_work_init(&vif_ctx_zep->nrf_wifi_net_iface_work, nrf_wifi_net_iface_work_handler); #endif /* CONFIG_NRF70_DATA_TX */ #ifdef CONFIG_NRF_WIFI_RPU_RECOVERY k_work_init(&vif_ctx_zep->nrf_wifi_rpu_recovery_work, nrf_wifi_rpu_recovery_work_handler); #endif /* CONFIG_NRF_WIFI_RPU_RECOVERY */ #if !defined(CONFIG_NRF_WIFI_IF_AUTO_START) net_if_flag_set(iface, NET_IF_NO_AUTO_START); #endif /* CONFIG_NRF_WIFI_IF_AUTO_START */ net_if_flag_set(iface, NET_IF_NO_TX_LOCK); } /* Board-specific Wi-Fi startup code to run before the Wi-Fi device is started */ __weak int nrf_wifi_if_zep_start_board(const struct device *dev) { ARG_UNUSED(dev); return 0; } /* Board-specific Wi-Fi shutdown code to run after the Wi-Fi device is stopped */ __weak int nrf_wifi_if_zep_stop_board(const struct device *dev) { ARG_UNUSED(dev); return 0; } int nrf_wifi_if_start_zep(const struct device *dev) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct nrf_wifi_umac_chg_vif_state_info vif_info; struct nrf_wifi_umac_add_vif_info add_vif_info; char *mac_addr = NULL; unsigned int mac_addr_len = 0; int ret = -1; bool fmac_dev_added = false; if (!dev) { LOG_ERR("%s: Invalid parameters", __func__); goto out; } if (!device_is_ready(dev)) { LOG_ERR("%s: Device %s is not ready", __func__, dev->name); goto out; } ret = nrf_wifi_if_zep_start_board(dev); if (ret) { LOG_ERR("nrf_wifi_if_zep_start_board failed with error: %d", ret); goto out; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto out; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); goto out; } ret = k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (ret != 0) { LOG_ERR("%s: Failed to lock vif_lock", __func__); goto out; } if (!rpu_ctx_zep->rpu_ctx) { status = nrf_wifi_fmac_dev_add_zep(&rpu_drv_priv_zep); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_dev_add_zep failed", __func__); goto out; } fmac_dev_added = true; LOG_DBG("%s: FMAC device added", __func__); } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; memset(&add_vif_info, 0, sizeof(add_vif_info)); /* TODO: This should be configurable */ add_vif_info.iftype = NRF_WIFI_IFTYPE_STATION; memcpy(add_vif_info.ifacename, dev->name, strlen(dev->name)); vif_ctx_zep->vif_idx = nrf_wifi_fmac_add_vif(fmac_dev_ctx, vif_ctx_zep, &add_vif_info); if (vif_ctx_zep->vif_idx >= MAX_NUM_VIFS) { LOG_ERR("%s: FMAC returned invalid interface index", __func__); goto dev_rem; } k_mutex_init(&vif_ctx_zep->vif_lock); rpu_ctx_zep->vif_ctx_zep[vif_ctx_zep->vif_idx].if_type = add_vif_info.iftype; /* Check if user has provided a valid MAC address, if not * fetch it from OTP. */ mac_addr = net_if_get_link_addr(vif_ctx_zep->zep_net_if_ctx)->addr; mac_addr_len = net_if_get_link_addr(vif_ctx_zep->zep_net_if_ctx)->len; if (!nrf_wifi_utils_is_mac_addr_valid(fmac_dev_ctx->fpriv->opriv, mac_addr)) { status = nrf_wifi_get_mac_addr(vif_ctx_zep); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Failed to get MAC address", __func__); goto del_vif; } net_if_set_link_addr(vif_ctx_zep->zep_net_if_ctx, vif_ctx_zep->mac_addr.addr, WIFI_MAC_ADDR_LEN, NET_LINK_ETHERNET); mac_addr = vif_ctx_zep->mac_addr.addr; mac_addr_len = WIFI_MAC_ADDR_LEN; } status = nrf_wifi_fmac_set_vif_macaddr(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, mac_addr); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: MAC address change failed", __func__); goto del_vif; } memset(&vif_info, 0, sizeof(vif_info)); vif_info.state = NRF_WIFI_FMAC_IF_OP_STATE_UP; vif_info.if_index = vif_ctx_zep->vif_idx; memcpy(vif_ctx_zep->ifname, dev->name, strlen(dev->name)); status = nrf_wifi_fmac_chg_vif_state(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &vif_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_chg_vif_state failed", __func__); goto del_vif; } #ifdef CONFIG_NRF70_STA_MODE nrf_wifi_wpa_supp_event_mac_chgd(vif_ctx_zep); #ifdef CONFIG_NRF_WIFI_LOW_POWER status = nrf_wifi_fmac_set_power_save(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, NRF_WIFI_PS_ENABLED); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_set_power_save failed", __func__); goto dev_rem; } #endif /* CONFIG_NRF_WIFI_LOW_POWER */ #endif /* CONFIG_NRF70_STA_MODE */ vif_ctx_zep->if_op_state = NRF_WIFI_FMAC_IF_OP_STATE_UP; ret = 0; goto out; del_vif: status = nrf_wifi_fmac_del_vif(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_del_vif failed", __func__); } dev_rem: /* Free only if we added above i.e., for 1st VIF */ if (fmac_dev_added) { nrf_wifi_fmac_dev_rem_zep(&rpu_drv_priv_zep); } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_if_stop_zep(const struct device *dev) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_umac_chg_vif_state_info vif_info; int ret = -1; if (!dev) { LOG_ERR("%s: Invalid parameters", __func__); goto out; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto out; } ret = k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (ret != 0) { LOG_ERR("%s: Failed to lock vif_lock", __func__); goto out; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); goto out; } #ifdef CONFIG_NRF70_STA_MODE #ifdef CONFIG_NRF_WIFI_LOW_POWER status = nrf_wifi_fmac_set_power_save(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, NRF_WIFI_PS_DISABLED); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_set_power_save failed", __func__); goto unlock; } #endif /* CONFIG_NRF_WIFI_LOW_POWER */ #endif /* CONFIG_NRF70_STA_MODE */ memset(&vif_info, 0, sizeof(vif_info)); vif_info.state = NRF_WIFI_FMAC_IF_OP_STATE_DOWN; vif_info.if_index = vif_ctx_zep->vif_idx; status = nrf_wifi_fmac_chg_vif_state(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &vif_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_chg_vif_state failed", __func__); goto unlock; } status = nrf_wifi_fmac_del_vif(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_del_vif failed", __func__); goto unlock; } vif_ctx_zep->if_op_state = NRF_WIFI_FMAC_IF_OP_STATE_DOWN; if (nrf_wifi_fmac_get_num_vifs(rpu_ctx_zep->rpu_ctx) == 0) { nrf_wifi_fmac_dev_rem_zep(&rpu_drv_priv_zep); } ret = 0; unlock: k_mutex_unlock(&vif_ctx_zep->vif_lock); ret = nrf_wifi_if_zep_stop_board(dev); if (ret) { LOG_ERR("nrf_wifi_if_zep_stop_board failed with error: %d", ret); } out: return ret; } int nrf_wifi_if_get_config_zep(const struct device *dev, enum ethernet_config_type type, struct ethernet_config *config) { int ret = -1; #ifdef CONFIG_NRF70_RAW_DATA_TX struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; if (!dev || !config) { LOG_ERR("%s: Invalid parameters", __func__); goto out; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto out; } ret = k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (ret != 0) { LOG_ERR("%s: Failed to lock vif_lock", __func__); goto out; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep || !rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: rpu_ctx_zep or rpu_ctx is NULL", __func__); goto unlock; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; def_dev_ctx = wifi_dev_priv(fmac_dev_ctx); if (!def_dev_ctx) { LOG_ERR("%s: def_dev_ctx is NULL", __func__); goto unlock; } if (type == ETHERNET_CONFIG_TYPE_TXINJECTION_MODE) { config->txinjection_mode = def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->txinjection_mode; } ret = 0; unlock: k_mutex_unlock(&vif_ctx_zep->vif_lock); out: #endif return ret; } int nrf_wifi_if_set_config_zep(const struct device *dev, enum ethernet_config_type type, const struct ethernet_config *config) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; int ret = -1; if (!dev) { LOG_ERR("%s: Invalid parameters", __func__); goto out; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto out; } ret = k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (ret != 0) { LOG_ERR("%s: Failed to lock vif_lock", __func__); goto out; } /* Commands without FMAC interaction */ if (type == ETHERNET_CONFIG_TYPE_MAC_ADDRESS) { if (!net_eth_is_addr_valid((struct net_eth_addr *)&config->mac_address)) { LOG_ERR("%s: Invalid MAC address", __func__); goto unlock; } memcpy(vif_ctx_zep->mac_addr.addr, config->mac_address.addr, sizeof(vif_ctx_zep->mac_addr.addr)); net_if_set_link_addr(vif_ctx_zep->zep_net_if_ctx, vif_ctx_zep->mac_addr.addr, sizeof(vif_ctx_zep->mac_addr.addr), NET_LINK_ETHERNET); ret = 0; goto unlock; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep || !rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: rpu_ctx_zep or rpu_ctx is NULL", __func__); goto unlock; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; def_dev_ctx = wifi_dev_priv(fmac_dev_ctx); if (!def_dev_ctx) { LOG_ERR("%s: def_dev_ctx is NULL", __func__); goto unlock; } #ifdef CONFIG_NRF70_RAW_DATA_TX if (type == ETHERNET_CONFIG_TYPE_TXINJECTION_MODE) { unsigned char mode; if (def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->txinjection_mode == config->txinjection_mode) { LOG_INF("%s: Driver TX injection setting is same as configured setting", __func__); goto unlock; } /** * Since UMAC wishes to use the same mode command as previously * used for mode, `OR` the primary mode with TX-Injection mode and * send it to the UMAC. That way UMAC can still maintain code * as is */ if (config->txinjection_mode) { mode = (def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->mode) | (NRF_WIFI_TX_INJECTION_MODE); } else { mode = (def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->mode) ^ (NRF_WIFI_TX_INJECTION_MODE); } ret = nrf_wifi_fmac_set_mode(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, mode); if (ret != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Mode set operation failed", __func__); goto unlock; } } #endif #ifdef CONFIG_NRF70_PROMISC_DATA_RX else if (type == ETHERNET_CONFIG_TYPE_PROMISC_MODE) { unsigned char mode; if (def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->promisc_mode == config->promisc_mode) { LOG_ERR("%s: Driver promisc mode setting is same as configured setting", __func__); goto out; } if (config->promisc_mode) { mode = (def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->mode) | (NRF_WIFI_PROMISCUOUS_MODE); } else { mode = (def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->mode) ^ (NRF_WIFI_PROMISCUOUS_MODE); } ret = nrf_wifi_fmac_set_mode(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, mode); if (ret != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: mode set operation failed", __func__); goto out; } } #endif ret = 0; unlock: k_mutex_unlock(&vif_ctx_zep->vif_lock); out: return ret; } #ifdef CONFIG_NET_STATISTICS_ETHERNET struct net_stats_eth *nrf_wifi_eth_stats_get(const struct device *dev) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; if (!dev) { LOG_ERR("%s Device not found", __func__); goto out; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto out; } return &vif_ctx_zep->eth_stats; out: return NULL; } #endif /* CONFIG_NET_STATISTICS_ETHERNET */ #ifdef CONFIG_NET_STATISTICS_WIFI int nrf_wifi_stats_get(const struct device *dev, struct net_stats_wifi *zstats) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; #ifdef CONFIG_NRF70_RAW_DATA_TX struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; #endif /* CONFIG_NRF70_RAW_DATA_TX */ struct rpu_op_stats stats; int ret = -1; if (!dev) { LOG_ERR("%s Device not found", __func__); goto out; } if (!zstats) { LOG_ERR("%s Stats buffer not allocated", __func__); goto out; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto out; } ret = k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (ret != 0) { LOG_ERR("%s: Failed to lock vif_lock", __func__); goto out; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep || !rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: rpu_ctx_zep or rpu_ctx is NULL", __func__); goto unlock; } memset(&stats, 0, sizeof(struct rpu_op_stats)); status = nrf_wifi_fmac_stats_get(rpu_ctx_zep->rpu_ctx, 0, &stats); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_stats_get failed", __func__); goto unlock; } zstats->pkts.tx = stats.host.total_tx_pkts; zstats->pkts.rx = stats.host.total_rx_pkts; zstats->errors.tx = stats.host.total_tx_drop_pkts; zstats->errors.rx = stats.host.total_rx_drop_pkts + stats.fw.umac.interface_data_stats.rx_checksum_error_count; zstats->bytes.received = stats.fw.umac.interface_data_stats.rx_bytes; zstats->bytes.sent = stats.fw.umac.interface_data_stats.tx_bytes; zstats->sta_mgmt.beacons_rx = stats.fw.umac.interface_data_stats.rx_beacon_success_count; zstats->sta_mgmt.beacons_miss = stats.fw.umac.interface_data_stats.rx_beacon_miss_count; zstats->broadcast.rx = stats.fw.umac.interface_data_stats.rx_broadcast_pkt_count; zstats->broadcast.tx = stats.fw.umac.interface_data_stats.tx_broadcast_pkt_count; zstats->multicast.rx = stats.fw.umac.interface_data_stats.rx_multicast_pkt_count; zstats->multicast.tx = stats.fw.umac.interface_data_stats.tx_multicast_pkt_count; zstats->unicast.rx = stats.fw.umac.interface_data_stats.rx_unicast_pkt_count; zstats->unicast.tx = stats.fw.umac.interface_data_stats.tx_unicast_pkt_count; #ifdef CONFIG_NRF70_RAW_DATA_TX def_dev_ctx = wifi_dev_priv(rpu_ctx_zep->rpu_ctx); zstats->errors.tx += def_dev_ctx->raw_pkt_stats.raw_pkt_send_failure; #endif /* CONFIG_NRF70_RAW_DATA_TX */ ret = 0; unlock: k_mutex_unlock(&vif_ctx_zep->vif_lock); out: return ret; } #endif /* CONFIG_NET_STATISTICS_WIFI */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/net_if.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
8,999
```c /* * */ /** * @brief File containing FW load functions for Zephyr. */ #include <stdlib.h> #include <string.h> #include <zephyr/kernel.h> #include <zephyr/device.h> #include <zephyr/logging/log.h> LOG_MODULE_DECLARE(wifi_nrf, CONFIG_WIFI_NRF70_LOG_LEVEL); #include <fmac_main.h> #ifdef CONFIG_NRF_WIFI_PATCHES_BUILTIN /* INCBIN macro Taken from path_to_url */ #define STR2(x) #x #define STR(x) STR2(x) #ifdef __APPLE__ #define USTR(x) "_" STR(x) #else #define USTR(x) STR(x) #endif #ifdef _WIN32 #define INCBIN_SECTION ".rdata, \"dr\"" #elif defined __APPLE__ #define INCBIN_SECTION "__TEXT,__const" #else #define INCBIN_SECTION ".rodata.*" #endif /* this aligns start address to 16 and terminates byte array with explicit 0 * which is not really needed, feel free to change it to whatever you want/need */ #define INCBIN(prefix, name, file) \ __asm__(".section " INCBIN_SECTION "\n" \ ".global " USTR(prefix) "_" STR(name) "_start\n" \ ".balign 16\n" \ USTR(prefix) "_" STR(name) "_start:\n" \ ".incbin \"" file "\"\n" \ \ ".global " STR(prefix) "_" STR(name) "_end\n" \ ".balign 1\n" \ USTR(prefix) "_" STR(name) "_end:\n" \ ".byte 0\n" \ ); \ extern __aligned(16) const char prefix ## _ ## name ## _start[]; \ extern const char prefix ## _ ## name ## _end[]; INCBIN(_bin, nrf70_fw, STR(CONFIG_NRF_WIFI_FW_BIN)); #endif /* CONFIG_NRF_WIFI_PATCHES_BUILTIN */ enum nrf_wifi_status nrf_wifi_fw_load(void *rpu_ctx) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_fmac_fw_info fw_info = { 0 }; uint8_t *fw_start; uint8_t *fw_end; fw_start = (uint8_t *)_bin_nrf70_fw_start; fw_end = (uint8_t *)_bin_nrf70_fw_end; status = nrf_wifi_fmac_fw_parse(rpu_ctx, fw_start, fw_end - fw_start, &fw_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_fw_parse failed", __func__); return status; } /* Load the FW patches to the RPU */ status = nrf_wifi_fmac_fw_load(rpu_ctx, &fw_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_fw_load failed", __func__); } return status; } ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/fw_load.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
641
```c /* * */ /** * @brief File containing FMAC interface specific definitions for the * Zephyr OS layer of the Wi-Fi driver. */ #include <stdlib.h> #include <zephyr/kernel.h> #ifdef CONFIG_NET_L2_ETHERNET #include <zephyr/net/ethernet.h> #endif #include <zephyr/logging/log.h> #include <zephyr/net/wifi_mgmt.h> #include <zephyr/net/conn_mgr_connectivity.h> #include <zephyr/net/conn_mgr_connectivity_impl.h> #include <zephyr/net/conn_mgr/connectivity_wifi_mgmt.h> #include <util.h> #include <fmac_api.h> #include "fmac_util.h" #include <fmac_main.h> #ifndef CONFIG_NRF70_RADIO_TEST #ifdef CONFIG_NRF70_STA_MODE #include <zephyr/net/wifi_nm.h> #include <wifi_mgmt_scan.h> #include <wifi_mgmt.h> #include <wpa_supp_if.h> #else #include <wifi_mgmt.h> #include <wifi_mgmt_scan.h> #endif /* CONFIG_NRF70_STA_MODE */ #include <zephyr/net/conn_mgr_connectivity.h> #endif /* !CONFIG_NRF70_RADIO_TEST */ #define DT_DRV_COMPAT nordic_wlan LOG_MODULE_DECLARE(wifi_nrf, CONFIG_WIFI_NRF70_LOG_LEVEL); struct nrf_wifi_drv_priv_zep rpu_drv_priv_zep; /* 3 bytes for addreess, 3 bytes for length */ #define MAX_PKT_RAM_TX_ALIGN_OVERHEAD 6 #ifndef CONFIG_NRF70_RADIO_TEST #ifdef CONFIG_NRF70_DATA_TX #define MAX_RX_QUEUES 3 #define MAX_TX_FRAME_SIZE \ (CONFIG_NRF_WIFI_IFACE_MTU + NRF_WIFI_FMAC_ETH_HDR_LEN + TX_BUF_HEADROOM) #define TOTAL_TX_SIZE \ (CONFIG_NRF70_MAX_TX_TOKENS * CONFIG_NRF70_TX_MAX_DATA_SIZE) #define TOTAL_RX_SIZE \ (CONFIG_NRF70_RX_NUM_BUFS * CONFIG_NRF70_RX_MAX_DATA_SIZE) BUILD_ASSERT(CONFIG_NRF70_MAX_TX_TOKENS >= 1, "At least one TX token is required"); BUILD_ASSERT(CONFIG_NRF70_MAX_TX_AGGREGATION <= 15, "Max TX aggregation is 15"); BUILD_ASSERT(CONFIG_NRF70_RX_NUM_BUFS >= 1, "At least one RX buffer is required"); BUILD_ASSERT(RPU_PKTRAM_SIZE - TOTAL_RX_SIZE >= TOTAL_TX_SIZE, "Packet RAM overflow: not enough memory for TX"); BUILD_ASSERT(CONFIG_NRF70_TX_MAX_DATA_SIZE >= MAX_TX_FRAME_SIZE, "TX buffer size must be at least as big as the MTU and headroom"); static const unsigned char aggregation = 1; static const unsigned char wmm = 1; static const unsigned char max_num_tx_agg_sessions = 4; static const unsigned char max_num_rx_agg_sessions = 8; static const unsigned char reorder_buf_size = 16; static const unsigned char max_rxampdu_size = MAX_RX_AMPDU_SIZE_64KB; static const unsigned char max_tx_aggregation = CONFIG_NRF70_MAX_TX_AGGREGATION; static const unsigned int rx1_num_bufs = CONFIG_NRF70_RX_NUM_BUFS / MAX_RX_QUEUES; static const unsigned int rx2_num_bufs = CONFIG_NRF70_RX_NUM_BUFS / MAX_RX_QUEUES; static const unsigned int rx3_num_bufs = CONFIG_NRF70_RX_NUM_BUFS / MAX_RX_QUEUES; static const unsigned int rx1_buf_sz = CONFIG_NRF70_RX_MAX_DATA_SIZE; static const unsigned int rx2_buf_sz = CONFIG_NRF70_RX_MAX_DATA_SIZE; static const unsigned int rx3_buf_sz = CONFIG_NRF70_RX_MAX_DATA_SIZE; static const unsigned char rate_protection_type; #else /* Reduce buffers to Scan only operation */ static const unsigned int rx1_num_bufs = 2; static const unsigned int rx2_num_bufs = 2; static const unsigned int rx3_num_bufs = 2; static const unsigned int rx1_buf_sz = 1000; static const unsigned int rx2_buf_sz = 1000; static const unsigned int rx3_buf_sz = 1000; #endif struct nrf_wifi_drv_priv_zep rpu_drv_priv_zep; static K_MUTEX_DEFINE(reg_lock); const char *nrf_wifi_get_drv_version(void) { return NRF70_DRIVER_VERSION; } /* If the interface is not Wi-Fi then errors are expected, so, fail silently */ struct nrf_wifi_vif_ctx_zep *nrf_wifi_get_vif_ctx(struct net_if *iface) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx = &rpu_drv_priv_zep.rpu_ctx_zep; if (!iface || !rpu_ctx || !rpu_ctx->rpu_ctx) { return NULL; } for (int i = 0; i < ARRAY_SIZE(rpu_ctx->vif_ctx_zep); i++) { if (rpu_ctx->vif_ctx_zep[i].zep_net_if_ctx == iface) { vif_ctx_zep = &rpu_ctx->vif_ctx_zep[i]; break; } } return vif_ctx_zep; } void nrf_wifi_event_proc_scan_start_zep(void *if_priv, struct nrf_wifi_umac_event_trigger_scan *scan_start_event, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; vif_ctx_zep = if_priv; if (vif_ctx_zep->scan_type == SCAN_DISPLAY) { return; } #ifdef CONFIG_NRF70_STA_MODE nrf_wifi_wpa_supp_event_proc_scan_start(if_priv); #endif /* CONFIG_NRF70_STA_MODE */ } void nrf_wifi_event_proc_scan_done_zep(void *vif_ctx, struct nrf_wifi_umac_event_trigger_scan *scan_done_event, unsigned int event_len) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; vif_ctx_zep = vif_ctx; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return; } switch (vif_ctx_zep->scan_type) { #ifdef CONFIG_NET_L2_WIFI_MGMT case SCAN_DISPLAY: status = nrf_wifi_disp_scan_res_get_zep(vif_ctx_zep); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_disp_scan_res_get_zep failed", __func__); return; } vif_ctx_zep->scan_in_progress = false; break; #endif /* CONFIG_NET_L2_WIFI_MGMT */ #ifdef CONFIG_NRF70_STA_MODE case SCAN_CONNECT: nrf_wifi_wpa_supp_event_proc_scan_done(vif_ctx_zep, scan_done_event, event_len, 0); break; #endif /* CONFIG_NRF70_STA_MODE */ default: LOG_ERR("%s: Scan type = %d not supported yet", __func__, vif_ctx_zep->scan_type); return; } status = NRF_WIFI_STATUS_SUCCESS; } void nrf_wifi_scan_timeout_work(struct k_work *work) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; vif_ctx_zep = CONTAINER_OF(work, struct nrf_wifi_vif_ctx_zep, scan_timeout_work.work); if (!vif_ctx_zep->scan_in_progress) { LOG_INF("%s: Scan not in progress", __func__); return; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; #ifdef CONFIG_NET_L2_WIFI_MGMT if (vif_ctx_zep->disp_scan_cb) { vif_ctx_zep->disp_scan_cb(vif_ctx_zep->zep_net_if_ctx, -ETIMEDOUT, NULL); vif_ctx_zep->disp_scan_cb = NULL; } else #endif /* CONFIG_NET_L2_WIFI_MGMT */ { #ifdef CONFIG_NRF70_STA_MODE /* WPA supplicant scan */ union wpa_event_data event; struct scan_info *info = NULL; memset(&event, 0, sizeof(event)); info = &event.scan_info; info->aborted = 0; info->external_scan = 0; info->nl_scan_event = 1; if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.scan_done) { vif_ctx_zep->supp_callbk_fns.scan_done(vif_ctx_zep->supp_drv_if_ctx, &event); } #endif /* CONFIG_NRF70_STA_MODE */ } vif_ctx_zep->scan_in_progress = false; } #ifdef CONFIG_NRF70_STA_MODE static void nrf_wifi_process_rssi_from_rx(void *vif_ctx, signed short signal) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = vif_ctx; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; vif_ctx_zep = vif_ctx; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; vif_ctx_zep->rssi = MBM_TO_DBM(signal); vif_ctx_zep->rssi_record_timestamp_us = nrf_wifi_osal_time_get_curr_us(fmac_dev_ctx->fpriv->opriv); } #endif /* CONFIG_NRF70_STA_MODE */ void nrf_wifi_event_get_reg_zep(void *vif_ctx, struct nrf_wifi_reg *get_reg_event, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; LOG_DBG("%s: alpha2 = %c%c", __func__, get_reg_event->nrf_wifi_alpha2[0], get_reg_event->nrf_wifi_alpha2[1]); vif_ctx_zep = vif_ctx; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; if (fmac_dev_ctx->alpha2_valid) { LOG_ERR("%s: Unsolicited regulatory get!", __func__); return; } memcpy(&fmac_dev_ctx->alpha2, &get_reg_event->nrf_wifi_alpha2, sizeof(get_reg_event->nrf_wifi_alpha2)); fmac_dev_ctx->reg_chan_count = get_reg_event->num_channels; memcpy(fmac_dev_ctx->reg_chan_info, &get_reg_event->chn_info, fmac_dev_ctx->reg_chan_count * sizeof(struct nrf_wifi_get_reg_chn_info)); fmac_dev_ctx->alpha2_valid = true; } int nrf_wifi_reg_domain(const struct device *dev, struct wifi_reg_domain *reg_domain) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_fmac_reg_info reg_domain_info = {0}; struct wifi_reg_chan_info *chan_info = NULL; struct nrf_wifi_get_reg_chn_info *reg_domain_chan_info = NULL; int ret = -1; int chan_idx = 0; k_mutex_lock(&reg_lock, K_FOREVER); if (!dev || !reg_domain) { goto err; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto err; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); goto err; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; if (!fmac_dev_ctx) { LOG_ERR("%s: fmac_dev_ctx is NULL", __func__); goto err; } if (reg_domain->oper == WIFI_MGMT_SET) { #ifndef CONFIG_NRF70_RADIO_TEST #ifdef CONFIG_NRF70_STA_MODE /* Need to check if WPA supplicant is initialized or not. * Must be checked when CONFIG_WIFI_NM_WPA_SUPPLICANT is enabled. * Not applicable for RADIO_TEST or when * CONFIG_WIFI_NM_WPA_SUPPLICANT is not enabled. */ /* It is possbile that during supplicant initialization driver may * get the command. lock will try to ensure that supplicant * initialization is complete. */ k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if ((!vif_ctx_zep->supp_drv_if_ctx) || (!wifi_nm_get_instance_iface(vif_ctx_zep->zep_net_if_ctx))) { LOG_ERR("%s: WPA supplicant initialization not complete yet", __func__); k_mutex_unlock(&vif_ctx_zep->vif_lock); goto err; } k_mutex_unlock(&vif_ctx_zep->vif_lock); #endif /* CONFIG_NRF70_STA_MODE */ #endif /* !CONFIG_NRF70_RADIO_TEST */ memcpy(reg_domain_info.alpha2, reg_domain->country_code, WIFI_COUNTRY_CODE_LEN); reg_domain_info.force = reg_domain->force; status = nrf_wifi_fmac_set_reg(fmac_dev_ctx, &reg_domain_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Failed to set regulatory domain", __func__); goto err; } } else if (reg_domain->oper == WIFI_MGMT_GET) { if (!reg_domain->chan_info) { LOG_ERR("%s: Invalid regulatory info (NULL)\n", __func__); goto err; } status = nrf_wifi_fmac_get_reg(fmac_dev_ctx, &reg_domain_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Failed to get regulatory domain", __func__); goto err; } memcpy(reg_domain->country_code, reg_domain_info.alpha2, WIFI_COUNTRY_CODE_LEN); reg_domain->num_channels = reg_domain_info.reg_chan_count; for (chan_idx = 0; chan_idx < reg_domain_info.reg_chan_count; chan_idx++) { chan_info = &(reg_domain->chan_info[chan_idx]); reg_domain_chan_info = &(reg_domain_info.reg_chan_info[chan_idx]); chan_info->center_frequency = reg_domain_chan_info->center_frequency; chan_info->dfs = !!reg_domain_chan_info->dfs; chan_info->max_power = reg_domain_chan_info->max_power; chan_info->passive_only = !!reg_domain_chan_info->passive_channel; chan_info->supported = !!reg_domain_chan_info->supported; } } else { LOG_ERR("%s: Invalid operation: %d", __func__, reg_domain->oper); goto err; } ret = 0; err: k_mutex_unlock(&reg_lock); return ret; } #ifdef CONFIG_NRF70_STA_MODE void nrf_wifi_event_proc_cookie_rsp(void *vif_ctx, struct nrf_wifi_umac_event_cookie_rsp *cookie_rsp_event, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; vif_ctx_zep = vif_ctx; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; LOG_DBG("%s: cookie_rsp_event->cookie = %llx", __func__, cookie_rsp_event->cookie); LOG_DBG("%s: host_cookie = %llx", __func__, cookie_rsp_event->host_cookie); LOG_DBG("%s: mac_addr = %x:%x:%x:%x:%x:%x", __func__, cookie_rsp_event->mac_addr[0], cookie_rsp_event->mac_addr[1], cookie_rsp_event->mac_addr[2], cookie_rsp_event->mac_addr[3], cookie_rsp_event->mac_addr[4], cookie_rsp_event->mac_addr[5]); vif_ctx_zep->cookie_resp_received = true; /* TODO: When supp_callbk_fns.mgmt_tx_status is implemented, add logic * here to use the cookie and host_cookie to map requests to responses. */ } #endif /* CONFIG_NRF70_STA_MODE */ void reg_change_callbk_fn(void *vif_ctx, struct nrf_wifi_event_regulatory_change *reg_change_event, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; vif_ctx_zep = vif_ctx; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; if (!fmac_dev_ctx) { LOG_ERR("%s: fmac_dev_ctx is NULL", __func__); return; } fmac_dev_ctx->reg_change = k_malloc(sizeof(struct nrf_wifi_event_regulatory_change)); if (!fmac_dev_ctx->reg_change) { LOG_ERR("%s: Failed to allocate memory for reg_change", __func__); return; } memcpy(fmac_dev_ctx->reg_change, reg_change_event, sizeof(struct nrf_wifi_event_regulatory_change)); fmac_dev_ctx->reg_set_status = true; } #endif /* !CONFIG_NRF70_RADIO_TEST */ /* DTS uses 1dBm as the unit for TX power, while the RPU uses 0.25dBm */ #define MAX_TX_PWR(label) DT_PROP(DT_NODELABEL(nrf70), label) * 4 void configure_tx_pwr_settings(struct nrf_wifi_tx_pwr_ctrl_params *tx_pwr_ctrl_params, struct nrf_wifi_tx_pwr_ceil_params *tx_pwr_ceil_params) { tx_pwr_ctrl_params->ant_gain_2g = CONFIG_NRF70_ANT_GAIN_2G; tx_pwr_ctrl_params->ant_gain_5g_band1 = CONFIG_NRF70_ANT_GAIN_5G_BAND1; tx_pwr_ctrl_params->ant_gain_5g_band2 = CONFIG_NRF70_ANT_GAIN_5G_BAND2; tx_pwr_ctrl_params->ant_gain_5g_band3 = CONFIG_NRF70_ANT_GAIN_5G_BAND3; tx_pwr_ctrl_params->band_edge_2g_lo_dss = CONFIG_NRF70_BAND_2G_LOWER_EDGE_BACKOFF_DSSS; tx_pwr_ctrl_params->band_edge_2g_lo_ht = CONFIG_NRF70_BAND_2G_LOWER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_2g_lo_he = CONFIG_NRF70_BAND_2G_LOWER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_2g_hi_dsss = CONFIG_NRF70_BAND_2G_UPPER_EDGE_BACKOFF_DSSS; tx_pwr_ctrl_params->band_edge_2g_hi_ht = CONFIG_NRF70_BAND_2G_UPPER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_2g_hi_he = CONFIG_NRF70_BAND_2G_UPPER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_5g_unii_1_lo_ht = CONFIG_NRF70_BAND_UNII_1_LOWER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_5g_unii_1_lo_he = CONFIG_NRF70_BAND_UNII_1_LOWER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_5g_unii_1_hi_ht = CONFIG_NRF70_BAND_UNII_1_UPPER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_5g_unii_1_hi_he = CONFIG_NRF70_BAND_UNII_1_UPPER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_5g_unii_2a_lo_ht = CONFIG_NRF70_BAND_UNII_2A_LOWER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_5g_unii_2a_lo_he = CONFIG_NRF70_BAND_UNII_2A_LOWER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_5g_unii_2a_hi_ht = CONFIG_NRF70_BAND_UNII_2A_UPPER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_5g_unii_2a_hi_he = CONFIG_NRF70_BAND_UNII_2A_UPPER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_5g_unii_2c_lo_ht = CONFIG_NRF70_BAND_UNII_2C_LOWER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_5g_unii_2c_lo_he = CONFIG_NRF70_BAND_UNII_2C_LOWER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_5g_unii_2c_hi_ht = CONFIG_NRF70_BAND_UNII_2C_UPPER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_5g_unii_2c_hi_he = CONFIG_NRF70_BAND_UNII_2C_UPPER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_5g_unii_3_lo_ht = CONFIG_NRF70_BAND_UNII_3_LOWER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_5g_unii_3_lo_he = CONFIG_NRF70_BAND_UNII_3_LOWER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_5g_unii_3_hi_ht = CONFIG_NRF70_BAND_UNII_3_UPPER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_5g_unii_3_hi_he = CONFIG_NRF70_BAND_UNII_3_UPPER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_5g_unii_4_lo_ht = CONFIG_NRF70_BAND_UNII_4_LOWER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_5g_unii_4_lo_he = CONFIG_NRF70_BAND_UNII_4_LOWER_EDGE_BACKOFF_HE; tx_pwr_ctrl_params->band_edge_5g_unii_4_hi_ht = CONFIG_NRF70_BAND_UNII_4_UPPER_EDGE_BACKOFF_HT; tx_pwr_ctrl_params->band_edge_5g_unii_4_hi_he = CONFIG_NRF70_BAND_UNII_4_UPPER_EDGE_BACKOFF_HE; tx_pwr_ceil_params->max_pwr_2g_dsss = MAX_TX_PWR(wifi_max_tx_pwr_2g_dsss); tx_pwr_ceil_params->max_pwr_2g_mcs7 = MAX_TX_PWR(wifi_max_tx_pwr_2g_mcs7); tx_pwr_ceil_params->max_pwr_2g_mcs0 = MAX_TX_PWR(wifi_max_tx_pwr_2g_mcs0); #ifndef CONFIG_NRF70_2_4G_ONLY tx_pwr_ceil_params->max_pwr_5g_low_mcs7 = MAX_TX_PWR(wifi_max_tx_pwr_5g_low_mcs7); tx_pwr_ceil_params->max_pwr_5g_mid_mcs7 = MAX_TX_PWR(wifi_max_tx_pwr_5g_mid_mcs7); tx_pwr_ceil_params->max_pwr_5g_high_mcs7 = MAX_TX_PWR(wifi_max_tx_pwr_5g_high_mcs7); tx_pwr_ceil_params->max_pwr_5g_low_mcs0 = MAX_TX_PWR(wifi_max_tx_pwr_5g_low_mcs0); tx_pwr_ceil_params->max_pwr_5g_mid_mcs0 = MAX_TX_PWR(wifi_max_tx_pwr_5g_mid_mcs0); tx_pwr_ceil_params->max_pwr_5g_high_mcs0 = MAX_TX_PWR(wifi_max_tx_pwr_5g_high_mcs0); #endif /* CONFIG_NRF70_2_4G_ONLY */ } void configure_board_dep_params(struct nrf_wifi_board_params *board_params) { board_params->pcb_loss_2g = CONFIG_NRF70_PCB_LOSS_2G; #ifndef CONFIG_NRF70_2_4G_ONLY board_params->pcb_loss_5g_band1 = CONFIG_NRF70_PCB_LOSS_5G_BAND1; board_params->pcb_loss_5g_band2 = CONFIG_NRF70_PCB_LOSS_5G_BAND2; board_params->pcb_loss_5g_band3 = CONFIG_NRF70_PCB_LOSS_5G_BAND3; #endif /* CONFIG_NRF70_2_4G_ONLY */ } enum nrf_wifi_status nrf_wifi_fmac_dev_add_zep(struct nrf_wifi_drv_priv_zep *drv_priv_zep) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; void *rpu_ctx = NULL; enum op_band op_band = CONFIG_NRF_WIFI_OP_BAND; #ifdef CONFIG_NRF_WIFI_LOW_POWER int sleep_type = -1; #ifndef CONFIG_NRF70_RADIO_TEST sleep_type = HW_SLEEP_ENABLE; #else sleep_type = SLEEP_DISABLE; #endif /* CONFIG_NRF70_RADIO_TEST */ #endif /* CONFIG_NRF_WIFI_LOW_POWER */ struct nrf_wifi_tx_pwr_ctrl_params tx_pwr_ctrl_params; struct nrf_wifi_tx_pwr_ceil_params tx_pwr_ceil_params; struct nrf_wifi_board_params board_params; unsigned int fw_ver = 0; rpu_ctx_zep = &drv_priv_zep->rpu_ctx_zep; rpu_ctx_zep->drv_priv_zep = drv_priv_zep; rpu_ctx = nrf_wifi_fmac_dev_add(drv_priv_zep->fmac_priv, rpu_ctx_zep); if (!rpu_ctx) { LOG_ERR("%s: nrf_wifi_fmac_dev_add failed", __func__); rpu_ctx_zep = NULL; goto err; } rpu_ctx_zep->rpu_ctx = rpu_ctx; status = nrf_wifi_fw_load(rpu_ctx); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fw_load failed", __func__); goto err; } status = nrf_wifi_fmac_ver_get(rpu_ctx, &fw_ver); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: FW version read failed", __func__); goto err; } LOG_DBG("Firmware (v%d.%d.%d.%d) booted successfully", NRF_WIFI_UMAC_VER(fw_ver), NRF_WIFI_UMAC_VER_MAJ(fw_ver), NRF_WIFI_UMAC_VER_MIN(fw_ver), NRF_WIFI_UMAC_VER_EXTRA(fw_ver)); configure_tx_pwr_settings(&tx_pwr_ctrl_params, &tx_pwr_ceil_params); configure_board_dep_params(&board_params); #ifdef CONFIG_NRF70_RADIO_TEST status = nrf_wifi_fmac_dev_init_rt(rpu_ctx_zep->rpu_ctx, #ifdef CONFIG_NRF_WIFI_LOW_POWER sleep_type, #endif /* CONFIG_NRF_WIFI_LOW_POWER */ NRF_WIFI_DEF_PHY_CALIB, op_band, IS_ENABLED(CONFIG_NRF_WIFI_BEAMFORMING), &tx_pwr_ctrl_params, &tx_pwr_ceil_params, &board_params); #else status = nrf_wifi_fmac_dev_init(rpu_ctx_zep->rpu_ctx, #ifdef CONFIG_NRF_WIFI_LOW_POWER sleep_type, #endif /* CONFIG_NRF_WIFI_LOW_POWER */ NRF_WIFI_DEF_PHY_CALIB, op_band, IS_ENABLED(CONFIG_NRF_WIFI_BEAMFORMING), &tx_pwr_ctrl_params, &tx_pwr_ceil_params, &board_params); #endif /* CONFIG_NRF70_RADIO_TEST */ if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_dev_init failed", __func__); goto err; } k_mutex_init(&rpu_ctx_zep->rpu_lock); return status; err: if (rpu_ctx) { #ifdef CONFIG_NRF70_RADIO_TEST nrf_wifi_fmac_dev_rem_rt(rpu_ctx); #else nrf_wifi_fmac_dev_rem(rpu_ctx); #endif /* CONFIG_NRF70_RADIO_TEST */ rpu_ctx_zep->rpu_ctx = NULL; } return status; } enum nrf_wifi_status nrf_wifi_fmac_dev_rem_zep(struct nrf_wifi_drv_priv_zep *drv_priv_zep) { struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; rpu_ctx_zep = &drv_priv_zep->rpu_ctx_zep; #ifdef CONFIG_NRF70_RADIO_TEST nrf_wifi_fmac_dev_deinit_rt(rpu_ctx_zep->rpu_ctx); nrf_wifi_fmac_dev_rem_rt(rpu_ctx_zep->rpu_ctx); #else nrf_wifi_fmac_dev_deinit(rpu_ctx_zep->rpu_ctx); nrf_wifi_fmac_dev_rem(rpu_ctx_zep->rpu_ctx); #endif /* CONFIG_NRF70_RADIO_TEST */ k_free(rpu_ctx_zep->extended_capa); rpu_ctx_zep->extended_capa = NULL; k_free(rpu_ctx_zep->extended_capa_mask); rpu_ctx_zep->extended_capa_mask = NULL; rpu_ctx_zep->rpu_ctx = NULL; LOG_DBG("%s: FMAC device removed", __func__); return NRF_WIFI_STATUS_SUCCESS; } static int nrf_wifi_drv_main_zep(const struct device *dev) { #ifndef CONFIG_NRF70_RADIO_TEST struct nrf_wifi_fmac_callbk_fns callbk_fns = { 0 }; struct nrf_wifi_data_config_params data_config = { 0 }; struct rx_buf_pool_params rx_buf_pools[MAX_NUM_OF_RX_QUEUES]; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = dev->data; vif_ctx_zep->rpu_ctx_zep = &rpu_drv_priv_zep.rpu_ctx_zep; #ifdef CONFIG_NRF70_DATA_TX data_config.aggregation = aggregation; data_config.wmm = wmm; data_config.max_num_tx_agg_sessions = max_num_tx_agg_sessions; data_config.max_num_rx_agg_sessions = max_num_rx_agg_sessions; data_config.max_tx_aggregation = max_tx_aggregation; data_config.reorder_buf_size = reorder_buf_size; data_config.max_rxampdu_size = max_rxampdu_size; data_config.rate_protection_type = rate_protection_type; callbk_fns.if_carr_state_chg_callbk_fn = nrf_wifi_if_carr_state_chg; callbk_fns.rx_frm_callbk_fn = nrf_wifi_if_rx_frm; #if defined(CONFIG_NRF70_RAW_DATA_RX) || defined(CONFIG_NRF70_PROMISC_DATA_RX) callbk_fns.rx_sniffer_frm_callbk_fn = nrf_wifi_if_sniffer_rx_frm; #endif /* CONFIG_NRF70_RAW_DATA_RX || CONFIG_NRF70_PROMISC_DATA_RX */ #endif rx_buf_pools[0].num_bufs = rx1_num_bufs; rx_buf_pools[1].num_bufs = rx2_num_bufs; rx_buf_pools[2].num_bufs = rx3_num_bufs; rx_buf_pools[0].buf_sz = rx1_buf_sz; rx_buf_pools[1].buf_sz = rx2_buf_sz; rx_buf_pools[2].buf_sz = rx3_buf_sz; #ifdef CONFIG_NRF_WIFI_RPU_RECOVERY callbk_fns.rpu_recovery_callbk_fn = nrf_wifi_rpu_recovery_cb; #endif /* CONFIG_NRF_WIFI_RPU_RECOVERY */ callbk_fns.scan_start_callbk_fn = nrf_wifi_event_proc_scan_start_zep; callbk_fns.scan_done_callbk_fn = nrf_wifi_event_proc_scan_done_zep; callbk_fns.reg_change_callbk_fn = reg_change_callbk_fn; #ifdef CONFIG_NET_L2_WIFI_MGMT callbk_fns.disp_scan_res_callbk_fn = nrf_wifi_event_proc_disp_scan_res_zep; #endif /* CONFIG_NET_L2_WIFI_MGMT */ #ifdef CONFIG_WIFI_MGMT_RAW_SCAN_RESULTS callbk_fns.rx_bcn_prb_resp_callbk_fn = nrf_wifi_rx_bcn_prb_resp_frm; #endif /* CONFIG_WIFI_MGMT_RAW_SCAN_RESULTS */ #if defined(CONFIG_NRF70_SYSTEM_MODE) || defined(CONFIG_NRF70_SYSTEM_WITH_RAW_MODES) callbk_fns.set_if_callbk_fn = nrf_wifi_set_iface_event_handler; #endif /* CONFIG_NRF70_SYSTEM_MODE */ #ifdef CONFIG_NRF70_STA_MODE callbk_fns.twt_config_callbk_fn = nrf_wifi_event_proc_twt_setup_zep; callbk_fns.twt_teardown_callbk_fn = nrf_wifi_event_proc_twt_teardown_zep; callbk_fns.twt_sleep_callbk_fn = nrf_wifi_event_proc_twt_sleep_zep; callbk_fns.event_get_reg = nrf_wifi_event_get_reg_zep; callbk_fns.event_get_ps_info = nrf_wifi_event_proc_get_power_save_info; callbk_fns.cookie_rsp_callbk_fn = nrf_wifi_event_proc_cookie_rsp; callbk_fns.process_rssi_from_rx = nrf_wifi_process_rssi_from_rx; callbk_fns.scan_res_callbk_fn = nrf_wifi_wpa_supp_event_proc_scan_res; callbk_fns.auth_resp_callbk_fn = nrf_wifi_wpa_supp_event_proc_auth_resp; callbk_fns.assoc_resp_callbk_fn = nrf_wifi_wpa_supp_event_proc_assoc_resp; callbk_fns.deauth_callbk_fn = nrf_wifi_wpa_supp_event_proc_deauth; callbk_fns.disassoc_callbk_fn = nrf_wifi_wpa_supp_event_proc_disassoc; callbk_fns.get_station_callbk_fn = nrf_wifi_wpa_supp_event_proc_get_sta; callbk_fns.get_interface_callbk_fn = nrf_wifi_wpa_supp_event_proc_get_if; callbk_fns.mgmt_tx_status = nrf_wifi_wpa_supp_event_mgmt_tx_status; callbk_fns.unprot_mlme_mgmt_rx_callbk_fn = nrf_wifi_wpa_supp_event_proc_unprot_mgmt; callbk_fns.event_get_wiphy = nrf_wifi_wpa_supp_event_get_wiphy; callbk_fns.mgmt_rx_callbk_fn = nrf_wifi_wpa_supp_event_mgmt_rx_callbk_fn; callbk_fns.get_conn_info_callbk_fn = nrf_wifi_supp_event_proc_get_conn_info; #endif /* CONFIG_NRF70_STA_MODE */ rpu_drv_priv_zep.fmac_priv = nrf_wifi_fmac_init(&data_config, rx_buf_pools, &callbk_fns); #else /* !CONFIG_NRF70_RADIO_TEST */ enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; rpu_drv_priv_zep.fmac_priv = nrf_wifi_fmac_init_rt(); #endif /* CONFIG_NRF70_RADIO_TEST */ if (rpu_drv_priv_zep.fmac_priv == NULL) { LOG_ERR("%s: nrf_wifi_fmac_init failed", __func__); goto err; } #ifdef CONFIG_NRF70_DATA_TX struct nrf_wifi_fmac_priv_def *def_priv = NULL; def_priv = wifi_fmac_priv(rpu_drv_priv_zep.fmac_priv); def_priv->max_ampdu_len_per_token = (RPU_PKTRAM_SIZE - (CONFIG_NRF70_RX_NUM_BUFS * CONFIG_NRF70_RX_MAX_DATA_SIZE)) / CONFIG_NRF70_MAX_TX_TOKENS; /* Align to 4-byte */ def_priv->max_ampdu_len_per_token &= ~0x3; /* Alignment overhead for size based coalesce */ def_priv->avail_ampdu_len_per_token = def_priv->max_ampdu_len_per_token - (MAX_PKT_RAM_TX_ALIGN_OVERHEAD * max_tx_aggregation); #endif /* CONFIG_NRF70_DATA_TX */ #ifdef CONFIG_NRF70_RADIO_TEST status = nrf_wifi_fmac_dev_add_zep(&rpu_drv_priv_zep); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_dev_add_zep failed", __func__); goto fmac_deinit; } #else k_work_init_delayable(&vif_ctx_zep->scan_timeout_work, nrf_wifi_scan_timeout_work); #endif /* CONFIG_NRF70_RADIO_TEST */ return 0; #ifdef CONFIG_NRF70_RADIO_TEST fmac_deinit: nrf_wifi_fmac_deinit_rt(rpu_drv_priv_zep.fmac_priv); #endif /* CONFIG_NRF70_RADIO_TEST */ err: return -1; } #ifndef CONFIG_NRF70_RADIO_TEST #ifdef CONFIG_NET_L2_WIFI_MGMT static struct wifi_mgmt_ops nrf_wifi_mgmt_ops = { .scan = nrf_wifi_disp_scan_zep, #ifdef CONFIG_NET_STATISTICS_WIFI .get_stats = nrf_wifi_stats_get, #endif /* CONFIG_NET_STATISTICS_WIFI */ #ifdef CONFIG_NRF70_STA_MODE .set_power_save = nrf_wifi_set_power_save, .set_twt = nrf_wifi_set_twt, .reg_domain = nrf_wifi_reg_domain, .get_power_save_config = nrf_wifi_get_power_save_config, .set_rts_threshold = nrf_wifi_set_rts_threshold, #endif /* CONFIG_NRF70_STA_MODE */ #ifdef CONFIG_NRF70_SYSTEM_WITH_RAW_MODES .mode = nrf_wifi_mode, #endif #if defined(CONFIG_NRF70_RAW_DATA_TX) || defined(CONFIG_NRF70_RAW_DATA_RX) .channel = nrf_wifi_channel, #endif /* CONFIG_NRF70_RAW_DATA_TX || CONFIG_NRF70_RAW_DATA_RX */ #if defined(CONFIG_NRF70_RAW_DATA_RX) || defined(CONFIG_NRF70_PROMISC_DATA_RX) .filter = nrf_wifi_filter, #endif /* CONFIG_NRF70_RAW_DATA_RX || CONFIG_NRF70_PROMISC_DATA_RX */ }; #endif /* CONFIG_NET_L2_WIFI_MGMT */ #ifdef CONFIG_NRF70_STA_MODE static struct zep_wpa_supp_dev_ops wpa_supp_ops = { .init = nrf_wifi_wpa_supp_dev_init, .deinit = nrf_wifi_wpa_supp_dev_deinit, .scan2 = nrf_wifi_wpa_supp_scan2, .scan_abort = nrf_wifi_wpa_supp_scan_abort, .get_scan_results2 = nrf_wifi_wpa_supp_scan_results_get, .deauthenticate = nrf_wifi_wpa_supp_deauthenticate, .authenticate = nrf_wifi_wpa_supp_authenticate, .associate = nrf_wifi_wpa_supp_associate, .set_supp_port = nrf_wifi_wpa_set_supp_port, .set_key = nrf_wifi_wpa_supp_set_key, .signal_poll = nrf_wifi_wpa_supp_signal_poll, .send_mlme = nrf_wifi_nl80211_send_mlme, .get_wiphy = nrf_wifi_supp_get_wiphy, .register_frame = nrf_wifi_supp_register_frame, .get_capa = nrf_wifi_supp_get_capa, .get_conn_info = nrf_wifi_supp_get_conn_info, #ifdef CONFIG_NRF70_AP_MODE .init_ap = nrf_wifi_wpa_supp_init_ap, .start_ap = nrf_wifi_wpa_supp_start_ap, .change_beacon = nrf_wifi_wpa_supp_change_beacon, .stop_ap = nrf_wifi_wpa_supp_stop_ap, .deinit_ap = nrf_wifi_wpa_supp_deinit_ap, .sta_add = nrf_wifi_wpa_supp_sta_add, .sta_remove = nrf_wifi_wpa_supp_sta_remove, .register_mgmt_frame = nrf_wifi_supp_register_mgmt_frame, .sta_set_flags = nrf_wifi_wpa_supp_sta_set_flags, .get_inact_sec = nrf_wifi_wpa_supp_sta_get_inact_sec, #endif /* CONFIG_NRF70_AP_MODE */ }; #endif /* CONFIG_NRF70_STA_MODE */ #endif /* !CONFIG_NRF70_RADIO_TEST */ #ifdef CONFIG_NET_L2_ETHERNET static const struct net_wifi_mgmt_offload wifi_offload_ops = { .wifi_iface.iface_api.init = nrf_wifi_if_init_zep, .wifi_iface.start = nrf_wifi_if_start_zep, .wifi_iface.stop = nrf_wifi_if_stop_zep, .wifi_iface.set_config = nrf_wifi_if_set_config_zep, .wifi_iface.get_config = nrf_wifi_if_get_config_zep, .wifi_iface.get_capabilities = nrf_wifi_if_caps_get, .wifi_iface.send = nrf_wifi_if_send, #ifdef CONFIG_NET_STATISTICS_ETHERNET .wifi_iface.get_stats = nrf_wifi_eth_stats_get, #endif /* CONFIG_NET_STATISTICS_ETHERNET */ #ifdef CONFIG_NET_L2_WIFI_MGMT .wifi_mgmt_api = &nrf_wifi_mgmt_ops, #endif /* CONFIG_NET_L2_WIFI_MGMT */ #ifdef CONFIG_NRF70_STA_MODE .wifi_drv_ops = &wpa_supp_ops, #endif /* CONFIG_NRF70_STA_MODE */ }; #endif /* CONFIG_NET_L2_ETHERNET */ #ifdef CONFIG_NET_L2_ETHERNET ETH_NET_DEVICE_DT_INST_DEFINE(0, nrf_wifi_drv_main_zep, /* init_fn */ NULL, /* pm_action_cb */ &rpu_drv_priv_zep.rpu_ctx_zep.vif_ctx_zep[0], /* data */ #ifdef CONFIG_NRF70_STA_MODE &wpa_supp_ops, /* cfg */ #else /* CONFIG_NRF70_STA_MODE */ NULL, /* cfg */ #endif /* !CONFIG_NRF70_STA_MODE */ CONFIG_WIFI_INIT_PRIORITY, /* prio */ &wifi_offload_ops, /* api */ CONFIG_NRF_WIFI_IFACE_MTU); /*mtu */ #else DEVICE_DT_INST_DEFINE(0, nrf_wifi_drv_main_zep, /* init_fn */ NULL, /* pm_action_cb */ #ifndef CONFIG_NRF70_RADIO_TEST &rpu_drv_priv_zep, /* data */ #else /* !CONFIG_NRF70_RADIO_TEST */ NULL, #endif /* CONFIG_NRF70_RADIO_TEST */ NULL, /* cfg */ POST_KERNEL, CONFIG_WIFI_INIT_PRIORITY, /* prio */ NULL); /* api */ #endif /* CONFIG_NRF70_STA_MODE */ #ifdef CONFIG_NET_CONNECTION_MANAGER_CONNECTIVITY_WIFI_MGMT CONNECTIVITY_WIFI_MGMT_BIND(Z_DEVICE_DT_DEV_ID(DT_DRV_INST(0))); #endif /* CONFIG_NET_CONNECTION_MANAGER_CONNECTIVITY_WIFI_MGMT */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/fmac_main.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
9,483
```objective-c /* * */ /* @file * @brief nRF Wi-Fi radio-test mode shell module */ #include <zephyr/kernel.h> #include <stdio.h> #include <stdlib.h> #include <zephyr/shell/shell.h> #include <zephyr/init.h> #include <ctype.h> #include <host_rpu_sys_if.h> #include <fmac_structs.h> #include <queue.h> struct nrf_wifi_ctx_zep_rt { struct nrf_wifi_fmac_priv *fmac_priv; struct rpu_conf_params conf_params; }; ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/wifi_util.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
116
```objective-c /* * */ /** * @brief Header containing timer specific declarations for the * Zephyr OS layer of the Wi-Fi driver. */ #ifndef __TIMER_H__ #define __TIMER_H__ struct timer_list { void (*function)(unsigned long data); unsigned long data; struct k_work_delayable work; }; void init_timer(struct timer_list *timer); void mod_timer(struct timer_list *timer, int msec); void del_timer_sync(struct timer_list *timer); #endif /* __TIMER_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/timer.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
101
```c /* * */ /** * @brief Header containing OS specific definitions for the * Zephyr OS layer of the Wi-Fi driver. */ #include <stdio.h> #include <string.h> #include <sys/time.h> #include <zephyr/kernel.h> #include <zephyr/sys/printk.h> #include <zephyr/drivers/gpio.h> #include <zephyr/logging/log.h> #include <zephyr/sys/__assert.h> #include "rpu_hw_if.h" #include "shim.h" #include "work.h" #include "timer.h" #include "osal_ops.h" #include "qspi_if.h" LOG_MODULE_REGISTER(wifi_nrf, CONFIG_WIFI_NRF70_LOG_LEVEL); struct zep_shim_intr_priv *intr_priv; static void *zep_shim_mem_alloc(size_t size) { size_t size_aligned = ROUND_UP(size, 4); return k_malloc(size_aligned); } static void *zep_shim_mem_zalloc(size_t size) { size_t size_aligned = ROUND_UP(size, 4); return k_calloc(size_aligned, sizeof(char)); } static void *zep_shim_mem_cpy(void *dest, const void *src, size_t count) { return memcpy(dest, src, count); } static void *zep_shim_mem_set(void *start, int val, size_t size) { return memset(start, val, size); } static int zep_shim_mem_cmp(const void *addr1, const void *addr2, size_t size) { return memcmp(addr1, addr2, size); } static unsigned int zep_shim_qspi_read_reg32(void *priv, unsigned long addr) { unsigned int val; struct zep_shim_bus_qspi_priv *qspi_priv = priv; struct qspi_dev *dev; dev = qspi_priv->qspi_dev; if (addr < 0x0C0000) { dev->hl_read(addr, &val, 4); } else { dev->read(addr, &val, 4); } return val; } static void zep_shim_qspi_write_reg32(void *priv, unsigned long addr, unsigned int val) { struct zep_shim_bus_qspi_priv *qspi_priv = priv; struct qspi_dev *dev; dev = qspi_priv->qspi_dev; dev->write(addr, &val, 4); } static void zep_shim_qspi_cpy_from(void *priv, void *dest, unsigned long addr, size_t count) { struct zep_shim_bus_qspi_priv *qspi_priv = priv; struct qspi_dev *dev; size_t count_aligned = ROUND_UP(count, 4); dev = qspi_priv->qspi_dev; if (addr < 0x0C0000) { dev->hl_read(addr, dest, count_aligned); } else { dev->read(addr, dest, count_aligned); } } static void zep_shim_qspi_cpy_to(void *priv, unsigned long addr, const void *src, size_t count) { struct zep_shim_bus_qspi_priv *qspi_priv = priv; struct qspi_dev *dev; size_t count_aligned = ROUND_UP(count, 4); dev = qspi_priv->qspi_dev; dev->write(addr, src, count_aligned); } static void *zep_shim_spinlock_alloc(void) { struct k_sem *lock = NULL; lock = k_malloc(sizeof(*lock)); if (!lock) { LOG_ERR("%s: Unable to allocate memory for spinlock", __func__); } return lock; } static void zep_shim_spinlock_free(void *lock) { k_free(lock); } static void zep_shim_spinlock_init(void *lock) { k_sem_init(lock, 1, 1); } static void zep_shim_spinlock_take(void *lock) { k_sem_take(lock, K_FOREVER); } static void zep_shim_spinlock_rel(void *lock) { k_sem_give(lock); } static void zep_shim_spinlock_irq_take(void *lock, unsigned long *flags) { k_sem_take(lock, K_FOREVER); } static void zep_shim_spinlock_irq_rel(void *lock, unsigned long *flags) { k_sem_give(lock); } static int zep_shim_pr_dbg(const char *fmt, va_list args) { static char buf[80]; vsnprintf(buf, sizeof(buf), fmt, args); LOG_DBG("%s", buf); return 0; } static int zep_shim_pr_info(const char *fmt, va_list args) { static char buf[80]; vsnprintf(buf, sizeof(buf), fmt, args); LOG_INF("%s", buf); return 0; } static int zep_shim_pr_err(const char *fmt, va_list args) { static char buf[256]; vsnprintf(buf, sizeof(buf), fmt, args); LOG_ERR("%s", buf); return 0; } struct nwb { unsigned char *data; unsigned char *tail; int len; int headroom; void *next; void *priv; int iftype; void *ifaddr; void *dev; int hostbuffer; void *cleanup_ctx; void (*cleanup_cb)(); unsigned char priority; bool chksum_done; }; static void *zep_shim_nbuf_alloc(unsigned int size) { struct nwb *nbuff; nbuff = (struct nwb *)k_calloc(sizeof(struct nwb), sizeof(char)); if (!nbuff) return NULL; nbuff->priv = k_calloc(size, sizeof(char)); if (!nbuff->priv) { k_free(nbuff); return NULL; } nbuff->data = (unsigned char *)nbuff->priv; nbuff->tail = nbuff->data; nbuff->len = 0; nbuff->headroom = 0; nbuff->next = NULL; return nbuff; } static void zep_shim_nbuf_free(void *nbuf) { k_free(((struct nwb *)nbuf)->priv); k_free(nbuf); } static void zep_shim_nbuf_headroom_res(void *nbuf, unsigned int size) { struct nwb *nwb = (struct nwb *)nbuf; nwb->data += size; nwb->tail += size; nwb->headroom += size; } static unsigned int zep_shim_nbuf_headroom_get(void *nbuf) { return ((struct nwb *)nbuf)->headroom; } static unsigned int zep_shim_nbuf_data_size(void *nbuf) { return ((struct nwb *)nbuf)->len; } static void *zep_shim_nbuf_data_get(void *nbuf) { return ((struct nwb *)nbuf)->data; } static void *zep_shim_nbuf_data_put(void *nbuf, unsigned int size) { struct nwb *nwb = (struct nwb *)nbuf; unsigned char *data = nwb->tail; nwb->tail += size; nwb->len += size; return data; } static void *zep_shim_nbuf_data_push(void *nbuf, unsigned int size) { struct nwb *nwb = (struct nwb *)nbuf; nwb->data -= size; nwb->headroom -= size; nwb->len += size; return nwb->data; } static void *zep_shim_nbuf_data_pull(void *nbuf, unsigned int size) { struct nwb *nwb = (struct nwb *)nbuf; nwb->data += size; nwb->headroom += size; nwb->len -= size; return nwb->data; } static unsigned char zep_shim_nbuf_get_priority(void *nbuf) { struct nwb *nwb = (struct nwb *)nbuf; return nwb->priority; } static unsigned char zep_shim_nbuf_get_chksum_done(void *nbuf) { struct nwb *nwb = (struct nwb *)nbuf; return nwb->chksum_done; } static void zep_shim_nbuf_set_chksum_done(void *nbuf, unsigned char chksum_done) { struct nwb *nwb = (struct nwb *)nbuf; nwb->chksum_done = (bool)chksum_done; } #include <zephyr/net/ethernet.h> #include <zephyr/net/net_core.h> void *net_pkt_to_nbuf(struct net_pkt *pkt) { struct nwb *nbuff; unsigned char *data; unsigned int len; len = net_pkt_get_len(pkt); nbuff = zep_shim_nbuf_alloc(len + 100); if (!nbuff) { return NULL; } zep_shim_nbuf_headroom_res(nbuff, 100); data = zep_shim_nbuf_data_put(nbuff, len); net_pkt_read(pkt, data, len); nbuff->priority = net_pkt_priority(pkt); nbuff->chksum_done = (bool)net_pkt_is_chksum_done(pkt); return nbuff; } void *net_pkt_from_nbuf(void *iface, void *frm) { struct net_pkt *pkt = NULL; unsigned char *data; unsigned int len; struct nwb *nwb = frm; if (!nwb) { return NULL; } len = zep_shim_nbuf_data_size(nwb); data = zep_shim_nbuf_data_get(nwb); pkt = net_pkt_rx_alloc_with_buffer(iface, len, AF_UNSPEC, 0, K_MSEC(100)); if (!pkt) { goto out; } if (net_pkt_write(pkt, data, len)) { net_pkt_unref(pkt); pkt = NULL; goto out; } out: zep_shim_nbuf_free(nwb); return pkt; } #if defined(CONFIG_NRF70_RAW_DATA_RX) || defined(CONFIG_NRF70_PROMISC_DATA_RX) void *net_raw_pkt_from_nbuf(void *iface, void *frm, unsigned short raw_hdr_len, void *raw_rx_hdr, bool pkt_free) { struct net_pkt *pkt = NULL; unsigned char *nwb_data; unsigned char *data = NULL; unsigned int nwb_len; unsigned int total_len; struct nwb *nwb = frm; if (!nwb) { LOG_ERR("%s: Received network buffer is NULL", __func__); return NULL; } nwb_len = zep_shim_nbuf_data_size(nwb); nwb_data = zep_shim_nbuf_data_get(nwb); total_len = raw_hdr_len + nwb_len; data = (unsigned char *)k_malloc(total_len); if (!data) { LOG_ERR("%s: Unable to allocate memory for sniffer data packet", __func__); goto out; } pkt = net_pkt_rx_alloc_with_buffer(iface, total_len, AF_PACKET, ETH_P_ALL, K_MSEC(100)); if (!pkt) { LOG_ERR("%s: Unable to allocate net packet buffer", __func__); goto out; } memcpy(data, raw_rx_hdr, raw_hdr_len); memcpy((data+raw_hdr_len), nwb_data, nwb_len); if (net_pkt_write(pkt, data, total_len)) { net_pkt_unref(pkt); pkt = NULL; goto out; } out: if (data != NULL) { k_free(data); } if (pkt_free) { zep_shim_nbuf_free(nwb); } return pkt; } #endif /* CONFIG_NRF70_RAW_DATA_RX || CONFIG_NRF70_PROMISC_DATA_RX */ static void *zep_shim_llist_node_alloc(void) { struct zep_shim_llist_node *llist_node = NULL; llist_node = k_calloc(sizeof(*llist_node), sizeof(char)); if (!llist_node) { LOG_ERR("%s: Unable to allocate memory for linked list node", __func__); return NULL; } sys_dnode_init(&llist_node->head); return llist_node; } static void zep_shim_llist_node_free(void *llist_node) { k_free(llist_node); } static void *zep_shim_llist_node_data_get(void *llist_node) { struct zep_shim_llist_node *zep_llist_node = NULL; zep_llist_node = (struct zep_shim_llist_node *)llist_node; return zep_llist_node->data; } static void zep_shim_llist_node_data_set(void *llist_node, void *data) { struct zep_shim_llist_node *zep_llist_node = NULL; zep_llist_node = (struct zep_shim_llist_node *)llist_node; zep_llist_node->data = data; } static void *zep_shim_llist_alloc(void) { struct zep_shim_llist *llist = NULL; llist = k_calloc(sizeof(*llist), sizeof(char)); if (!llist) { LOG_ERR("%s: Unable to allocate memory for linked list", __func__); } return llist; } static void zep_shim_llist_free(void *llist) { k_free(llist); } static void zep_shim_llist_init(void *llist) { struct zep_shim_llist *zep_llist = NULL; zep_llist = (struct zep_shim_llist *)llist; sys_dlist_init(&zep_llist->head); } static void zep_shim_llist_add_node_tail(void *llist, void *llist_node) { struct zep_shim_llist *zep_llist = NULL; struct zep_shim_llist_node *zep_node = NULL; zep_llist = (struct zep_shim_llist *)llist; zep_node = (struct zep_shim_llist_node *)llist_node; sys_dlist_append(&zep_llist->head, &zep_node->head); zep_llist->len += 1; } static void zep_shim_llist_add_node_head(void *llist, void *llist_node) { struct zep_shim_llist *zep_llist = NULL; struct zep_shim_llist_node *zep_node = NULL; zep_llist = (struct zep_shim_llist *)llist; zep_node = (struct zep_shim_llist_node *)llist_node; sys_dlist_prepend(&zep_llist->head, &zep_node->head); zep_llist->len += 1; } static void *zep_shim_llist_get_node_head(void *llist) { struct zep_shim_llist_node *zep_head_node = NULL; struct zep_shim_llist *zep_llist = NULL; zep_llist = (struct zep_shim_llist *)llist; if (!zep_llist->len) { return NULL; } zep_head_node = (struct zep_shim_llist_node *)sys_dlist_peek_head(&zep_llist->head); return zep_head_node; } static void *zep_shim_llist_get_node_nxt(void *llist, void *llist_node) { struct zep_shim_llist_node *zep_node = NULL; struct zep_shim_llist_node *zep_nxt_node = NULL; struct zep_shim_llist *zep_llist = NULL; zep_llist = (struct zep_shim_llist *)llist; zep_node = (struct zep_shim_llist_node *)llist_node; zep_nxt_node = (struct zep_shim_llist_node *)sys_dlist_peek_next(&zep_llist->head, &zep_node->head); return zep_nxt_node; } static void zep_shim_llist_del_node(void *llist, void *llist_node) { struct zep_shim_llist_node *zep_node = NULL; struct zep_shim_llist *zep_llist = NULL; zep_llist = (struct zep_shim_llist *)llist; zep_node = (struct zep_shim_llist_node *)llist_node; sys_dlist_remove(&zep_node->head); zep_llist->len -= 1; } static unsigned int zep_shim_llist_len(void *llist) { struct zep_shim_llist *zep_llist = NULL; zep_llist = (struct zep_shim_llist *)llist; return zep_llist->len; } static void *zep_shim_work_alloc(int type) { return work_alloc(type); } static void zep_shim_work_free(void *item) { return work_free(item); } static void zep_shim_work_init(void *item, void (*callback)(unsigned long data), unsigned long data) { work_init(item, callback, data); } static void zep_shim_work_schedule(void *item) { work_schedule(item); } static void zep_shim_work_kill(void *item) { work_kill(item); } static unsigned long zep_shim_time_get_curr_us(void) { return k_uptime_get() * USEC_PER_MSEC; } static unsigned int zep_shim_time_elapsed_us(unsigned long start_time_us) { unsigned long curr_time_us = 0; curr_time_us = zep_shim_time_get_curr_us(); return curr_time_us - start_time_us; } static enum nrf_wifi_status zep_shim_bus_qspi_dev_init(void *os_qspi_dev_ctx) { ARG_UNUSED(os_qspi_dev_ctx); return NRF_WIFI_STATUS_SUCCESS; } static void zep_shim_bus_qspi_dev_deinit(void *priv) { struct zep_shim_bus_qspi_priv *qspi_priv = priv; volatile struct qspi_dev *dev = qspi_priv->qspi_dev; dev->deinit(); } static void *zep_shim_bus_qspi_dev_add(void *os_qspi_priv, void *osal_qspi_dev_ctx) { struct zep_shim_bus_qspi_priv *zep_qspi_priv = os_qspi_priv; struct qspi_dev *dev = qspi_dev(); int ret; enum nrf_wifi_status status; ret = rpu_init(); if (ret) { LOG_ERR("%s: RPU init failed with error %d", __func__, ret); return NULL; } status = dev->init(qspi_defconfig()); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: QSPI device init failed", __func__); return NULL; } ret = rpu_enable(); if (ret) { LOG_ERR("%s: RPU enable failed with error %d", __func__, ret); return NULL; } zep_qspi_priv->qspi_dev = dev; zep_qspi_priv->dev_added = true; return zep_qspi_priv; } static void zep_shim_bus_qspi_dev_rem(void *priv) { struct zep_shim_bus_qspi_priv *qspi_priv = priv; struct qspi_dev *dev = qspi_priv->qspi_dev; ARG_UNUSED(dev); /* TODO: Make qspi_dev a dynamic instance and remove it here */ rpu_disable(); } static void *zep_shim_bus_qspi_init(void) { struct zep_shim_bus_qspi_priv *qspi_priv = NULL; qspi_priv = k_calloc(sizeof(*qspi_priv), sizeof(char)); if (!qspi_priv) { LOG_ERR("%s: Unable to allocate memory for qspi_priv", __func__); goto out; } out: return qspi_priv; } static void zep_shim_bus_qspi_deinit(void *os_qspi_priv) { struct zep_shim_bus_qspi_priv *qspi_priv = NULL; qspi_priv = os_qspi_priv; k_free(qspi_priv); } #ifdef CONFIG_NRF_WIFI_LOW_POWER static int zep_shim_bus_qspi_ps_sleep(void *os_qspi_priv) { rpu_sleep(); return 0; } static int zep_shim_bus_qspi_ps_wake(void *os_qspi_priv) { rpu_wakeup(); return 0; } static int zep_shim_bus_qspi_ps_status(void *os_qspi_priv) { return rpu_sleep_status(); } #endif /* CONFIG_NRF_WIFI_LOW_POWER */ static void zep_shim_bus_qspi_dev_host_map_get(void *os_qspi_dev_ctx, struct nrf_wifi_osal_host_map *host_map) { if (!os_qspi_dev_ctx || !host_map) { LOG_ERR("%s: Invalid parameters", __func__); return; } host_map->addr = 0; } static void irq_work_handler(struct k_work *work) { int ret = 0; ret = intr_priv->callbk_fn(intr_priv->callbk_data); if (ret) { LOG_ERR("%s: Interrupt callback failed", __func__); } } extern struct k_work_q zep_wifi_intr_q; static void zep_shim_irq_handler(const struct device *dev, struct gpio_callback *cb, uint32_t pins) { ARG_UNUSED(cb); ARG_UNUSED(pins); k_work_schedule_for_queue(&zep_wifi_intr_q, &intr_priv->work, K_NO_WAIT); } static enum nrf_wifi_status zep_shim_bus_qspi_intr_reg(void *os_dev_ctx, void *callbk_data, int (*callbk_fn)(void *callbk_data)) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int ret = -1; ARG_UNUSED(os_dev_ctx); intr_priv = k_calloc(sizeof(*intr_priv), sizeof(char)); if (!intr_priv) { LOG_ERR("%s: Unable to allocate memory for intr_priv", __func__); goto out; } intr_priv->callbk_data = callbk_data; intr_priv->callbk_fn = callbk_fn; k_work_init_delayable(&intr_priv->work, irq_work_handler); ret = rpu_irq_config(&intr_priv->gpio_cb_data, zep_shim_irq_handler); if (ret) { LOG_ERR("%s: request_irq failed", __func__); k_free(intr_priv); intr_priv = NULL; goto out; } status = NRF_WIFI_STATUS_SUCCESS; out: return status; } static void zep_shim_bus_qspi_intr_unreg(void *os_qspi_dev_ctx) { struct k_work_sync sync; int ret; ARG_UNUSED(os_qspi_dev_ctx); ret = rpu_irq_remove(&intr_priv->gpio_cb_data); if (ret) { LOG_ERR("%s: rpu_irq_remove failed", __func__); return; } k_work_cancel_delayable_sync(&intr_priv->work, &sync); k_free(intr_priv); intr_priv = NULL; } #ifdef CONFIG_NRF_WIFI_LOW_POWER static void *zep_shim_timer_alloc(void) { struct timer_list *timer = NULL; timer = k_malloc(sizeof(*timer)); if (!timer) LOG_ERR("%s: Unable to allocate memory for work", __func__); return timer; } static void zep_shim_timer_init(void *timer, void (*callback)(unsigned long), unsigned long data) { ((struct timer_list *)timer)->function = callback; ((struct timer_list *)timer)->data = data; init_timer(timer); } static void zep_shim_timer_free(void *timer) { k_free(timer); } static void zep_shim_timer_schedule(void *timer, unsigned long duration) { mod_timer(timer, duration); } static void zep_shim_timer_kill(void *timer) { del_timer_sync(timer); } #endif /* CONFIG_NRF_WIFI_LOW_POWER */ static void zep_shim_assert(int test_val, int val, enum nrf_wifi_assert_op_type op, char *msg) { switch (op) { case NRF_WIFI_ASSERT_EQUAL_TO: NET_ASSERT(test_val == val, "%s", msg); break; case NRF_WIFI_ASSERT_NOT_EQUAL_TO: NET_ASSERT(test_val != val, "%s", msg); break; case NRF_WIFI_ASSERT_LESS_THAN: NET_ASSERT(test_val < val, "%s", msg); break; case NRF_WIFI_ASSERT_LESS_THAN_EQUAL_TO: NET_ASSERT(test_val <= val, "%s", msg); break; case NRF_WIFI_ASSERT_GREATER_THAN: NET_ASSERT(test_val > val, "%s", msg); break; case NRF_WIFI_ASSERT_GREATER_THAN_EQUAL_TO: NET_ASSERT(test_val >= val, "%s", msg); break; default: LOG_ERR("%s: Invalid assertion operation", __func__); } } static unsigned int zep_shim_strlen(const void *str) { return strlen(str); } static const struct nrf_wifi_osal_ops nrf_wifi_os_zep_ops = { .mem_alloc = zep_shim_mem_alloc, .mem_zalloc = zep_shim_mem_zalloc, .mem_free = k_free, .mem_cpy = zep_shim_mem_cpy, .mem_set = zep_shim_mem_set, .mem_cmp = zep_shim_mem_cmp, .qspi_read_reg32 = zep_shim_qspi_read_reg32, .qspi_write_reg32 = zep_shim_qspi_write_reg32, .qspi_cpy_from = zep_shim_qspi_cpy_from, .qspi_cpy_to = zep_shim_qspi_cpy_to, .spinlock_alloc = zep_shim_spinlock_alloc, .spinlock_free = zep_shim_spinlock_free, .spinlock_init = zep_shim_spinlock_init, .spinlock_take = zep_shim_spinlock_take, .spinlock_rel = zep_shim_spinlock_rel, .spinlock_irq_take = zep_shim_spinlock_irq_take, .spinlock_irq_rel = zep_shim_spinlock_irq_rel, .log_dbg = zep_shim_pr_dbg, .log_info = zep_shim_pr_info, .log_err = zep_shim_pr_err, .llist_node_alloc = zep_shim_llist_node_alloc, .llist_node_free = zep_shim_llist_node_free, .llist_node_data_get = zep_shim_llist_node_data_get, .llist_node_data_set = zep_shim_llist_node_data_set, .llist_alloc = zep_shim_llist_alloc, .llist_free = zep_shim_llist_free, .llist_init = zep_shim_llist_init, .llist_add_node_tail = zep_shim_llist_add_node_tail, .llist_add_node_head = zep_shim_llist_add_node_head, .llist_get_node_head = zep_shim_llist_get_node_head, .llist_get_node_nxt = zep_shim_llist_get_node_nxt, .llist_del_node = zep_shim_llist_del_node, .llist_len = zep_shim_llist_len, .nbuf_alloc = zep_shim_nbuf_alloc, .nbuf_free = zep_shim_nbuf_free, .nbuf_headroom_res = zep_shim_nbuf_headroom_res, .nbuf_headroom_get = zep_shim_nbuf_headroom_get, .nbuf_data_size = zep_shim_nbuf_data_size, .nbuf_data_get = zep_shim_nbuf_data_get, .nbuf_data_put = zep_shim_nbuf_data_put, .nbuf_data_push = zep_shim_nbuf_data_push, .nbuf_data_pull = zep_shim_nbuf_data_pull, .nbuf_get_priority = zep_shim_nbuf_get_priority, .nbuf_get_chksum_done = zep_shim_nbuf_get_chksum_done, .nbuf_set_chksum_done = zep_shim_nbuf_set_chksum_done, .tasklet_alloc = zep_shim_work_alloc, .tasklet_free = zep_shim_work_free, .tasklet_init = zep_shim_work_init, .tasklet_schedule = zep_shim_work_schedule, .tasklet_kill = zep_shim_work_kill, .sleep_ms = k_msleep, .delay_us = k_usleep, .time_get_curr_us = zep_shim_time_get_curr_us, .time_elapsed_us = zep_shim_time_elapsed_us, .bus_qspi_init = zep_shim_bus_qspi_init, .bus_qspi_deinit = zep_shim_bus_qspi_deinit, .bus_qspi_dev_add = zep_shim_bus_qspi_dev_add, .bus_qspi_dev_rem = zep_shim_bus_qspi_dev_rem, .bus_qspi_dev_init = zep_shim_bus_qspi_dev_init, .bus_qspi_dev_deinit = zep_shim_bus_qspi_dev_deinit, .bus_qspi_dev_intr_reg = zep_shim_bus_qspi_intr_reg, .bus_qspi_dev_intr_unreg = zep_shim_bus_qspi_intr_unreg, .bus_qspi_dev_host_map_get = zep_shim_bus_qspi_dev_host_map_get, #ifdef CONFIG_NRF_WIFI_LOW_POWER .timer_alloc = zep_shim_timer_alloc, .timer_init = zep_shim_timer_init, .timer_free = zep_shim_timer_free, .timer_schedule = zep_shim_timer_schedule, .timer_kill = zep_shim_timer_kill, .bus_qspi_ps_sleep = zep_shim_bus_qspi_ps_sleep, .bus_qspi_ps_wake = zep_shim_bus_qspi_ps_wake, .bus_qspi_ps_status = zep_shim_bus_qspi_ps_status, #endif /* CONFIG_NRF_WIFI_LOW_POWER */ .assert = zep_shim_assert, .strlen = zep_shim_strlen, }; const struct nrf_wifi_osal_ops *get_os_ops(void) { return &nrf_wifi_os_zep_ops; } ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/shim.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
6,376
```objective-c /* * */ /** * @brief Header containing work specific declarations for the * Zephyr OS layer of the Wi-Fi driver. */ #ifndef __WORK_H__ #define __WORK_H__ extern struct k_work_q zep_wifi_bh_q; enum zep_work_type { ZEP_WORK_TYPE_BH, ZEP_WORK_TYPE_IRQ, ZEP_WORK_TYPE_TX_DONE, ZEP_WORK_TYPE_RX, }; struct zep_work_item { bool in_use; struct k_work work; unsigned long data; void (*callback)(unsigned long data); enum zep_work_type type; }; struct zep_work_item *work_alloc(enum zep_work_type); void work_init(struct zep_work_item *work, void (*callback)(unsigned long callbk_data), unsigned long data); void work_schedule(struct zep_work_item *work); void work_kill(struct zep_work_item *work); void work_free(struct zep_work_item *work); #endif /* __WORK_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/work.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
199
```c /* * */ /* @file * @brief NRF Wi-Fi util shell module */ #include <stdlib.h> #include "host_rpu_umac_if.h" #include "fmac_api.h" #include "fmac_util.h" #include "fmac_main.h" #include "wifi_util.h" extern struct nrf_wifi_drv_priv_zep rpu_drv_priv_zep; struct nrf_wifi_ctx_zep *ctx = &rpu_drv_priv_zep.rpu_ctx_zep; static bool check_valid_data_rate(const struct shell *sh, unsigned char rate_flag, unsigned int data_rate) { bool ret = false; switch (rate_flag) { case RPU_TPUT_MODE_LEGACY: if ((data_rate == 1) || (data_rate == 2) || (data_rate == 55) || (data_rate == 11) || (data_rate == 6) || (data_rate == 9) || (data_rate == 12) || (data_rate == 18) || (data_rate == 24) || (data_rate == 36) || (data_rate == 48) || (data_rate == 54)) { ret = true; } break; case RPU_TPUT_MODE_HT: case RPU_TPUT_MODE_HE_SU: case RPU_TPUT_MODE_VHT: if ((data_rate >= 0) && (data_rate <= 7)) { ret = true; } break; case RPU_TPUT_MODE_HE_ER_SU: if (data_rate >= 0 && data_rate <= 2) { ret = true; } break; default: shell_fprintf(sh, SHELL_ERROR, "%s: Invalid rate_flag %d\n", __func__, rate_flag); break; } return ret; } int nrf_wifi_util_conf_init(struct rpu_conf_params *conf_params) { if (!conf_params) { return -ENOEXEC; } memset(conf_params, 0, sizeof(*conf_params)); /* Initialize values which are other than 0 */ conf_params->he_ltf = -1; conf_params->he_gi = -1; return 0; } static int nrf_wifi_util_set_he_ltf(const struct shell *sh, size_t argc, const char *argv[]) { char *ptr = NULL; unsigned long he_ltf = 0; if (ctx->conf_params.set_he_ltf_gi) { shell_fprintf(sh, SHELL_ERROR, "Disable 'set_he_ltf_gi', to set 'he_ltf'\n"); return -ENOEXEC; } he_ltf = strtoul(argv[1], &ptr, 10); if (he_ltf > 2) { shell_fprintf(sh, SHELL_ERROR, "Invalid HE LTF value(%lu).\n", he_ltf); shell_help(sh); return -ENOEXEC; } ctx->conf_params.he_ltf = he_ltf; return 0; } static int nrf_wifi_util_set_he_gi(const struct shell *sh, size_t argc, const char *argv[]) { char *ptr = NULL; unsigned long he_gi = 0; if (ctx->conf_params.set_he_ltf_gi) { shell_fprintf(sh, SHELL_ERROR, "Disable 'set_he_ltf_gi', to set 'he_gi'\n"); return -ENOEXEC; } he_gi = strtoul(argv[1], &ptr, 10); if (he_gi > 2) { shell_fprintf(sh, SHELL_ERROR, "Invalid HE GI value(%lu).\n", he_gi); shell_help(sh); return -ENOEXEC; } ctx->conf_params.he_gi = he_gi; return 0; } static int nrf_wifi_util_set_he_ltf_gi(const struct shell *sh, size_t argc, const char *argv[]) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; char *ptr = NULL; unsigned long val = 0; val = strtoul(argv[1], &ptr, 10); if ((val < 0) || (val > 1)) { shell_fprintf(sh, SHELL_ERROR, "Invalid value(%lu).\n", val); shell_help(sh); return -ENOEXEC; } status = nrf_wifi_fmac_conf_ltf_gi(ctx->rpu_ctx, ctx->conf_params.he_ltf, ctx->conf_params.he_gi, val); if (status != NRF_WIFI_STATUS_SUCCESS) { shell_fprintf(sh, SHELL_ERROR, "Programming ltf_gi failed\n"); return -ENOEXEC; } ctx->conf_params.set_he_ltf_gi = val; return 0; } #ifdef CONFIG_NRF70_STA_MODE static int nrf_wifi_util_set_uapsd_queue(const struct shell *sh, size_t argc, const char *argv[]) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; char *ptr = NULL; unsigned long val = 0; val = strtoul(argv[1], &ptr, 10); if ((val < UAPSD_Q_MIN) || (val > UAPSD_Q_MAX)) { shell_fprintf(sh, SHELL_ERROR, "Invalid value(%lu).\n", val); shell_help(sh); return -ENOEXEC; } if (ctx->conf_params.uapsd_queue != val) { status = nrf_wifi_fmac_set_uapsd_queue(ctx->rpu_ctx, 0, val); if (status != NRF_WIFI_STATUS_SUCCESS) { shell_fprintf(sh, SHELL_ERROR, "Programming uapsd_queue failed\n"); return -ENOEXEC; } ctx->conf_params.uapsd_queue = val; } return 0; } #endif /* CONFIG_NRF70_STA_MODE */ static int nrf_wifi_util_show_cfg(const struct shell *sh, size_t argc, const char *argv[]) { struct rpu_conf_params *conf_params = NULL; conf_params = &ctx->conf_params; shell_fprintf(sh, SHELL_INFO, "************* Configured Parameters ***********\n"); shell_fprintf(sh, SHELL_INFO, "\n"); shell_fprintf(sh, SHELL_INFO, "he_ltf = %d\n", conf_params->he_ltf); shell_fprintf(sh, SHELL_INFO, "he_gi = %u\n", conf_params->he_gi); shell_fprintf(sh, SHELL_INFO, "set_he_ltf_gi = %d\n", conf_params->set_he_ltf_gi); shell_fprintf(sh, SHELL_INFO, "uapsd_queue = %d\n", conf_params->uapsd_queue); shell_fprintf(sh, SHELL_INFO, "rate_flag = %d, rate_val = %d\n", ctx->conf_params.tx_pkt_tput_mode, ctx->conf_params.tx_pkt_rate); return 0; } #ifdef CONFIG_NRF70_STA_MODE static int nrf_wifi_util_tx_stats(const struct shell *sh, size_t argc, const char *argv[]) { int vif_index = -1; int peer_index = 0; int max_vif_index = MAX(MAX_NUM_APS, MAX_NUM_STAS); struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; void *queue = NULL; unsigned int tx_pending_pkts = 0; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; vif_index = atoi(argv[1]); if ((vif_index < 0) || (vif_index >= max_vif_index)) { shell_fprintf(sh, SHELL_ERROR, "Invalid vif index(%d).\n", vif_index); shell_help(sh); return -ENOEXEC; } fmac_dev_ctx = ctx->rpu_ctx; def_dev_ctx = wifi_dev_priv(fmac_dev_ctx); /* TODO: Get peer_index from shell once AP mode is supported */ shell_fprintf(sh, SHELL_INFO, "************* Tx Stats: vif(%d) peer(0) ***********\n", vif_index); for (int i = 0; i < NRF_WIFI_FMAC_AC_MAX ; i++) { queue = def_dev_ctx->tx_config.data_pending_txq[peer_index][i]; tx_pending_pkts = nrf_wifi_utils_q_len(fmac_dev_ctx->fpriv->opriv, queue); shell_fprintf( sh, SHELL_INFO, "Outstanding tokens: ac: %d -> %d (pending_q_len: %d)\n", i, def_dev_ctx->tx_config.outstanding_descs[i], tx_pending_pkts); } return 0; } #endif /* CONFIG_NRF70_STA_MODE */ static int nrf_wifi_util_tx_rate(const struct shell *sh, size_t argc, const char *argv[]) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; char *ptr = NULL; long rate_flag = -1; long data_rate = -1; rate_flag = strtol(argv[1], &ptr, 10); if (rate_flag >= RPU_TPUT_MODE_MAX) { shell_fprintf(sh, SHELL_ERROR, "Invalid value %ld for rate_flags\n", rate_flag); shell_help(sh); return -ENOEXEC; } if (rate_flag == RPU_TPUT_MODE_HE_TB) { data_rate = -1; } else { if (argc < 3) { shell_fprintf(sh, SHELL_ERROR, "rate_val needed for rate_flag = %ld\n", rate_flag); shell_help(sh); return -ENOEXEC; } data_rate = strtol(argv[2], &ptr, 10); if (!(check_valid_data_rate(sh, rate_flag, data_rate))) { shell_fprintf(sh, SHELL_ERROR, "Invalid data_rate %ld for rate_flag %ld\n", data_rate, rate_flag); return -ENOEXEC; } } status = nrf_wifi_fmac_set_tx_rate(ctx->rpu_ctx, rate_flag, data_rate); if (status != NRF_WIFI_STATUS_SUCCESS) { shell_fprintf(sh, SHELL_ERROR, "Programming tx_rate failed\n"); return -ENOEXEC; } ctx->conf_params.tx_pkt_tput_mode = rate_flag; ctx->conf_params.tx_pkt_rate = data_rate; return 0; } #ifdef CONFIG_NRF_WIFI_LOW_POWER static int nrf_wifi_util_show_host_rpu_ps_ctrl_state(const struct shell *sh, size_t argc, const char *argv[]) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int rpu_ps_state = -1; status = nrf_wifi_fmac_get_host_rpu_ps_ctrl_state(ctx->rpu_ctx, &rpu_ps_state); if (status != NRF_WIFI_STATUS_SUCCESS) { shell_fprintf(sh, SHELL_ERROR, "Failed to get PS state\n"); return -ENOEXEC; } shell_fprintf(sh, SHELL_INFO, "RPU sleep status = %s\n", rpu_ps_state ? "AWAKE" : "SLEEP"); return 0; } #endif /* CONFIG_NRF_WIFI_LOW_POWER */ static int nrf_wifi_util_show_vers(const struct shell *sh, size_t argc, const char *argv[]) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; unsigned int fw_ver; fmac_dev_ctx = ctx->rpu_ctx; shell_fprintf(sh, SHELL_INFO, "Driver version: %s\n", NRF70_DRIVER_VERSION); status = nrf_wifi_fmac_ver_get(fmac_dev_ctx, &fw_ver); if (status != NRF_WIFI_STATUS_SUCCESS) { shell_fprintf(sh, SHELL_INFO, "Failed to get firmware version\n"); return -ENOEXEC; } shell_fprintf(sh, SHELL_INFO, "Firmware version: %d.%d.%d.%d\n", NRF_WIFI_UMAC_VER(fw_ver), NRF_WIFI_UMAC_VER_MAJ(fw_ver), NRF_WIFI_UMAC_VER_MIN(fw_ver), NRF_WIFI_UMAC_VER_EXTRA(fw_ver)); return status; } #ifndef CONFIG_NRF70_RADIO_TEST static int nrf_wifi_util_dump_rpu_stats(const struct shell *sh, size_t argc, const char *argv[]) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct rpu_op_stats stats; enum rpu_stats_type stats_type = RPU_STATS_TYPE_ALL; if (argc == 2) { const char *type = argv[1]; if (!strcmp(type, "umac")) { stats_type = RPU_STATS_TYPE_UMAC; } else if (!strcmp(type, "lmac")) { stats_type = RPU_STATS_TYPE_LMAC; } else if (!strcmp(type, "phy")) { stats_type = RPU_STATS_TYPE_PHY; } else if (!strcmp(type, "all")) { stats_type = RPU_STATS_TYPE_ALL; } else { shell_fprintf(sh, SHELL_ERROR, "Invalid stats type %s\n", type); return -ENOEXEC; } } fmac_dev_ctx = ctx->rpu_ctx; memset(&stats, 0, sizeof(struct rpu_op_stats)); status = nrf_wifi_fmac_stats_get(fmac_dev_ctx, 0, &stats); if (status != NRF_WIFI_STATUS_SUCCESS) { shell_fprintf(sh, SHELL_ERROR, "Failed to get stats\n"); return -ENOEXEC; } if (stats_type == RPU_STATS_TYPE_UMAC || stats_type == RPU_STATS_TYPE_ALL) { struct rpu_umac_stats *umac = &stats.fw.umac; shell_fprintf(sh, SHELL_INFO, "UMAC TX debug stats:\n" "======================\n" "tx_cmd: %u\n" "tx_non_coalesce_pkts_rcvd_from_host: %u\n" "tx_coalesce_pkts_rcvd_from_host: %u\n" "tx_max_coalesce_pkts_rcvd_from_host: %u\n" "tx_cmds_max_used: %u\n" "tx_cmds_currently_in_use: %u\n" "tx_done_events_send_to_host: %u\n" "tx_done_success_pkts_to_host: %u\n" "tx_done_failure_pkts_to_host: %u\n" "tx_cmds_with_crypto_pkts_rcvd_from_host: %u\n" "tx_cmds_with_non_crypto_pkts_rcvd_from_host: %u\n" "tx_cmds_with_broadcast_pkts_rcvd_from_host: %u\n" "tx_cmds_with_multicast_pkts_rcvd_from_host: %u\n" "tx_cmds_with_unicast_pkts_rcvd_from_host: %u\n" "xmit: %u\n" "send_addba_req: %u\n" "addba_resp: %u\n" "softmac_tx: %u\n" "internal_pkts: %u\n" "external_pkts: %u\n" "tx_cmds_to_lmac: %u\n" "tx_dones_from_lmac: %u\n" "total_cmds_to_lmac: %u\n" "tx_packet_data_count: %u\n" "tx_packet_mgmt_count: %u\n" "tx_packet_beacon_count: %u\n" "tx_packet_probe_req_count: %u\n" "tx_packet_auth_count: %u\n" "tx_packet_deauth_count: %u\n" "tx_packet_assoc_req_count: %u\n" "tx_packet_disassoc_count: %u\n" "tx_packet_action_count: %u\n" "tx_packet_other_mgmt_count: %u\n" "tx_packet_non_mgmt_data_count: %u\n\n", umac->tx_dbg_params.tx_cmd, umac->tx_dbg_params.tx_non_coalesce_pkts_rcvd_from_host, umac->tx_dbg_params.tx_coalesce_pkts_rcvd_from_host, umac->tx_dbg_params.tx_max_coalesce_pkts_rcvd_from_host, umac->tx_dbg_params.tx_cmds_max_used, umac->tx_dbg_params.tx_cmds_currently_in_use, umac->tx_dbg_params.tx_done_events_send_to_host, umac->tx_dbg_params.tx_done_success_pkts_to_host, umac->tx_dbg_params.tx_done_failure_pkts_to_host, umac->tx_dbg_params.tx_cmds_with_crypto_pkts_rcvd_from_host, umac->tx_dbg_params.tx_cmds_with_non_crypto_pkts_rcvd_from_host, umac->tx_dbg_params.tx_cmds_with_broadcast_pkts_rcvd_from_host, umac->tx_dbg_params.tx_cmds_with_multicast_pkts_rcvd_from_host, umac->tx_dbg_params.tx_cmds_with_unicast_pkts_rcvd_from_host, umac->tx_dbg_params.xmit, umac->tx_dbg_params.send_addba_req, umac->tx_dbg_params.addba_resp, umac->tx_dbg_params.softmac_tx, umac->tx_dbg_params.internal_pkts, umac->tx_dbg_params.external_pkts, umac->tx_dbg_params.tx_cmds_to_lmac, umac->tx_dbg_params.tx_dones_from_lmac, umac->tx_dbg_params.total_cmds_to_lmac, umac->tx_dbg_params.tx_packet_data_count, umac->tx_dbg_params.tx_packet_mgmt_count, umac->tx_dbg_params.tx_packet_beacon_count, umac->tx_dbg_params.tx_packet_probe_req_count, umac->tx_dbg_params.tx_packet_auth_count, umac->tx_dbg_params.tx_packet_deauth_count, umac->tx_dbg_params.tx_packet_assoc_req_count, umac->tx_dbg_params.tx_packet_disassoc_count, umac->tx_dbg_params.tx_packet_action_count, umac->tx_dbg_params.tx_packet_other_mgmt_count, umac->tx_dbg_params.tx_packet_non_mgmt_data_count); shell_fprintf(sh, SHELL_INFO, "UMAC RX debug stats\n" "======================\n" "lmac_events: %u\n" "rx_events: %u\n" "rx_coalesce_events: %u\n" "total_rx_pkts_from_lmac: %u\n" "max_refill_gap: %u\n" "current_refill_gap: %u\n" "out_of_order_mpdus: %u\n" "reorder_free_mpdus: %u\n" "umac_consumed_pkts: %u\n" "host_consumed_pkts: %u\n" "rx_mbox_post: %u\n" "rx_mbox_receive: %u\n" "reordering_ampdu: %u\n" "timer_mbox_post: %u\n" "timer_mbox_rcv: %u\n" "work_mbox_post: %u\n" "work_mbox_rcv: %u\n" "tasklet_mbox_post: %u\n" "tasklet_mbox_rcv: %u\n" "userspace_offload_frames: %u\n" "alloc_buf_fail: %u\n" "rx_packet_total_count: %u\n" "rx_packet_data_count: %u\n" "rx_packet_qos_data_count: %u\n" "rx_packet_protected_data_count: %u\n" "rx_packet_mgmt_count: %u\n" "rx_packet_beacon_count: %u\n" "rx_packet_probe_resp_count: %u\n" "rx_packet_auth_count: %u\n" "rx_packet_deauth_count: %u\n" "rx_packet_assoc_resp_count: %u\n" "rx_packet_disassoc_count: %u\n" "rx_packet_action_count: %u\n" "rx_packet_probe_req_count: %u\n" "rx_packet_other_mgmt_count: %u\n" "max_coalesce_pkts: %d\n" "null_skb_pointer_from_lmac: %u\n" "unexpected_mgmt_pkt: %u\n\n", umac->rx_dbg_params.lmac_events, umac->rx_dbg_params.rx_events, umac->rx_dbg_params.rx_coalesce_events, umac->rx_dbg_params.total_rx_pkts_from_lmac, umac->rx_dbg_params.max_refill_gap, umac->rx_dbg_params.current_refill_gap, umac->rx_dbg_params.out_of_order_mpdus, umac->rx_dbg_params.reorder_free_mpdus, umac->rx_dbg_params.umac_consumed_pkts, umac->rx_dbg_params.host_consumed_pkts, umac->rx_dbg_params.rx_mbox_post, umac->rx_dbg_params.rx_mbox_receive, umac->rx_dbg_params.reordering_ampdu, umac->rx_dbg_params.timer_mbox_post, umac->rx_dbg_params.timer_mbox_rcv, umac->rx_dbg_params.work_mbox_post, umac->rx_dbg_params.work_mbox_rcv, umac->rx_dbg_params.tasklet_mbox_post, umac->rx_dbg_params.tasklet_mbox_rcv, umac->rx_dbg_params.userspace_offload_frames, umac->rx_dbg_params.alloc_buf_fail, umac->rx_dbg_params.rx_packet_total_count, umac->rx_dbg_params.rx_packet_data_count, umac->rx_dbg_params.rx_packet_qos_data_count, umac->rx_dbg_params.rx_packet_protected_data_count, umac->rx_dbg_params.rx_packet_mgmt_count, umac->rx_dbg_params.rx_packet_beacon_count, umac->rx_dbg_params.rx_packet_probe_resp_count, umac->rx_dbg_params.rx_packet_auth_count, umac->rx_dbg_params.rx_packet_deauth_count, umac->rx_dbg_params.rx_packet_assoc_resp_count, umac->rx_dbg_params.rx_packet_disassoc_count, umac->rx_dbg_params.rx_packet_action_count, umac->rx_dbg_params.rx_packet_probe_req_count, umac->rx_dbg_params.rx_packet_other_mgmt_count, umac->rx_dbg_params.max_coalesce_pkts, umac->rx_dbg_params.null_skb_pointer_from_lmac, umac->rx_dbg_params.unexpected_mgmt_pkt); shell_fprintf(sh, SHELL_INFO, "UMAC control path stats\n" "======================\n" "cmd_init: %u\n" "event_init_done: %u\n" "cmd_rf_test: %u\n" "cmd_connect: %u\n" "cmd_get_stats: %u\n" "event_ps_state: %u\n" "cmd_set_reg: %u\n" "cmd_get_reg: %u\n" "cmd_req_set_reg: %u\n" "cmd_trigger_scan: %u\n" "event_scan_done: %u\n" "cmd_get_scan: %u\n" "umac_scan_req: %u\n" "umac_scan_complete: %u\n" "umac_scan_busy: %u\n" "cmd_auth: %u\n" "cmd_assoc: %u\n" "cmd_deauth: %u\n" "cmd_register_frame: %u\n" "cmd_frame: %u\n" "cmd_del_key: %u\n" "cmd_new_key: %u\n" "cmd_set_key: %u\n" "cmd_get_key: %u\n" "event_beacon_hint: %u\n" "event_reg_change: %u\n" "event_wiphy_reg_change: %u\n" "cmd_set_station: %u\n" "cmd_new_station: %u\n" "cmd_del_station: %u\n" "cmd_new_interface: %u\n" "cmd_set_interface: %u\n" "cmd_get_interface: %u\n" "cmd_set_ifflags: %u\n" "cmd_set_ifflags_done: %u\n" "cmd_set_bss: %u\n" "cmd_set_wiphy: %u\n" "cmd_start_ap: %u\n" "LMAC_CMD_PS: %u\n" "CURR_STATE: %u\n\n", umac->cmd_evnt_dbg_params.cmd_init, umac->cmd_evnt_dbg_params.event_init_done, umac->cmd_evnt_dbg_params.cmd_rf_test, umac->cmd_evnt_dbg_params.cmd_connect, umac->cmd_evnt_dbg_params.cmd_get_stats, umac->cmd_evnt_dbg_params.event_ps_state, umac->cmd_evnt_dbg_params.cmd_set_reg, umac->cmd_evnt_dbg_params.cmd_get_reg, umac->cmd_evnt_dbg_params.cmd_req_set_reg, umac->cmd_evnt_dbg_params.cmd_trigger_scan, umac->cmd_evnt_dbg_params.event_scan_done, umac->cmd_evnt_dbg_params.cmd_get_scan, umac->cmd_evnt_dbg_params.umac_scan_req, umac->cmd_evnt_dbg_params.umac_scan_complete, umac->cmd_evnt_dbg_params.umac_scan_busy, umac->cmd_evnt_dbg_params.cmd_auth, umac->cmd_evnt_dbg_params.cmd_assoc, umac->cmd_evnt_dbg_params.cmd_deauth, umac->cmd_evnt_dbg_params.cmd_register_frame, umac->cmd_evnt_dbg_params.cmd_frame, umac->cmd_evnt_dbg_params.cmd_del_key, umac->cmd_evnt_dbg_params.cmd_new_key, umac->cmd_evnt_dbg_params.cmd_set_key, umac->cmd_evnt_dbg_params.cmd_get_key, umac->cmd_evnt_dbg_params.event_beacon_hint, umac->cmd_evnt_dbg_params.event_reg_change, umac->cmd_evnt_dbg_params.event_wiphy_reg_change, umac->cmd_evnt_dbg_params.cmd_set_station, umac->cmd_evnt_dbg_params.cmd_new_station, umac->cmd_evnt_dbg_params.cmd_del_station, umac->cmd_evnt_dbg_params.cmd_new_interface, umac->cmd_evnt_dbg_params.cmd_set_interface, umac->cmd_evnt_dbg_params.cmd_get_interface, umac->cmd_evnt_dbg_params.cmd_set_ifflags, umac->cmd_evnt_dbg_params.cmd_set_ifflags_done, umac->cmd_evnt_dbg_params.cmd_set_bss, umac->cmd_evnt_dbg_params.cmd_set_wiphy, umac->cmd_evnt_dbg_params.cmd_start_ap, umac->cmd_evnt_dbg_params.LMAC_CMD_PS, umac->cmd_evnt_dbg_params.CURR_STATE); shell_fprintf(sh, SHELL_INFO, "UMAC interface stats\n" "======================\n" "tx_unicast_pkt_count: %u\n" "tx_multicast_pkt_count: %u\n" "tx_broadcast_pkt_count: %u\n" "tx_bytes: %u\n" "rx_unicast_pkt_count: %u\n" "rx_multicast_pkt_count: %u\n" "rx_broadcast_pkt_count: %u\n" "rx_beacon_success_count: %u\n" "rx_beacon_miss_count: %u\n" "rx_bytes: %u\n" "rx_checksum_error_count: %u\n\n" "replay_attack_drop_cnt: %u\n\n", umac->interface_data_stats.tx_unicast_pkt_count, umac->interface_data_stats.tx_multicast_pkt_count, umac->interface_data_stats.tx_broadcast_pkt_count, umac->interface_data_stats.tx_bytes, umac->interface_data_stats.rx_unicast_pkt_count, umac->interface_data_stats.rx_multicast_pkt_count, umac->interface_data_stats.rx_broadcast_pkt_count, umac->interface_data_stats.rx_beacon_success_count, umac->interface_data_stats.rx_beacon_miss_count, umac->interface_data_stats.rx_bytes, umac->interface_data_stats.rx_checksum_error_count, umac->interface_data_stats.replay_attack_drop_cnt); } if (stats_type == RPU_STATS_TYPE_LMAC || stats_type == RPU_STATS_TYPE_ALL) { struct rpu_lmac_stats *lmac = &stats.fw.lmac; shell_fprintf(sh, SHELL_INFO, "LMAC stats\n" "======================\n" "reset_cmd_cnt: %u\n" "reset_complete_event_cnt: %u\n" "unable_gen_event: %u\n" "ch_prog_cmd_cnt: %u\n" "channel_prog_done: %u\n" "tx_pkt_cnt: %u\n" "tx_pkt_done_cnt: %u\n" "scan_pkt_cnt: %u\n" "internal_pkt_cnt: %u\n" "internal_pkt_done_cnt: %u\n" "ack_resp_cnt: %u\n" "tx_timeout: %u\n" "deagg_isr: %u\n" "deagg_inptr_desc_empty: %u\n" "deagg_circular_buffer_full: %u\n" "lmac_rxisr_cnt: %u\n" "rx_decryptcnt: %u\n" "process_decrypt_fail: %u\n" "prepa_rx_event_fail: %u\n" "rx_core_pool_full_cnt: %u\n" "rx_mpdu_crc_success_cnt: %u\n" "rx_mpdu_crc_fail_cnt: %u\n" "rx_ofdm_crc_success_cnt: %u\n" "rx_ofdm_crc_fail_cnt: %u\n" "rxDSSSCrcSuccessCnt: %u\n" "rxDSSSCrcFailCnt: %u\n" "rx_crypto_start_cnt: %u\n" "rx_crypto_done_cnt: %u\n" "rx_event_buf_full: %u\n" "rx_extram_buf_full: %u\n" "scan_req: %u\n" "scan_complete: %u\n" "scan_abort_req: %u\n" "scan_abort_complete: %u\n" "internal_buf_pool_null: %u\n" "rpu_hw_lockup_count: %u\n" "rpu_hw_lockup_recovery_done: %u\n\n", lmac->reset_cmd_cnt, lmac->reset_complete_event_cnt, lmac->unable_gen_event, lmac->ch_prog_cmd_cnt, lmac->channel_prog_done, lmac->tx_pkt_cnt, lmac->tx_pkt_done_cnt, lmac->scan_pkt_cnt, lmac->internal_pkt_cnt, lmac->internal_pkt_done_cnt, lmac->ack_resp_cnt, lmac->tx_timeout, lmac->deagg_isr, lmac->deagg_inptr_desc_empty, lmac->deagg_circular_buffer_full, lmac->lmac_rxisr_cnt, lmac->rx_decryptcnt, lmac->process_decrypt_fail, lmac->prepa_rx_event_fail, lmac->rx_core_pool_full_cnt, lmac->rx_mpdu_crc_success_cnt, lmac->rx_mpdu_crc_fail_cnt, lmac->rx_ofdm_crc_success_cnt, lmac->rx_ofdm_crc_fail_cnt, lmac->rxDSSSCrcSuccessCnt, lmac->rxDSSSCrcFailCnt, lmac->rx_crypto_start_cnt, lmac->rx_crypto_done_cnt, lmac->rx_event_buf_full, lmac->rx_extram_buf_full, lmac->scan_req, lmac->scan_complete, lmac->scan_abort_req, lmac->scan_abort_complete, lmac->internal_buf_pool_null, lmac->rpu_hw_lockup_count, lmac->rpu_hw_lockup_recovery_done); } if (stats_type == RPU_STATS_TYPE_PHY || stats_type == RPU_STATS_TYPE_ALL) { struct rpu_phy_stats *phy = &stats.fw.phy; shell_fprintf(sh, SHELL_INFO, "PHY stats\n" "======================\n" "rssi_avg: %d\n" "pdout_val: %u\n" "ofdm_crc32_pass_cnt: %u\n" "ofdm_crc32_fail_cnt: %u\n" "dsss_crc32_pass_cnt: %u\n" "dsss_crc32_fail_cnt: %u\n\n", phy->rssi_avg, phy->pdout_val, phy->ofdm_crc32_pass_cnt, phy->ofdm_crc32_fail_cnt, phy->dsss_crc32_pass_cnt, phy->dsss_crc32_fail_cnt); } return 0; } #endif /* CONFIG_NRF70_RADIO_TEST */ #ifdef CONFIG_NRF_WIFI_RPU_RECOVERY static int nrf_wifi_util_trigger_rpu_recovery(const struct shell *sh, size_t argc, const char *argv[]) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; if (!ctx || !ctx->rpu_ctx) { shell_fprintf(sh, SHELL_ERROR, "RPU context not initialized\n"); return -ENOEXEC; } fmac_dev_ctx = ctx->rpu_ctx; status = nrf_wifi_fmac_rpu_recovery_callback(fmac_dev_ctx, NULL, 0); if (status != NRF_WIFI_STATUS_SUCCESS) { shell_fprintf(sh, SHELL_ERROR, "Failed to trigger RPU recovery\n"); return -ENOEXEC; } shell_fprintf(sh, SHELL_INFO, "RPU recovery triggered\n"); return 0; } #endif /* CONFIG_NRF_WIFI_RPU_RECOVERY */ SHELL_STATIC_SUBCMD_SET_CREATE( nrf_wifi_util_subcmds, SHELL_CMD_ARG(he_ltf, NULL, "0 - 1x HE LTF\n" "1 - 2x HE LTF\n" "2 - 4x HE LTF ", nrf_wifi_util_set_he_ltf, 2, 0), SHELL_CMD_ARG(he_gi, NULL, "0 - 0.8 us\n" "1 - 1.6 us\n" "2 - 3.2 us ", nrf_wifi_util_set_he_gi, 2, 0), SHELL_CMD_ARG(set_he_ltf_gi, NULL, "0 - Disable\n" "1 - Enable", nrf_wifi_util_set_he_ltf_gi, 2, 0), #ifdef CONFIG_NRF70_STA_MODE SHELL_CMD_ARG(uapsd_queue, NULL, "<val> - 0 to 15", nrf_wifi_util_set_uapsd_queue, 2, 0), #endif /* CONFIG_NRF70_STA_MODE */ SHELL_CMD_ARG(show_config, NULL, "Display the current configuration values", nrf_wifi_util_show_cfg, 1, 0), #ifdef CONFIG_NRF70_STA_MODE SHELL_CMD_ARG(tx_stats, NULL, "Displays transmit statistics\n" "vif_index: 0 - 1\n", nrf_wifi_util_tx_stats, 2, 0), #endif /* CONFIG_NRF70_STA_MODE */ SHELL_CMD_ARG(tx_rate, NULL, "Sets TX data rate to either a fixed value or AUTO\n" "Parameters:\n" " <rate_flag> : The TX data rate type to be set, where:\n" " 0 - LEGACY\n" " 1 - HT\n" " 2 - VHT\n" " 3 - HE_SU\n" " 4 - HE_ER_SU\n" " 5 - AUTO\n" " <rate_val> : The TX data rate value to be set, valid values are:\n" " Legacy : <1, 2, 55, 11, 6, 9, 12, 18, 24, 36, 48, 54>\n" " Non-legacy: <MCS index value between 0 - 7>\n" " AUTO: <No value needed>\n", nrf_wifi_util_tx_rate, 2, 1), #ifdef CONFIG_NRF_WIFI_LOW_POWER SHELL_CMD_ARG(sleep_state, NULL, "Display current sleep status", nrf_wifi_util_show_host_rpu_ps_ctrl_state, 1, 0), #endif /* CONFIG_NRF_WIFI_LOW_POWER */ SHELL_CMD_ARG(show_vers, NULL, "Display the driver and the firmware versions", nrf_wifi_util_show_vers, 1, 0), #ifndef CONFIG_NRF70_RADIO_TEST SHELL_CMD_ARG(rpu_stats, NULL, "Display RPU stats " "Parameters: umac or lmac or phy or all (default)", nrf_wifi_util_dump_rpu_stats, 1, 1), #endif /* CONFIG_NRF70_RADIO_TEST */ #ifdef CONFIG_NRF_WIFI_RPU_RECOVERY SHELL_CMD_ARG(rpu_recovery_test, NULL, "Trigger RPU recovery", nrf_wifi_util_trigger_rpu_recovery, 1, 0), #endif /* CONFIG_NRF_WIFI_RPU_RECOVERY */ SHELL_SUBCMD_SET_END); SHELL_CMD_REGISTER(wifi_util, &nrf_wifi_util_subcmds, "nRF Wi-Fi utility shell commands", NULL); static int nrf_wifi_util_init(void) { if (nrf_wifi_util_conf_init(&ctx->conf_params) < 0) return -1; return 0; } SYS_INIT(nrf_wifi_util_init, APPLICATION, CONFIG_APPLICATION_INIT_PRIORITY); ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/wifi_util.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
8,430
```c /* * */ /** * @brief File containing WiFi management operation implementations * for the Zephyr OS. */ #include <stdlib.h> #include <zephyr/kernel.h> #include <zephyr/logging/log.h> #include "util.h" #include "fmac_api.h" #include "fmac_tx.h" #include "fmac_util.h" #include "fmac_main.h" #include "wifi_mgmt.h" LOG_MODULE_DECLARE(wifi_nrf, CONFIG_WIFI_NRF70_LOG_LEVEL); extern struct nrf_wifi_drv_priv_zep rpu_drv_priv_zep; int nrf_wifi_set_power_save(const struct device *dev, struct wifi_ps_params *params) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; int ret = -1; unsigned int uapsd_queue = UAPSD_Q_MIN; /* Legacy mode */ if (!dev || !params) { LOG_ERR("%s: dev or params is NULL", __func__); return ret; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } switch (params->type) { case WIFI_PS_PARAM_LISTEN_INTERVAL: if ((params->listen_interval < NRF_WIFI_LISTEN_INTERVAL_MIN) || (params->listen_interval > WIFI_LISTEN_INTERVAL_MAX)) { params->fail_reason = WIFI_PS_PARAM_LISTEN_INTERVAL_RANGE_INVALID; return -EINVAL; } status = nrf_wifi_fmac_set_listen_interval( rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, params->listen_interval); break; case WIFI_PS_PARAM_TIMEOUT: if ((vif_ctx_zep->if_type != NRF_WIFI_IFTYPE_STATION) #ifdef CONFIG_NRF70_RAW_DATA_TX && (vif_ctx_zep->if_type != NRF_WIFI_STA_TX_INJECTOR) #endif /* CONFIG_NRF70_RAW_DATA_TX */ #ifdef CONFIG_NRF70_PROMISC_DATA_RX && (vif_ctx_zep->if_type != NRF_WIFI_STA_PROMISC_TX_INJECTOR) #endif /* CONFIG_NRF70_PROMISC_DATA_RX */ ) { LOG_ERR("%s: Operation supported only in STA enabled mode", __func__); params->fail_reason = WIFI_PS_PARAM_FAIL_CMD_EXEC_FAIL; goto out; } status = nrf_wifi_fmac_set_power_save_timeout( rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, params->timeout_ms); break; case WIFI_PS_PARAM_MODE: if (params->mode == WIFI_PS_MODE_WMM) { uapsd_queue = UAPSD_Q_MAX; /* WMM mode */ } status = nrf_wifi_fmac_set_uapsd_queue(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, uapsd_queue); break; case WIFI_PS_PARAM_STATE: status = nrf_wifi_fmac_set_power_save(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, params->enabled); break; case WIFI_PS_PARAM_WAKEUP_MODE: status = nrf_wifi_fmac_set_ps_wakeup_mode( rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, params->wakeup_mode); break; default: params->fail_reason = WIFI_PS_PARAM_FAIL_CMD_EXEC_FAIL; return -ENOTSUP; } if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Confiuring PS param %d failed", __func__, params->type); params->fail_reason = WIFI_PS_PARAM_FAIL_CMD_EXEC_FAIL; goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_get_power_save_config(const struct device *dev, struct wifi_ps_config *ps_config) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; int ret = -1; int count = 0; if (!dev || !ps_config) { return ret; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return ret; } if ((vif_ctx_zep->if_type != NRF_WIFI_IFTYPE_STATION) #ifdef CONFIG_NRF70_RAW_DATA_TX && (vif_ctx_zep->if_type != NRF_WIFI_STA_TX_INJECTOR) #endif /* CONFIG_NRF70_RAW_DATA_TX */ #ifdef CONFIG_NRF70_PROMISC_DATA_RX && (vif_ctx_zep->if_type != NRF_WIFI_STA_PROMISC_TX_INJECTOR) #endif /* CONFIG_NRF70_PROMISC_DATA_RX */ ) { LOG_ERR("%s: Operation supported only in STA enabled mode", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); goto out; } vif_ctx_zep->ps_info = ps_config; vif_ctx_zep->ps_config_info_evnt = false; status = nrf_wifi_fmac_get_power_save_info(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_get_power_save_info failed", __func__); goto out; } do { nrf_wifi_osal_sleep_ms(fmac_dev_ctx->fpriv->opriv, 1); count++; } while ((vif_ctx_zep->ps_config_info_evnt == false) && (count < NRF_WIFI_FMAC_PS_CONF_EVNT_RECV_TIMEOUT)); if (count == NRF_WIFI_FMAC_PS_CONF_EVNT_RECV_TIMEOUT) { nrf_wifi_osal_log_err(fmac_dev_ctx->fpriv->opriv, "%s: Timed out", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } /* TWT interval conversion helpers: User <-> Protocol */ static struct twt_interval_float nrf_wifi_twt_us_to_float(uint32_t twt_interval) { double mantissa = 0.0; int exponent = 0; struct twt_interval_float twt_interval_fp; double twt_interval_ms = twt_interval / 1000.0; mantissa = frexp(twt_interval_ms, &exponent); /* Ceiling and conversion to milli seconds */ twt_interval_fp.mantissa = ceil(mantissa * 1000); twt_interval_fp.exponent = exponent; return twt_interval_fp; } static uint64_t nrf_wifi_twt_float_to_us(struct twt_interval_float twt_interval_fp) { /* Conversion to micro-seconds */ return floor(ldexp(twt_interval_fp.mantissa, twt_interval_fp.exponent) / (1000)) * 1000; } static unsigned char twt_wifi_mgmt_to_rpu_neg_type(enum wifi_twt_negotiation_type neg_type) { unsigned char rpu_neg_type = 0; switch (neg_type) { case WIFI_TWT_INDIVIDUAL: rpu_neg_type = NRF_WIFI_TWT_NEGOTIATION_TYPE_INDIVIDUAL; break; case WIFI_TWT_BROADCAST: rpu_neg_type = NRF_WIFI_TWT_NEGOTIATION_TYPE_BROADCAST; break; default: LOG_ERR("%s: Invalid negotiation type: %d", __func__, neg_type); break; } return rpu_neg_type; } static enum wifi_twt_negotiation_type twt_rpu_to_wifi_mgmt_neg_type(unsigned char neg_type) { enum wifi_twt_negotiation_type wifi_neg_type = WIFI_TWT_INDIVIDUAL; switch (neg_type) { case NRF_WIFI_TWT_NEGOTIATION_TYPE_INDIVIDUAL: wifi_neg_type = WIFI_TWT_INDIVIDUAL; break; case NRF_WIFI_TWT_NEGOTIATION_TYPE_BROADCAST: wifi_neg_type = WIFI_TWT_BROADCAST; break; default: LOG_ERR("%s: Invalid negotiation type: %d", __func__, neg_type); break; } return wifi_neg_type; } /* Though setup_cmd enums have 1-1 mapping but due to data type different need these */ static enum wifi_twt_setup_cmd twt_rpu_to_wifi_mgmt_setup_cmd(signed int setup_cmd) { enum wifi_twt_setup_cmd wifi_setup_cmd = WIFI_TWT_SETUP_CMD_REQUEST; switch (setup_cmd) { case NRF_WIFI_REQUEST_TWT: wifi_setup_cmd = WIFI_TWT_SETUP_CMD_REQUEST; break; case NRF_WIFI_SUGGEST_TWT: wifi_setup_cmd = WIFI_TWT_SETUP_CMD_SUGGEST; break; case NRF_WIFI_DEMAND_TWT: wifi_setup_cmd = WIFI_TWT_SETUP_CMD_DEMAND; break; case NRF_WIFI_GROUPING_TWT: wifi_setup_cmd = WIFI_TWT_SETUP_CMD_GROUPING; break; case NRF_WIFI_ACCEPT_TWT: wifi_setup_cmd = WIFI_TWT_SETUP_CMD_ACCEPT; break; case NRF_WIFI_ALTERNATE_TWT: wifi_setup_cmd = WIFI_TWT_SETUP_CMD_ALTERNATE; break; case NRF_WIFI_DICTATE_TWT: wifi_setup_cmd = WIFI_TWT_SETUP_CMD_DICTATE; break; case NRF_WIFI_REJECT_TWT: wifi_setup_cmd = WIFI_TWT_SETUP_CMD_REJECT; break; default: LOG_ERR("%s: Invalid setup command: %d", __func__, setup_cmd); break; } return wifi_setup_cmd; } static signed int twt_wifi_mgmt_to_rpu_setup_cmd(enum wifi_twt_setup_cmd setup_cmd) { signed int rpu_setup_cmd = NRF_WIFI_REQUEST_TWT; switch (setup_cmd) { case WIFI_TWT_SETUP_CMD_REQUEST: rpu_setup_cmd = NRF_WIFI_REQUEST_TWT; break; case WIFI_TWT_SETUP_CMD_SUGGEST: rpu_setup_cmd = NRF_WIFI_SUGGEST_TWT; break; case WIFI_TWT_SETUP_CMD_DEMAND: rpu_setup_cmd = NRF_WIFI_DEMAND_TWT; break; case WIFI_TWT_SETUP_CMD_GROUPING: rpu_setup_cmd = NRF_WIFI_GROUPING_TWT; break; case WIFI_TWT_SETUP_CMD_ACCEPT: rpu_setup_cmd = NRF_WIFI_ACCEPT_TWT; break; case WIFI_TWT_SETUP_CMD_ALTERNATE: rpu_setup_cmd = NRF_WIFI_ALTERNATE_TWT; break; case WIFI_TWT_SETUP_CMD_DICTATE: rpu_setup_cmd = NRF_WIFI_DICTATE_TWT; break; case WIFI_TWT_SETUP_CMD_REJECT: rpu_setup_cmd = NRF_WIFI_REJECT_TWT; break; default: LOG_ERR("%s: Invalid setup command: %d", __func__, setup_cmd); break; } return rpu_setup_cmd; } void nrf_wifi_event_proc_get_power_save_info(void *vif_ctx, struct nrf_wifi_umac_event_power_save_info *ps_info, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; if (!vif_ctx || !ps_info) { return; } vif_ctx_zep = vif_ctx; vif_ctx_zep->ps_info->ps_params.mode = ps_info->ps_mode; vif_ctx_zep->ps_info->ps_params.enabled = ps_info->enabled; vif_ctx_zep->ps_info->num_twt_flows = ps_info->num_twt_flows; vif_ctx_zep->ps_info->ps_params.timeout_ms = ps_info->ps_timeout; vif_ctx_zep->ps_info->ps_params.listen_interval = ps_info->listen_interval; vif_ctx_zep->ps_info->ps_params.wakeup_mode = ps_info->extended_ps; for (int i = 0; i < ps_info->num_twt_flows; i++) { struct twt_interval_float twt_interval_fp; struct wifi_twt_flow_info *twt_zep = &vif_ctx_zep->ps_info->twt_flows[i]; struct nrf_wifi_umac_config_twt_info *twt_rpu = &ps_info->twt_flow_info[i]; memset(twt_zep, 0, sizeof(struct wifi_twt_flow_info)); twt_zep->flow_id = twt_rpu->twt_flow_id; twt_zep->implicit = twt_rpu->is_implicit ? 1 : 0; twt_zep->trigger = twt_rpu->ap_trigger_frame ? 1 : 0; twt_zep->announce = twt_rpu->twt_flow_type == NRF_WIFI_TWT_FLOW_TYPE_ANNOUNCED; twt_zep->negotiation_type = twt_rpu_to_wifi_mgmt_neg_type(twt_rpu->neg_type); twt_zep->dialog_token = twt_rpu->dialog_token; twt_interval_fp.mantissa = twt_rpu->twt_target_wake_interval_mantissa; twt_interval_fp.exponent = twt_rpu->twt_target_wake_interval_exponent; twt_zep->twt_interval = nrf_wifi_twt_float_to_us(twt_interval_fp); twt_zep->twt_wake_interval = twt_rpu->nominal_min_twt_wake_duration; } vif_ctx_zep->ps_config_info_evnt = true; } static void nrf_wifi_twt_update_internal_state(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep, bool setup, unsigned char flow_id) { if (setup) { vif_ctx_zep->twt_flows_map |= BIT(flow_id); vif_ctx_zep->twt_flow_in_progress_map &= ~BIT(flow_id); } else { vif_ctx_zep->twt_flows_map &= ~BIT(flow_id); } } int nrf_wifi_twt_teardown_flows(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep, unsigned char start_flow_id, unsigned char end_flow_id) { struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_umac_config_twt_info twt_info = {0}; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int ret = 0; struct wifi_twt_params twt_params = {0}; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } for (int flow_id = start_flow_id; flow_id < end_flow_id; flow_id++) { if (!(vif_ctx_zep->twt_flows_map & BIT(flow_id))) { continue; } twt_info.twt_flow_id = flow_id; status = nrf_wifi_fmac_twt_teardown(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &twt_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: TWT teardown for flow id %d failed", __func__, flow_id); ret = -1; continue; } /* UMAC doesn't send TWT teardown event for host initiated teardown */ nrf_wifi_twt_update_internal_state(vif_ctx_zep, false, flow_id); /* TODO: Remove this once UMAC sends the status */ twt_params.operation = WIFI_TWT_TEARDOWN; twt_params.flow_id = flow_id; twt_params.teardown_status = WIFI_TWT_TEARDOWN_SUCCESS; wifi_mgmt_raise_twt_event(vif_ctx_zep->zep_net_if_ctx, &twt_params); } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_set_twt(const struct device *dev, struct wifi_twt_params *twt_params) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_umac_config_twt_info twt_info = {0}; int ret = -1; if (!dev || !twt_params) { LOG_ERR("%s: dev or twt_params is NULL", __func__); return ret; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } if (!(twt_params->operation == WIFI_TWT_TEARDOWN && twt_params->teardown.teardown_all) && twt_params->flow_id >= WIFI_MAX_TWT_FLOWS) { LOG_ERR("%s: Invalid flow id: %d", __func__, twt_params->flow_id); twt_params->fail_reason = WIFI_TWT_FAIL_INVALID_FLOW_ID; goto out; } switch (twt_params->operation) { case WIFI_TWT_SETUP: if (vif_ctx_zep->twt_flow_in_progress_map & BIT(twt_params->flow_id)) { twt_params->fail_reason = WIFI_TWT_FAIL_OPERATION_IN_PROGRESS; goto out; } if (twt_params->setup_cmd == WIFI_TWT_SETUP_CMD_REQUEST) { if (vif_ctx_zep->twt_flows_map & BIT(twt_params->flow_id)) { twt_params->fail_reason = WIFI_TWT_FAIL_FLOW_ALREADY_EXISTS; goto out; } } struct twt_interval_float twt_interval_fp = nrf_wifi_twt_us_to_float(twt_params->setup.twt_interval); twt_info.twt_flow_id = twt_params->flow_id; twt_info.neg_type = twt_wifi_mgmt_to_rpu_neg_type(twt_params->negotiation_type); twt_info.setup_cmd = twt_wifi_mgmt_to_rpu_setup_cmd(twt_params->setup_cmd); twt_info.ap_trigger_frame = twt_params->setup.trigger; twt_info.is_implicit = twt_params->setup.implicit; if (twt_params->setup.announce) { twt_info.twt_flow_type = NRF_WIFI_TWT_FLOW_TYPE_ANNOUNCED; } else { twt_info.twt_flow_type = NRF_WIFI_TWT_FLOW_TYPE_UNANNOUNCED; } twt_info.nominal_min_twt_wake_duration = twt_params->setup.twt_wake_interval; twt_info.twt_target_wake_interval_mantissa = twt_interval_fp.mantissa; twt_info.twt_target_wake_interval_exponent = twt_interval_fp.exponent; twt_info.dialog_token = twt_params->dialog_token; twt_info.twt_wake_ahead_duration = twt_params->setup.twt_wake_ahead_duration; status = nrf_wifi_fmac_twt_setup(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &twt_info); break; case WIFI_TWT_TEARDOWN: unsigned char start_flow_id = 0; unsigned char end_flow_id = WIFI_MAX_TWT_FLOWS; if (!twt_params->teardown.teardown_all) { if (!(vif_ctx_zep->twt_flows_map & BIT(twt_params->flow_id))) { twt_params->fail_reason = WIFI_TWT_FAIL_INVALID_FLOW_ID; goto out; } start_flow_id = twt_params->flow_id; end_flow_id = twt_params->flow_id + 1; twt_info.twt_flow_id = twt_params->flow_id; } status = nrf_wifi_twt_teardown_flows(vif_ctx_zep, start_flow_id, end_flow_id); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: TWT teardown failed: start_flow_id: %d, end_flow_id: %d", __func__, start_flow_id, end_flow_id); goto out; } break; default: LOG_ERR("Unknown TWT operation"); status = NRF_WIFI_STATUS_FAIL; break; } if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Failed", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } void nrf_wifi_event_proc_twt_setup_zep(void *vif_ctx, struct nrf_wifi_umac_cmd_config_twt *twt_setup_info, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct wifi_twt_params twt_params; struct twt_interval_float twt_interval_fp; if (!vif_ctx || !twt_setup_info) { return; } vif_ctx_zep = vif_ctx; twt_params.operation = WIFI_TWT_SETUP; twt_params.flow_id = twt_setup_info->info.twt_flow_id; twt_params.negotiation_type = twt_rpu_to_wifi_mgmt_neg_type(twt_setup_info->info.neg_type); twt_params.setup_cmd = twt_rpu_to_wifi_mgmt_setup_cmd(twt_setup_info->info.setup_cmd); twt_params.setup.trigger = twt_setup_info->info.ap_trigger_frame ? 1 : 0; twt_params.setup.implicit = twt_setup_info->info.is_implicit ? 1 : 0; twt_params.setup.announce = twt_setup_info->info.twt_flow_type == NRF_WIFI_TWT_FLOW_TYPE_ANNOUNCED; twt_params.setup.twt_wake_interval = twt_setup_info->info.nominal_min_twt_wake_duration; twt_interval_fp.mantissa = twt_setup_info->info.twt_target_wake_interval_mantissa; twt_interval_fp.exponent = twt_setup_info->info.twt_target_wake_interval_exponent; twt_params.setup.twt_interval = nrf_wifi_twt_float_to_us(twt_interval_fp); twt_params.dialog_token = twt_setup_info->info.dialog_token; twt_params.resp_status = twt_setup_info->info.twt_resp_status; if ((twt_setup_info->info.twt_resp_status == 0) || (twt_setup_info->info.neg_type == NRF_WIFI_ACCEPT_TWT)) { nrf_wifi_twt_update_internal_state(vif_ctx_zep, true, twt_params.flow_id); } wifi_mgmt_raise_twt_event(vif_ctx_zep->zep_net_if_ctx, &twt_params); } void nrf_wifi_event_proc_twt_teardown_zep(void *vif_ctx, struct nrf_wifi_umac_cmd_teardown_twt *twt_teardown_info, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct wifi_twt_params twt_params = {0}; if (!vif_ctx || !twt_teardown_info) { return; } vif_ctx_zep = vif_ctx; twt_params.operation = WIFI_TWT_TEARDOWN; twt_params.flow_id = twt_teardown_info->info.twt_flow_id; /* TODO: ADD reason code in the twt_params structure */ nrf_wifi_twt_update_internal_state(vif_ctx_zep, false, twt_params.flow_id); wifi_mgmt_raise_twt_event(vif_ctx_zep->zep_net_if_ctx, &twt_params); } void nrf_wifi_event_proc_twt_sleep_zep(void *vif_ctx, struct nrf_wifi_umac_event_twt_sleep *sleep_evnt, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; struct nrf_wifi_fmac_priv_def *def_priv = NULL; #ifdef CONFIG_NRF70_DATA_TX int desc = 0; int ac = 0; #endif vif_ctx_zep = vif_ctx; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; def_dev_ctx = wifi_dev_priv(fmac_dev_ctx); def_priv = wifi_fmac_priv(fmac_dev_ctx->fpriv); if (!sleep_evnt) { LOG_ERR("%s: sleep_evnt is NULL", __func__); return; } switch (sleep_evnt->info.type) { case TWT_BLOCK_TX: nrf_wifi_osal_spinlock_take(fmac_dev_ctx->fpriv->opriv, def_dev_ctx->tx_config.tx_lock); def_dev_ctx->twt_sleep_status = NRF_WIFI_FMAC_TWT_STATE_SLEEP; wifi_mgmt_raise_twt_sleep_state(vif_ctx_zep->zep_net_if_ctx, WIFI_TWT_STATE_SLEEP); nrf_wifi_osal_spinlock_rel(fmac_dev_ctx->fpriv->opriv, def_dev_ctx->tx_config.tx_lock); break; case TWT_UNBLOCK_TX: nrf_wifi_osal_spinlock_take(fmac_dev_ctx->fpriv->opriv, def_dev_ctx->tx_config.tx_lock); def_dev_ctx->twt_sleep_status = NRF_WIFI_FMAC_TWT_STATE_AWAKE; wifi_mgmt_raise_twt_sleep_state(vif_ctx_zep->zep_net_if_ctx, WIFI_TWT_STATE_AWAKE); #ifdef CONFIG_NRF70_DATA_TX for (ac = NRF_WIFI_FMAC_AC_BE; ac <= NRF_WIFI_FMAC_AC_MAX; ++ac) { desc = tx_desc_get(fmac_dev_ctx, ac); if (desc < def_priv->num_tx_tokens) { tx_pending_process(fmac_dev_ctx, desc, ac); } } #endif nrf_wifi_osal_spinlock_rel(fmac_dev_ctx->fpriv->opriv, def_dev_ctx->tx_config.tx_lock); break; default: break; } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); } #ifdef CONFIG_NRF70_SYSTEM_WITH_RAW_MODES int nrf_wifi_mode(const struct device *dev, struct wifi_mode_info *mode) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; int ret = -1; if (!dev || !mode) { LOG_ERR("%s: illegal input parameters", __func__); return ret; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; def_dev_ctx = wifi_dev_priv(fmac_dev_ctx); if (!device_is_ready(dev)) { LOG_ERR("%s: Device %s is not ready", __func__, dev->name); goto out; } if (mode->oper == WIFI_MGMT_SET) { status = nrf_wifi_check_mode_validity(mode->mode); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: mode setting is not valid", __func__); goto out; } if (vif_ctx_zep->authorized && (mode->mode == NRF_WIFI_MONITOR_MODE)) { LOG_ERR("%s: Cannot set monitor mode when station is connected", __func__); goto out; } /** * Send the driver vif_idx instead of upper layer sent if_index. * we map network if_index 1 to vif_idx of 0 and so on. The vif_ctx_zep * context maps the correct network interface index to current driver * interface index. */ status = nrf_wifi_fmac_set_mode(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, mode->mode); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: mode set operation failed", __func__); goto out; } } else { mode->mode = def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->mode; /** * This is a work-around to handle current UMAC mode handling. * This might be removed in future versions when UMAC has more space. */ #ifdef CONFIG_NRF70_RAW_DATA_TX if (def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->txinjection_mode == true) { mode->mode ^= NRF_WIFI_TX_INJECTION_MODE; } #endif /* CONFIG_NRF70_RAW_DATA_TX */ #ifdef CONFIG_NRF70_PROMISC_DATA_RX if (def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->promisc_mode == true) { mode->mode ^= NRF_WIFI_PROMISCUOUS_MODE; } #endif /* CONFIG_NRF70_PROMISC_DATA_RX */ } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } #endif /* CONFIG_NRF70_SYSTEM_WITH_RAW_MODES */ #if defined(CONFIG_NRF70_RAW_DATA_TX) || defined(CONFIG_NRF70_RAW_DATA_RX) int nrf_wifi_channel(const struct device *dev, struct wifi_channel_info *channel) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; int ret = -1; if (!dev || !channel) { LOG_ERR("%s: illegal input parameters", __func__); return ret; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return ret; } if (vif_ctx_zep->authorized) { LOG_ERR("%s: Cannot change channel when in station connected mode", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; def_dev_ctx = wifi_dev_priv(fmac_dev_ctx); if (channel->oper == WIFI_MGMT_SET) { /** * Send the driver vif_idx instead of upper layer sent if_index. * we map network if_index 1 to vif_idx of 0 and so on. The vif_ctx_zep * context maps the correct network interface index to current driver * interface index. */ status = nrf_wifi_fmac_set_channel(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, channel->channel); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: set channel failed", __func__); goto out; } } else { channel->channel = def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->channel; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } #endif /* CONFIG_NRF70_RAW_DATA_TX || CONFIG_NRF70_RAW_DATA_RX */ #if defined(CONFIG_NRF70_RAW_DATA_RX) || defined(CONFIG_NRF70_PROMISC_DATA_RX) int nrf_wifi_filter(const struct device *dev, struct wifi_filter_info *filter) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; int ret = -1; if (!dev || !filter) { LOG_ERR("%s: Illegal input parameters", __func__); goto out; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL\n", __func__); goto out; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; def_dev_ctx = wifi_dev_priv(fmac_dev_ctx); if (filter->oper == WIFI_MGMT_SET) { /** * In case a user sets data + management + ctrl bits * or all the filter bits. Map it to bit 0 set to * enable "all" packet filter bit setting. * In case only filter packet size is configured and filter * setting is sent as zero, set the filter value to * previously configured value. */ if (filter->filter == WIFI_MGMT_DATA_CTRL_FILTER_SETTING || filter->filter == WIFI_ALL_FILTER_SETTING) { filter->filter = 1; } else if (filter->filter == 0) { filter->filter = def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->packet_filter; } /** * Send the driver vif_idx instead of upper layer sent if_index. * we map network if_index 1 to vif_idx of 0 and so on. The vif_ctx_zep * context maps the correct network interface index to current driver * interface index */ status = nrf_wifi_fmac_set_packet_filter(rpu_ctx_zep->rpu_ctx, filter->filter, vif_ctx_zep->vif_idx, filter->buffer_size); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Set filter operation failed\n", __func__); goto out; } } else { filter->filter = def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]->packet_filter; } ret = 0; out: return ret; } #endif /* CONFIG_NRF70_RAW_DATA_RX || CONFIG_NRF70_PROMISC_DATA_RX */ int nrf_wifi_set_rts_threshold(const struct device *dev, unsigned int rts_threshold) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_umac_set_wiphy_info wiphy_info; int ret = -1; if (!dev) { LOG_ERR("%s: dev is NULL", __func__); return ret; } vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } if (!rpu_ctx_zep->rpu_ctx) { LOG_ERR("%s: RPU context not initialized", __func__); return ret; } if ((int)rts_threshold < -1) { /* 0 or any positive value is passed to f/w. * For RTS off, -1 is passed to f/w. * All other negative values considered as invalid. */ LOG_ERR("%s: Invalid threshold value : %d", __func__, (int)rts_threshold); return ret; } memset(&wiphy_info, 0, sizeof(struct nrf_wifi_umac_set_wiphy_info)); wiphy_info.rts_threshold = (int)rts_threshold; k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); status = nrf_wifi_fmac_set_wiphy_params(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &wiphy_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Configuring rts threshold failed\n", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/wifi_mgmt.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
8,845
```c /* * */ /** * @brief File containing display scan specific definitions for the * Zephyr OS layer of the Wi-Fi driver. */ #include <stdlib.h> #include <zephyr/kernel.h> #include <zephyr/logging/log.h> #include "util.h" #include "fmac_api.h" #include "fmac_tx.h" #include "fmac_main.h" #include "wifi_mgmt_scan.h" LOG_MODULE_DECLARE(wifi_nrf, CONFIG_WIFI_NRF70_LOG_LEVEL); extern struct nrf_wifi_drv_priv_zep rpu_drv_priv_zep; static enum nrf_wifi_band nrf_wifi_map_zep_band_to_rpu(enum wifi_frequency_bands zep_band) { switch (zep_band) { case WIFI_FREQ_BAND_2_4_GHZ: return NRF_WIFI_BAND_2GHZ; case WIFI_FREQ_BAND_5_GHZ: return NRF_WIFI_BAND_5GHZ; default: return NRF_WIFI_BAND_INVALID; } } int nrf_wifi_disp_scan_zep(const struct device *dev, struct wifi_scan_params *params, scan_result_cb_t cb) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_umac_scan_info *scan_info = NULL; enum nrf_wifi_band band = NRF_WIFI_BAND_INVALID; uint8_t band_flags = 0xFF; uint8_t i = 0; uint8_t j = 0; uint8_t k = 0; uint16_t num_scan_channels = 0; int ret = -1; vif_ctx_zep = dev->data; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return ret; } if (vif_ctx_zep->if_op_state != NRF_WIFI_FMAC_IF_OP_STATE_UP) { LOG_ERR("%s: Interface not UP", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; if (vif_ctx_zep->scan_in_progress) { LOG_INF("%s: Scan already in progress", __func__); ret = -EBUSY; goto out; } if (params) { band_flags &= (~(1 << WIFI_FREQ_BAND_2_4_GHZ)); #ifndef CONFIG_NRF70_2_4G_ONLY band_flags &= (~(1 << WIFI_FREQ_BAND_5_GHZ)); #endif /* CONFIG_NRF70_2_4G_ONLY */ if (params->bands & band_flags) { LOG_ERR("%s: Unsupported band(s) (0x%X)", __func__, params->bands); ret = -EBUSY; goto out; } for (j = 0; j < CONFIG_WIFI_MGMT_SCAN_CHAN_MAX_MANUAL; j++) { if (!params->band_chan[j].channel) { break; } num_scan_channels++; } } vif_ctx_zep->disp_scan_cb = cb; scan_info = k_calloc(sizeof(*scan_info) + (num_scan_channels * sizeof(scan_info->scan_params.center_frequency[0])), sizeof(char)); if (!scan_info) { LOG_ERR("%s: Unable to allocate memory for scan_info (size: %d bytes)", __func__, sizeof(*scan_info) + (num_scan_channels * sizeof(scan_info->scan_params.center_frequency[0]))); goto out; } memset(scan_info, 0, sizeof(*scan_info) + (num_scan_channels * sizeof(scan_info->scan_params.center_frequency[0]))); static uint8_t skip_local_admin_mac = IS_ENABLED(CONFIG_WIFI_NRF70_SKIP_LOCAL_ADMIN_MAC); scan_info->scan_params.skip_local_admin_macs = skip_local_admin_mac; scan_info->scan_reason = SCAN_DISPLAY; if (params) { if (params->scan_type == WIFI_SCAN_TYPE_PASSIVE) { scan_info->scan_params.passive_scan = 1; } scan_info->scan_params.bands = params->bands; if (params->dwell_time_active < 0) { LOG_ERR("%s: Invalid dwell_time_active %d", __func__, params->dwell_time_active); goto out; } else { scan_info->scan_params.dwell_time_active = params->dwell_time_active; } if (params->dwell_time_passive < 0) { LOG_ERR("%s: Invalid dwell_time_passive %d", __func__, params->dwell_time_passive); goto out; } else { scan_info->scan_params.dwell_time_passive = params->dwell_time_passive; } if ((params->max_bss_cnt < 0) || (params->max_bss_cnt > WIFI_MGMT_SCAN_MAX_BSS_CNT)) { LOG_ERR("%s: Invalid max_bss_cnt %d", __func__, params->max_bss_cnt); goto out; } else { vif_ctx_zep->max_bss_cnt = params->max_bss_cnt; } for (i = 0; i < NRF_WIFI_SCAN_MAX_NUM_SSIDS; i++) { if (!(params->ssids[i]) || !strlen(params->ssids[i])) { break; } memcpy(scan_info->scan_params.scan_ssids[i].nrf_wifi_ssid, params->ssids[i], sizeof(scan_info->scan_params.scan_ssids[i].nrf_wifi_ssid)); scan_info->scan_params.scan_ssids[i].nrf_wifi_ssid_len = strlen(scan_info->scan_params.scan_ssids[i].nrf_wifi_ssid); scan_info->scan_params.num_scan_ssids++; } for (i = 0; i < CONFIG_WIFI_MGMT_SCAN_CHAN_MAX_MANUAL; i++) { if (!params->band_chan[i].channel) { break; } band = nrf_wifi_map_zep_band_to_rpu(params->band_chan[i].band); if (band == NRF_WIFI_BAND_INVALID) { LOG_ERR("%s: Unsupported band %d", __func__, params->band_chan[i].band); goto out; } scan_info->scan_params.center_frequency[k++] = nrf_wifi_utils_chan_to_freq( fmac_dev_ctx->fpriv->opriv, band, params->band_chan[i].channel); if (scan_info->scan_params.center_frequency[k - 1] == -1) { LOG_ERR("%s: Invalid channel %d", __func__, params->band_chan[i].channel); goto out; } } scan_info->scan_params.num_scan_channels = k; } vif_ctx_zep->scan_res_cnt = 0; status = nrf_wifi_fmac_scan(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, scan_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_scan failed", __func__); goto out; } vif_ctx_zep->scan_type = SCAN_DISPLAY; vif_ctx_zep->scan_in_progress = true; k_work_schedule(&vif_ctx_zep->scan_timeout_work, K_SECONDS(CONFIG_WIFI_NRF70_SCAN_TIMEOUT_S)); ret = 0; out: if (scan_info) { k_free(scan_info); } k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } enum nrf_wifi_status nrf_wifi_disp_scan_res_get_zep(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return NRF_WIFI_STATUS_FAIL; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } status = nrf_wifi_fmac_scan_res_get(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, SCAN_DISPLAY); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_scan failed", __func__); goto out; } status = NRF_WIFI_STATUS_SUCCESS; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return status; } static inline enum wifi_mfp_options drv_to_wifi_mgmt_mfp(unsigned char mfp_flag) { if (!mfp_flag) return WIFI_MFP_DISABLE; if (mfp_flag & NRF_WIFI_MFP_REQUIRED) return WIFI_MFP_REQUIRED; if (mfp_flag & NRF_WIFI_MFP_CAPABLE) return WIFI_MFP_OPTIONAL; return WIFI_MFP_UNKNOWN; } static inline enum wifi_security_type drv_to_wifi_mgmt(int drv_security_type) { switch (drv_security_type) { case NRF_WIFI_OPEN: return WIFI_SECURITY_TYPE_NONE; case NRF_WIFI_WEP: return WIFI_SECURITY_TYPE_WEP; case NRF_WIFI_WPA: return WIFI_SECURITY_TYPE_WPA_PSK; case NRF_WIFI_WPA2: return WIFI_SECURITY_TYPE_PSK; case NRF_WIFI_WPA2_256: return WIFI_SECURITY_TYPE_PSK_SHA256; case NRF_WIFI_WPA3: return WIFI_SECURITY_TYPE_SAE; case NRF_WIFI_WAPI: return WIFI_SECURITY_TYPE_WAPI; case NRF_WIFI_EAP: return WIFI_SECURITY_TYPE_EAP; default: return WIFI_SECURITY_TYPE_UNKNOWN; } } void nrf_wifi_event_proc_disp_scan_res_zep(void *vif_ctx, struct nrf_wifi_umac_event_new_scan_display_results *scan_res, unsigned int event_len, bool more_res) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct umac_display_results *r = NULL; struct wifi_scan_result res; uint16_t max_bss_cnt = 0; unsigned int i = 0; scan_result_cb_t cb = NULL; vif_ctx_zep = vif_ctx; cb = (scan_result_cb_t)vif_ctx_zep->disp_scan_cb; /* Delayed event (after scan timeout) or rogue event after scan done */ if (!cb) { return; } max_bss_cnt = vif_ctx_zep->max_bss_cnt ? vif_ctx_zep->max_bss_cnt : CONFIG_NRF_WIFI_SCAN_MAX_BSS_CNT; for (i = 0; i < scan_res->event_bss_count; i++) { /* Limit the scan results to the configured maximum */ if ((max_bss_cnt > 0) && (vif_ctx_zep->scan_res_cnt >= max_bss_cnt)) { break; } memset(&res, 0x0, sizeof(res)); r = &scan_res->display_results[i]; res.ssid_length = MIN(sizeof(res.ssid), r->ssid.nrf_wifi_ssid_len); res.band = r->nwk_band; res.channel = r->nwk_channel; res.security = drv_to_wifi_mgmt(r->security_type); res.mfp = drv_to_wifi_mgmt_mfp(r->mfp_flag); memcpy(res.ssid, r->ssid.nrf_wifi_ssid, res.ssid_length); memcpy(res.mac, r->mac_addr, NRF_WIFI_ETH_ADDR_LEN); res.mac_length = NRF_WIFI_ETH_ADDR_LEN; if (r->signal.signal_type == NRF_WIFI_SIGNAL_TYPE_MBM) { int val = (r->signal.signal.mbm_signal); res.rssi = (val / 100); } else if (r->signal.signal_type == NRF_WIFI_SIGNAL_TYPE_UNSPEC) { res.rssi = (r->signal.signal.unspec_signal); } vif_ctx_zep->disp_scan_cb(vif_ctx_zep->zep_net_if_ctx, 0, &res); vif_ctx_zep->scan_res_cnt++; /* NET_MGMT dropping events if too many are queued */ k_yield(); } if (more_res == false) { vif_ctx_zep->disp_scan_cb(vif_ctx_zep->zep_net_if_ctx, 0, NULL); vif_ctx_zep->scan_in_progress = false; vif_ctx_zep->disp_scan_cb = NULL; k_work_cancel_delayable(&vif_ctx_zep->scan_timeout_work); } } #ifdef CONFIG_WIFI_MGMT_RAW_SCAN_RESULTS void nrf_wifi_rx_bcn_prb_resp_frm(void *vif_ctx, void *nwb, unsigned short frequency, signed short signal) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = vif_ctx; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; struct wifi_raw_scan_result bcn_prb_resp_info; int frame_length = 0; int val = signal; vif_ctx_zep = vif_ctx; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return; } if (!vif_ctx_zep->scan_in_progress) { /*LOG_INF("%s: Scan not in progress : raw scan data not available", __func__);*/ return; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; frame_length = nrf_wifi_osal_nbuf_data_size(fmac_dev_ctx->fpriv->opriv, nwb); if (frame_length > CONFIG_WIFI_MGMT_RAW_SCAN_RESULT_LENGTH) { nrf_wifi_osal_mem_cpy(fmac_dev_ctx->fpriv->opriv, &bcn_prb_resp_info.data, nrf_wifi_osal_nbuf_data_get( fmac_dev_ctx->fpriv->opriv, nwb), CONFIG_WIFI_MGMT_RAW_SCAN_RESULT_LENGTH); } else { nrf_wifi_osal_mem_cpy(fmac_dev_ctx->fpriv->opriv, &bcn_prb_resp_info.data, nrf_wifi_osal_nbuf_data_get( fmac_dev_ctx->fpriv->opriv, nwb), frame_length); } bcn_prb_resp_info.rssi = MBM_TO_DBM(val); bcn_prb_resp_info.frequency = frequency; bcn_prb_resp_info.frame_length = frame_length; wifi_mgmt_raise_raw_scan_result_event(vif_ctx_zep->zep_net_if_ctx, &bcn_prb_resp_info); out: k_mutex_unlock(&vif_ctx_zep->vif_lock); } #endif /* CONFIG_WIFI_MGMT_RAW_SCAN_RESULTS */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/wifi_mgmt_scan.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,476
```objective-c /* * */ /** * @brief Header containing OS interface specific declarations for the * Zephyr OS layer of the Wi-Fi driver. */ #ifndef __SHIM_H__ #define __SHIM_H__ #include <zephyr/kernel.h> #include <zephyr/drivers/gpio.h> #include <zephyr/net/net_pkt.h> /** * struct zep_shim_bus_qspi_priv - Structure to hold context information for the Linux OS * shim. * @opriv: Pointer to OSAL context. * @pcie_callbk_data: Callback data to be passed to the PCIe callback functions. * @pcie_prb_callbk: The callback function to be called when a PCIe device * has been probed. * @pcie_rem_callbk: The callback function to be called when a PCIe device * has been removed. * * This structure maintains the context information necessary for the operation * of the Linux shim. Some of the elements of the structure need to be * initialized during the initialization of the Linux shim while others need to * be kept updated over the duration of the Linux shim operation. */ struct zep_shim_bus_qspi_priv { void *qspi_dev; bool dev_added; bool dev_init; }; struct zep_shim_intr_priv { struct gpio_callback gpio_cb_data; void *callbk_data; int (*callbk_fn)(void *callbk_data); struct k_work_delayable work; }; struct zep_shim_llist_node { sys_dnode_t head; void *data; }; struct zep_shim_llist { sys_dlist_t head; unsigned int len; }; void *net_pkt_to_nbuf(struct net_pkt *pkt); void *net_pkt_from_nbuf(void *iface, void *frm); #if defined(CONFIG_NRF70_RAW_DATA_RX) || defined(CONFIG_NRF70_PROMISC_DATA_RX) void *net_raw_pkt_from_nbuf(void *iface, void *frm, unsigned short raw_hdr_len, void *raw_rx_hdr, bool pkt_free); #endif /* CONFIG_NRF70_RAW_DATA_RX || CONFIG_NRF70_PROMISC_DATA_RX */ #endif /* __SHIM_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/shim.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
452
```c /* * */ /** @file * @brief Coexistence functions */ #include <stdio.h> #include <stdlib.h> #include <zephyr/kernel.h> #include <zephyr/logging/log.h> #include <zephyr/drivers/gpio.h> #include "coex.h" #include "coex_struct.h" #include "fmac_main.h" #include "fmac_api.h" LOG_MODULE_DECLARE(wifi_nrf, CONFIG_WIFI_NRF70_LOG_LEVEL); extern struct nrf_wifi_drv_priv_zep rpu_drv_priv_zep; static struct nrf_wifi_ctx_zep *rpu_ctx = &rpu_drv_priv_zep.rpu_ctx_zep; #define CH_BASE_ADDRESS ABS_EXT_SYS_WLANSYSCOEX_CH_CONTROL #define COEX_CONFIG_FIXED_PARAMS 4 #define COEX_REG_CFG_OFFSET_SHIFT 24 /* copied from uccp530_77_registers_ext_sys_bus.h of UCCP toolkit */ #define EXT_SYS_WLANSYSCOEX_CH_CONTROL 0x0000 #define ABS_EXT_SYS_WLANSYSCOEX_CH_CONTROL 0xA401BC00UL #define EXT_SYS_WLANSYSCOEX_CH_TIME_REFERENCE 0x0004 #define EXT_SYS_WLANSYSCOEX_CH_SR_INFO_STATUS 0x0040 #define EXT_SYS_WLANSYSCOEX_CH_NO_WINDOW_LOOKUP_0 0x008C #define EXT_SYS_WLANSYSCOEX_CH_NO_WINDOW_LOOKUP_44 0x013C #define EXT_SYS_WLANSYSCOEX_RESET_SHIFT 0 /* copied from uccp530_77_registers.h of UCCP toolkit */ #define ABS_PMB_WLAN_MAC_CTRL_PULSED_SOFTWARE_RESET 0xA5009A00UL #ifdef CONFIG_NRF70_SR_COEX_RF_SWITCH #define NRF_RADIO_COEX_NODE DT_NODELABEL(nrf70) static const struct gpio_dt_spec sr_rf_switch_spec = GPIO_DT_SPEC_GET(NRF_RADIO_COEX_NODE, srrf_switch_gpios); #endif /* CONFIG_NRF70_SR_COEX_RF_SWITCH */ /* PTA registers configuration of Coexistence Hardware */ /* Separate antenna configuration, WLAN in 2.4GHz. For BLE protocol. */ const uint16_t config_buffer_SEA_ble[] = { 0x0019, 0x00F6, 0x0008, 0x0062, 0x00F5, 0x00F5, 0x0019, 0x0019, 0x0074, 0x0074, 0x0008, 0x01E2, 0x00D5, 0x00D5, 0x01F6, 0x01F6, 0x0061, 0x0061, 0x01E2, 0x0008, 0x0004, 0x0004, 0x0019, 0x0019, 0x0008, 0x0008, 0x00F5, 0x00F5, 0x00D5, 0x00D5, 0x0008, 0x01E2, 0x0051, 0x0051, 0x0074, 0x0074, 0x00F6, 0x0019, 0x0062, 0x0019, 0x00F6, 0x0008, 0x0062, 0x0008, 0x001A }; /* Separate antenna configuration, WLAN in 2.4GHz. For non BLE protocol */ const uint16_t config_buffer_SEA_non_ble[] = { 0x0019, 0x00F6, 0x0008, 0x0062, 0x00F5, 0x00F5, 0x0061, 0x0061, 0x0074, 0x0074, 0x01E2, 0x01E2, 0x00D5, 0x00D5, 0x01F6, 0x01F6, 0x0061, 0x0061, 0x01E2, 0x01E2, 0x00C4, 0x00C4, 0x0061, 0x0061, 0x0008, 0x0008, 0x00F5, 0x00F5, 0x00D5, 0x00D5, 0x0162, 0x0162, 0x0019, 0x0019, 0x01F6, 0x01F6, 0x00F6, 0x0019, 0x0062, 0x0019, 0x00F6, 0x0008, 0x0062, 0x0008, 0x001A }; /* Shared antenna configuration, WLAN in 2.4GHz. */ const uint16_t config_buffer_SHA[] = { 0x0019, 0x00F6, 0x0008, 0x00E2, 0x0015, 0x00F5, 0x0019, 0x0019, 0x0004, 0x01F6, 0x0008, 0x01E2, 0x00F5, 0x00F5, 0x01F6, 0x01F6, 0x00E1, 0x00E1, 0x01E2, 0x0008, 0x0004, 0x0004, 0x0019, 0x0019, 0x0008, 0x0008, 0x0015, 0x00F5, 0x00F5, 0x00F5, 0x0008, 0x01E2, 0x00E1, 0x00E1, 0x0004, 0x01F6, 0x00F6, 0x0019, 0x00E2, 0x0019, 0x00F6, 0x0008, 0x00E2, 0x0008, 0x001A }; /* Shared/separate antennas, WLAN in 5GHz */ const uint16_t config_buffer_5G[] = { 0x0039, 0x0076, 0x0028, 0x0062, 0x0075, 0x0075, 0x0061, 0x0061, 0x0074, 0x0074, 0x0060, 0x0060, 0x0075, 0x0075, 0x0064, 0x0064, 0x0071, 0x0071, 0x0060, 0x0060, 0x0064, 0x0064, 0x0061, 0x0061, 0x0060, 0x0060, 0x0075, 0x0075, 0x0075, 0x0075, 0x0060, 0x0060, 0x0071, 0x0071, 0x0074, 0x0074, 0x0076, 0x0039, 0x0062, 0x0039, 0x0076, 0x0028, 0x0062, 0x0028, 0x003A }; /* non-PTA register configuration of coexistence hardware */ /* Shared antenna */ const uint32_t ch_config_sha[] = { 0x00000028, 0x00000000, 0x001e1023, 0x00000000, 0x00000000, 0x00000000, 0x00000021, 0x000002ca, 0x00000050, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; /* Separate antennas. For BLE protocol. */ const uint32_t ch_config_sep_ble[] = { 0x00000028, 0x00000000, 0x001e1023, 0x00000000, 0x00000000, 0x00000000, 0x00000021, 0x000002ca, 0x00000055, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; /* Separate antennas. For non BLE protocol. */ const uint32_t ch_config_sep_non_ble[] = { 0x00000028, 0x00000000, 0x001e1023, 0x00000000, 0x00000000, 0x00000000, 0x00000021, 0x000002ca, 0x00000055, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; int nrf_wifi_coex_config_non_pta(bool separate_antennas, bool is_sr_protocol_ble) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct coex_ch_configuration params = { 0 }; const uint32_t *config_buffer_ptr = NULL; uint32_t start_offset = 0; uint32_t num_reg_to_config = 1; uint32_t cmd_len, index; /* Offset from the base address of CH */ start_offset = ((EXT_SYS_WLANSYSCOEX_CH_TIME_REFERENCE - EXT_SYS_WLANSYSCOEX_CH_CONTROL) >> 2); /* Number of registers to be configured */ num_reg_to_config = ((EXT_SYS_WLANSYSCOEX_CH_SR_INFO_STATUS - EXT_SYS_WLANSYSCOEX_CH_TIME_REFERENCE) >> 2) + 1; if (separate_antennas) { if (is_sr_protocol_ble) { config_buffer_ptr = ch_config_sep_ble; } else { config_buffer_ptr = ch_config_sep_non_ble; } } else { config_buffer_ptr = ch_config_sha; } params.message_id = HW_CONFIGURATION; params.num_reg_to_config = num_reg_to_config; params.hw_to_config = COEX_HARDWARE; params.hw_block_base_addr = CH_BASE_ADDRESS; for (index = 0; index < num_reg_to_config; index++) { params.configbuf[index] = (start_offset << COEX_REG_CFG_OFFSET_SHIFT) | (*(config_buffer_ptr + index)); start_offset++; } cmd_len = (COEX_CONFIG_FIXED_PARAMS + num_reg_to_config) * sizeof(uint32_t); status = nrf_wifi_fmac_conf_srcoex(rpu_ctx->rpu_ctx, (void *)(&params), cmd_len); if (status != NRF_WIFI_STATUS_SUCCESS) { return -1; } return 0; } int nrf_wifi_coex_config_pta(enum nrf_wifi_pta_wlan_op_band wlan_band, bool separate_antennas, bool is_sr_protocol_ble) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct coex_ch_configuration params = { 0 }; const uint16_t *config_buffer_ptr = NULL; uint32_t start_offset = 0; uint32_t num_reg_to_config = 1; uint32_t cmd_len, index; /* common for both SHA and SEA */ /* Indicates offset from the base address of CH */ start_offset = ((EXT_SYS_WLANSYSCOEX_CH_NO_WINDOW_LOOKUP_0 - EXT_SYS_WLANSYSCOEX_CH_CONTROL) >> 2); /* Number of contiguous registers to be configured starting from base+offset */ num_reg_to_config = ((EXT_SYS_WLANSYSCOEX_CH_NO_WINDOW_LOOKUP_44 - EXT_SYS_WLANSYSCOEX_CH_NO_WINDOW_LOOKUP_0) >> 2) + 1; if (wlan_band == NRF_WIFI_PTA_WLAN_OP_BAND_2_4_GHZ) { /* WLAN operating in 2.4GHz */ if (separate_antennas) { /* separate antennas configuration */ if (is_sr_protocol_ble) { config_buffer_ptr = config_buffer_SEA_ble; } else { config_buffer_ptr = config_buffer_SEA_non_ble; } } else { /* Shared antenna configuration */ config_buffer_ptr = config_buffer_SHA; } } else if (wlan_band == NRF_WIFI_PTA_WLAN_OP_BAND_5_GHZ) { /* WLAN operating in 5GHz */ config_buffer_ptr = config_buffer_5G; } else { return -EINVAL; } params.message_id = HW_CONFIGURATION; params.num_reg_to_config = num_reg_to_config; params.hw_to_config = COEX_HARDWARE; params.hw_block_base_addr = CH_BASE_ADDRESS; for (index = 0; index < num_reg_to_config; index++) { params.configbuf[index] = (start_offset << COEX_REG_CFG_OFFSET_SHIFT) | (*(config_buffer_ptr+index)); start_offset++; } cmd_len = (COEX_CONFIG_FIXED_PARAMS + num_reg_to_config) * sizeof(uint32_t); status = nrf_wifi_fmac_conf_srcoex(rpu_ctx->rpu_ctx, (void *)(&params), cmd_len); if (status != NRF_WIFI_STATUS_SUCCESS) { return -1; } return 0; } #ifdef CONFIG_NRF70_SR_COEX_RF_SWITCH int nrf_wifi_config_sr_switch(bool separate_antennas) { int ret; if (!device_is_ready(sr_rf_switch_spec.port)) { LOG_ERR("Unable to open GPIO device"); return -ENODEV; } ret = gpio_pin_configure_dt(&sr_rf_switch_spec, GPIO_OUTPUT); if (ret < 0) { LOG_ERR("Unable to configure GPIO device"); return -1; } if (separate_antennas) { gpio_pin_set_dt(&sr_rf_switch_spec, 0x0); LOG_INF("GPIO P1.10 set to 0"); } else { gpio_pin_set_dt(&sr_rf_switch_spec, 0x1); LOG_INF("GPIO P1.10 set to 1"); } return 0; } #endif /* CONFIG_NRF70_SR_COEX_RF_SWITCH */ int nrf_wifi_coex_hw_reset(void) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct coex_ch_configuration params = { 0 }; uint32_t num_reg_to_config = 1; uint32_t start_offset = 0; uint32_t index = 0; uint32_t coex_hw_reset = 1; uint32_t cmd_len; /* reset CH */ params.message_id = HW_CONFIGURATION; params.num_reg_to_config = num_reg_to_config; params.hw_to_config = COEX_HARDWARE; params.hw_block_base_addr = CH_BASE_ADDRESS; start_offset = ((EXT_SYS_WLANSYSCOEX_CH_CONTROL - EXT_SYS_WLANSYSCOEX_CH_CONTROL) >> 2); params.configbuf[index] = (start_offset << COEX_REG_CFG_OFFSET_SHIFT) | (coex_hw_reset << EXT_SYS_WLANSYSCOEX_RESET_SHIFT); cmd_len = (COEX_CONFIG_FIXED_PARAMS + num_reg_to_config) * sizeof(uint32_t); status = nrf_wifi_fmac_conf_srcoex(rpu_ctx->rpu_ctx, (void *)(&params), cmd_len); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("CH reset configuration failed"); return -1; } return 0; } #ifdef CONFIG_NRF70_SR_COEX_RF_SWITCH int sr_gpio_config(void) { int ret; if (!device_is_ready(sr_rf_switch_spec.port)) { return -ENODEV; } ret = gpio_pin_configure_dt(&sr_rf_switch_spec, GPIO_OUTPUT); if (ret) { LOG_ERR("SR GPIO configuration failed %d", ret); } return ret; } int sr_gpio_remove(void) { int ret; ret = gpio_pin_configure_dt(&sr_rf_switch_spec, GPIO_DISCONNECTED); if (ret) { LOG_ERR("SR GPIO remove failed %d", ret); } return ret; } int sr_ant_switch(unsigned int ant_switch) { int ret; ret = gpio_pin_set_dt(&sr_rf_switch_spec, ant_switch & 0x1); if (ret) { LOG_ERR("SR GPIO set failed %d", ret); } return ret; } #endif /* CONFIG_NRF70_SR_COEX_RF_SWITCH */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/coex.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,702
```c /* * */ /** * @brief File containing timer specific definitons for the * Zephyr OS layer of the Wi-Fi driver. */ #include <stdio.h> #include <string.h> #include <zephyr/kernel.h> #include <zephyr/sys/printk.h> #include <zephyr/drivers/gpio.h> #include "timer.h" static void timer_expiry_function(struct k_work *work) { struct timer_list *timer; timer = (struct timer_list *)CONTAINER_OF(work, struct timer_list, work.work); timer->function(timer->data); } void init_timer(struct timer_list *timer) { k_work_init_delayable(&timer->work, timer_expiry_function); } void mod_timer(struct timer_list *timer, int msec) { k_work_schedule(&timer->work, K_MSEC(msec)); } void del_timer_sync(struct timer_list *timer) { k_work_cancel_delayable(&timer->work); } ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/timer.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
192
```c /* * */ /* @file * @brief NRF Wi-Fi radio FICR programming functions */ #include <zephyr/logging/log.h> #include <zephyr/kernel.h> #include "rpu_if.h" #include "rpu_hw_if.h" #include "ficr_prog.h" LOG_MODULE_DECLARE(otp_prog, CONFIG_WIFI_NRF70_BUS_LOG_LEVEL); static void write_word(unsigned int addr, unsigned int data) { rpu_write(addr, &data, 4); } static void read_word(unsigned int addr, unsigned int *data) { rpu_read(addr, data, 4); } unsigned int check_protection(unsigned int *buff, unsigned int off1, unsigned int off2, unsigned int off3, unsigned int off4) { if ((buff[off1] == OTP_PROGRAMMED) && (buff[off2] == OTP_PROGRAMMED) && (buff[off3] == OTP_PROGRAMMED) && (buff[off4] == OTP_PROGRAMMED)) return OTP_PROGRAMMED; else if ((buff[off1] == OTP_FRESH_FROM_FAB) && (buff[off2] == OTP_FRESH_FROM_FAB) && (buff[off3] == OTP_FRESH_FROM_FAB) && (buff[off4] == OTP_FRESH_FROM_FAB)) return OTP_FRESH_FROM_FAB; else if ((buff[off1] == OTP_ENABLE_PATTERN) && (buff[off2] == OTP_ENABLE_PATTERN) && (buff[off3] == OTP_ENABLE_PATTERN) && (buff[off4] == OTP_ENABLE_PATTERN)) return OTP_ENABLE_PATTERN; else return OTP_INVALID; } static void set_otp_timing_reg_40mhz(void) { write_word(OTP_TIMING_REG1_ADDR, OTP_TIMING_REG1_VAL); write_word(OTP_TIMING_REG2_ADDR, OTP_TIMING_REG2_VAL); } static int poll_otp_ready(void) { int otp_mem_status = 0; int poll = 0; while (poll != 100) { read_word(OTP_POLL_ADDR, &otp_mem_status); if ((otp_mem_status & OTP_READY) == OTP_READY) { return 0; } poll++; } LOG_ERR("OTP is not ready"); return -ENOEXEC; } static int req_otp_standby_mode(void) { write_word(OTP_RWSBMODE_ADDR, 0x0); return poll_otp_ready(); } static int otp_wr_voltage_2V5(void) { int err; err = req_otp_standby_mode(); if (err) { LOG_ERR("Failed Setting OTP voltage IOVDD to 2.5V"); return -ENOEXEC; } write_word(OTP_VOLTCTRL_ADDR, OTP_VOLTCTRL_2V5); return 0; } static int poll_otp_read_valid(void) { int otp_mem_status = 0; int poll = 0; while (poll < 100) { read_word(OTP_POLL_ADDR, &otp_mem_status); if ((otp_mem_status & OTP_READ_VALID) == OTP_READ_VALID) { return 0; } poll++; } LOG_ERR("%s: OTP read failed", __func__); return -ENOEXEC; } static int poll_otp_wrdone(void) { int otp_mem_status = 0; int poll = 0; while (poll < 100) { read_word(OTP_POLL_ADDR, &otp_mem_status); if ((otp_mem_status & OTP_WR_DONE) == OTP_WR_DONE) { return 0; } poll++; } LOG_ERR("%s: OTP write done failed", __func__); return -ENOEXEC; } static int req_otp_read_mode(void) { write_word(OTP_RWSBMODE_ADDR, OTP_READ_MODE); return poll_otp_ready(); } static int req_otp_byte_write_mode(void) { write_word(OTP_RWSBMODE_ADDR, OTP_BYTE_WRITE_MODE); return poll_otp_ready(); } static unsigned int read_otp_location(unsigned int offset, unsigned int *read_val) { int err; write_word(OTP_RDENABLE_ADDR, offset); err = poll_otp_read_valid(); if (err) { LOG_ERR("OTP read failed"); return err; } read_word(OTP_READREG_ADDR, read_val); return 0; } static int write_otp_location(unsigned int otp_location_offset, unsigned int otp_data) { write_word(OTP_WRENABLE_ADDR, otp_location_offset); write_word(OTP_WRITEREG_ADDR, otp_data); return poll_otp_wrdone(); } static int otp_rd_voltage_1V8(void) { int err; err = req_otp_standby_mode(); if (err) { LOG_ERR("error in %s", __func__); return err; } write_word(OTP_VOLTCTRL_ADDR, OTP_VOLTCTRL_1V8); return 0; } static int update_mac_addr(unsigned int index, unsigned int *write_val) { int ret = 0; for (int i = 0; i < 2; i++) { ret = write_otp_location(MAC0_ADDR + 2 * index + i, write_val[i]); if (ret == -ENOEXEC) { LOG_ERR("FICR: Failed to update MAC ADDR%d", index); break; } LOG_INF("mac addr %d : Reg%d (0x%x) = 0x%04x", index, (i+1), (MAC0_ADDR + i) << 2, write_val[i]); } return ret; } int write_otp_memory(unsigned int otp_addr, unsigned int *write_val) { int err = 0; int mask_val; int ret = 0; int retrim_loc = 0; err = poll_otp_ready(); if (err) { LOG_ERR("err in otp ready poll"); return err; } set_otp_timing_reg_40mhz(); err = otp_wr_voltage_2V5(); if (err) { LOG_ERR("error in write_voltage 2V5"); goto _exit_otp_write; } err = req_otp_byte_write_mode(); if (err) { LOG_ERR("error in OTP byte write mode"); goto _exit_otp_write; } switch (otp_addr) { case REGION_PROTECT: write_otp_location(REGION_PROTECT, write_val[0]); write_otp_location(REGION_PROTECT+1, write_val[0]); write_otp_location(REGION_PROTECT+2, write_val[0]); write_otp_location(REGION_PROTECT+3, write_val[0]); LOG_INF("Written REGION_PROTECT0 (0x%x) : 0x%04x", (REGION_PROTECT << 2), write_val[0]); LOG_INF("Written REGION_PROTECT1 (0x%x) : 0x%04x", (REGION_PROTECT+1) << 2, write_val[0]); LOG_INF("Written REGION_PROTECT2 (0x%x) : 0x%04x", (REGION_PROTECT+2) << 2, write_val[0]); LOG_INF("Written REGION_PROTECT3 (0x%x) : 0x%04x", (REGION_PROTECT+3) << 2, write_val[0]); break; case QSPI_KEY: mask_val = QSPI_KEY_FLAG_MASK; for (int i = 0; i < QSPI_KEY_LENGTH_BYTES / 4; i++) { ret = write_otp_location(QSPI_KEY + i, write_val[i]); if (ret == -ENOEXEC) { LOG_ERR("FICR: Failed to write QSPI key offset-%d", QSPI_KEY + i); goto _exit_otp_write; } LOG_INF("Written QSPI_KEY0 (0x%x) : 0x%04x", (QSPI_KEY + i) << 2, write_val[i]); } write_otp_location(REGION_DEFAULTS, mask_val); LOG_INF("Written REGION_DEFAULTS (0x%x) : 0x%04x", (REGION_DEFAULTS) << 2, mask_val); break; case MAC0_ADDR: mask_val = MAC0_ADDR_FLAG_MASK; ret = update_mac_addr(0, write_val); if (ret == -ENOEXEC) { goto _exit_otp_write; } write_otp_location(REGION_DEFAULTS, mask_val); LOG_INF("Written MAC address 0"); LOG_INF("Written REGION_DEFAULTS (0x%x) : 0x%04x", (REGION_DEFAULTS) << 2, mask_val); break; case MAC1_ADDR: mask_val = MAC1_ADDR_FLAG_MASK; ret = update_mac_addr(1, write_val); if (ret == -ENOEXEC) { goto _exit_otp_write; } write_otp_location(REGION_DEFAULTS, mask_val); LOG_INF("Written MAC address 1"); LOG_INF("Written REGION_DEFAULTS (0x%x) : 0x%04x", (REGION_DEFAULTS) << 2, mask_val); break; case CALIB_XO: mask_val = CALIB_XO_FLAG_MASK; ret = write_otp_location(CALIB_XO, write_val[0]); if (ret == -ENOEXEC) { LOG_ERR("XO_Update Exception"); goto _exit_otp_write; } else { write_otp_location(REGION_DEFAULTS, mask_val); LOG_INF("Written CALIB_XO (0x%x) to 0x%04x", CALIB_XO << 2, write_val[0]); LOG_INF("Written REGION_DEFAULTS (0x%x) : 0x%04x", (REGION_DEFAULTS) << 2, mask_val); } break; case PRODRETEST_PROGVERSION: ret = write_otp_location(PRODRETEST_PROGVERSION, *write_val); if (ret == -ENOEXEC) { LOG_ERR("PRODRETEST.PROGVERSION_Update Exception"); goto _exit_otp_write; } else { LOG_INF("Written PRODRETEST.PROGVERSION 0x%04x", *write_val); } break; case PRODRETEST_TRIM0: case PRODRETEST_TRIM1: case PRODRETEST_TRIM2: case PRODRETEST_TRIM3: case PRODRETEST_TRIM4: case PRODRETEST_TRIM5: case PRODRETEST_TRIM6: case PRODRETEST_TRIM7: case PRODRETEST_TRIM8: case PRODRETEST_TRIM9: case PRODRETEST_TRIM10: case PRODRETEST_TRIM11: case PRODRETEST_TRIM12: case PRODRETEST_TRIM13: case PRODRETEST_TRIM14: retrim_loc = otp_addr - PRODRETEST_TRIM0; ret = write_otp_location(otp_addr, *write_val); if (ret == -ENOEXEC) { LOG_ERR("PRODRETEST.TRIM_Update Exception"); goto _exit_otp_write; } else { LOG_INF("Written PRODRETEST.TRIM%d 0x%04x", retrim_loc, *write_val); } break; case REGION_DEFAULTS: write_otp_location(REGION_DEFAULTS, write_val[0]); LOG_INF("Written REGION_DEFAULTS (0x%x) to 0x%04x", REGION_DEFAULTS << 2, write_val[0]); break; default: LOG_ERR("unknown field received: %d", otp_addr); } return ret; _exit_otp_write: err = req_otp_standby_mode(); err |= otp_rd_voltage_1V8(); return err; } int read_otp_memory(unsigned int otp_addr, unsigned int *read_val, int len) { int err; err = poll_otp_ready(); if (err) { LOG_ERR("err in otp ready poll"); return -ENOEXEC; } set_otp_timing_reg_40mhz(); err = otp_rd_voltage_1V8(); if (err) { LOG_ERR("error in read_voltage 1V8"); return -ENOEXEC; } err = req_otp_read_mode(); if (err) { LOG_ERR("error in req_otp_read_mode()"); return -ENOEXEC; } for (int i = 0; i < len; i++) { read_otp_location(otp_addr + i, &read_val[i]); } return req_otp_standby_mode(); } ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/qspi/src/ficr_prog.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,769
```c /* * */ /** * @brief File containing QSPI device interface specific definitions for the * Zephyr OS layer of the Wi-Fi driver. */ #include <errno.h> #include <string.h> #include <zephyr/init.h> #include <zephyr/logging/log.h> #include <zephyr/drivers/pinctrl.h> #include <soc.h> #include <nrf_erratas.h> #include <nrfx_qspi.h> #include <hal/nrf_clock.h> #include <hal/nrf_gpio.h> #include "spi_nor.h" #include "qspi_if.h" /* The QSPI bus node which the NRF70 is on */ #define QSPI_IF_BUS_NODE DT_NODELABEL(qspi) /* QSPI bus properties from the devicetree */ #define QSPI_IF_BUS_IRQN DT_IRQN(QSPI_IF_BUS_NODE) #define QSPI_IF_BUS_IRQ_PRIO DT_IRQ(QSPI_IF_BUS_NODE, priority) #define QSPI_IF_BUS_SCK_PIN DT_PROP(QSPI_IF_BUS_NODE, sck_pin) #define QSPI_IF_BUS_CSN_PIN DT_PROP(QSPI_IF_BUS_NODE, csn_pins) #define QSPI_IF_BUS_IO0_PIN DT_PROP_BY_IDX(QSPI_IF_BUS_NODE, io_pins, 0) #define QSPI_IF_BUS_IO1_PIN DT_PROP_BY_IDX(QSPI_IF_BUS_NODE, io_pins, 1) #define QSPI_IF_BUS_IO2_PIN DT_PROP_BY_IDX(QSPI_IF_BUS_NODE, io_pins, 2) #define QSPI_IF_BUS_IO3_PIN DT_PROP_BY_IDX(QSPI_IF_BUS_NODE, io_pins, 3) #define QSPI_IF_BUS_HAS_4_IO_PINS \ (DT_PROP_LEN(QSPI_IF_BUS_NODE, io_pins) == 4) #define QSPI_IF_BUS_PINCTRL_DT_DEV_CONFIG_GET \ PINCTRL_DT_DEV_CONFIG_GET(QSPI_IF_BUS_NODE) /* The NRF70 device node which is on the QSPI bus */ #define QSPI_IF_DEVICE_NODE DT_NODELABEL(nrf70) /* NRF70 device QSPI properties */ #define QSPI_IF_DEVICE_FREQUENCY DT_PROP(QSPI_IF_DEVICE_NODE, qspi_frequency) #define QSPI_IF_DEVICE_CPHA DT_PROP(QSPI_IF_DEVICE_NODE, qspi_cpha) #define QSPI_IF_DEVICE_CPOL DT_PROP(QSPI_IF_DEVICE_NODE, qspi_cpol) #define QSPI_IF_DEVICE_QUAD_MODE DT_PROP(QSPI_IF_DEVICE_NODE, qspi_quad_mode) #define QSPI_IF_DEVICE_RX_DELAY DT_PROP(QSPI_IF_DEVICE_NODE, qspi_rx_delay) static struct qspi_config *qspi_cfg; #if NRF_QSPI_HAS_XIP_ENC || NRF_QSPI_HAS_DMA_ENC static unsigned int nonce_last_addr; static unsigned int nonce_cnt; #endif /*NRF_QSPI_HAS_XIP_ENC || NRF_QSPI_HAS_DMA_ENC*/ /* Main config structure */ static nrfx_qspi_config_t QSPIconfig; /* * According to the respective specifications, the nRF52 QSPI supports clock * frequencies 2 - 32 MHz and the nRF53 one supports 6 - 96 MHz. */ BUILD_ASSERT(QSPI_IF_DEVICE_FREQUENCY >= (NRF_QSPI_BASE_CLOCK_FREQ / 16), "Unsupported SCK frequency."); /* * Determine a configuration value (INST_0_SCK_CFG) and, if needed, a divider * (BASE_CLOCK_DIV) for the clock from which the SCK frequency is derived that * need to be used to achieve the SCK frequency as close as possible (but not * higher) to the one specified in DT. */ #if defined(CONFIG_SOC_SERIES_NRF53X) /* * On nRF53 Series SoCs, the default /4 divider for the HFCLK192M clock can * only be used when the QSPI peripheral is idle. When a QSPI operation is * performed, the divider needs to be changed to /1 or /2 (particularly, * the specification says that the peripheral "supports 192 MHz and 96 MHz * PCLK192M frequency"), but after that operation is complete, the default * divider needs to be restored to avoid increased current consumption. */ /* To prevent anomaly 159, use only divider /1 for HFCLK192M. */ #define BASE_CLOCK_DIV NRF_CLOCK_HFCLK_DIV_1 #if (QSPI_IF_DEVICE_FREQUENCY >= (NRF_QSPI_BASE_CLOCK_FREQ / 4)) /* For requested SCK >= 24 MHz, use HFCLK192M / 1 / (2*4) = 24 MHz */ #define INST_0_SCK_CFG NRF_QSPI_FREQ_DIV4 #else /* For requested SCK < 24 MHz, calculate the configuration value. */ #define INST_0_SCK_CFG (DIV_ROUND_UP(NRF_QSPI_BASE_CLOCK_FREQ / 2, \ QSPI_IF_DEVICE_FREQUENCY) - 1) #endif /* For 8 MHz, use HFCLK192M / 2 / (2*6) */ #define INST_0_SCK_CFG_WAKE NRF_QSPI_FREQ_DIV6 #else /* * On nRF52 Series SoCs, the base clock divider is not configurable, * so BASE_CLOCK_DIV is not defined. */ #if (QSPI_IF_DEVICE_FREQUENCY >= NRF_QSPI_BASE_CLOCK_FREQ) #define INST_0_SCK_CFG NRF_QSPI_FREQ_DIV1 #else #define INST_0_SCK_CFG (DIV_ROUND_UP(NRF_QSPI_BASE_CLOCK_FREQ, \ QSPI_IF_DEVICE_FREQUENCY) - 1) #endif /* For 8 MHz, use PCLK32M / 4 */ #define INST_0_SCK_CFG_WAKE NRF_QSPI_FREQ_DIV4 #endif /* defined(CONFIG_SOC_SERIES_NRF53X) */ static int qspi_device_init(const struct device *dev); static void qspi_device_uninit(const struct device *dev); #define WORD_SIZE 4 LOG_MODULE_DECLARE(wifi_nrf_bus, CONFIG_WIFI_NRF70_BUS_LOG_LEVEL); /** * @brief QSPI buffer structure * Structure used both for TX and RX purposes. * * @param buf is a valid pointer to a data buffer. * Can not be NULL. * @param len is the length of the data to be handled. * If no data to transmit/receive - pass 0. */ struct qspi_buf { uint8_t *buf; size_t len; }; /** * @brief QSPI command structure * Structure used for custom command usage. * * @param op_code is a command value (i.e 0x9F - get Jedec ID) * @param tx_buf structure used for TX purposes. Can be NULL if not used. * @param rx_buf structure used for RX purposes. Can be NULL if not used. */ struct qspi_cmd { uint8_t op_code; const struct qspi_buf *tx_buf; const struct qspi_buf *rx_buf; }; /** * @brief Structure for defining the QSPI NOR access */ struct qspi_nor_data { #ifdef CONFIG_MULTITHREADING /* The semaphore to control exclusive access on write/erase. */ struct k_sem trans; /* The semaphore to control exclusive access to the device. */ struct k_sem sem; /* The semaphore to indicate that transfer has completed. */ struct k_sem sync; /* The semaphore to control driver init/uninit. */ struct k_sem count; #else /* CONFIG_MULTITHREADING */ /* A flag that signals completed transfer when threads are * not enabled. */ volatile bool ready; #endif /* CONFIG_MULTITHREADING */ }; static inline int qspi_get_mode(bool cpol, bool cpha) { register int ret = -EINVAL; if ((!cpol) && (!cpha)) ret = 0; else if (cpol && cpha) ret = 1; __ASSERT(ret != -EINVAL, "Invalid QSPI mode"); return ret; } static inline bool qspi_write_is_quad(nrf_qspi_writeoc_t lines) { switch (lines) { case NRF_QSPI_WRITEOC_PP4IO: case NRF_QSPI_WRITEOC_PP4O: return true; default: return false; } } static inline bool qspi_read_is_quad(nrf_qspi_readoc_t lines) { switch (lines) { case NRF_QSPI_READOC_READ4IO: case NRF_QSPI_READOC_READ4O: return true; default: return false; } } static inline int qspi_get_lines_write(uint8_t lines) { register int ret = -EINVAL; switch (lines) { case 3: ret = NRF_QSPI_WRITEOC_PP4IO; break; case 2: ret = NRF_QSPI_WRITEOC_PP4O; break; case 1: ret = NRF_QSPI_WRITEOC_PP2O; break; case 0: ret = NRF_QSPI_WRITEOC_PP; break; default: break; } __ASSERT(ret != -EINVAL, "Invalid QSPI write line"); return ret; } static inline int qspi_get_lines_read(uint8_t lines) { register int ret = -EINVAL; switch (lines) { case 4: ret = NRF_QSPI_READOC_READ4IO; break; case 3: ret = NRF_QSPI_READOC_READ4O; break; case 2: ret = NRF_QSPI_READOC_READ2IO; break; case 1: ret = NRF_QSPI_READOC_READ2O; break; case 0: ret = NRF_QSPI_READOC_FASTREAD; break; default: break; } __ASSERT(ret != -EINVAL, "Invalid QSPI read line"); return ret; } nrfx_err_t _nrfx_qspi_read(void *p_rx_buffer, size_t rx_buffer_length, uint32_t src_address) { return nrfx_qspi_read(p_rx_buffer, rx_buffer_length, src_address); } nrfx_err_t _nrfx_qspi_write(void const *p_tx_buffer, size_t tx_buffer_length, uint32_t dst_address) { return nrfx_qspi_write(p_tx_buffer, tx_buffer_length, dst_address); } nrfx_err_t _nrfx_qspi_init(nrfx_qspi_config_t const *p_config, nrfx_qspi_handler_t handler, void *p_context) { NRF_QSPI_Type *p_reg = NRF_QSPI; nrfx_qspi_init(p_config, handler, p_context); /* RDC4IO = 4'hA (register IFTIMING), which means 10 Dummy Cycles for READ4. */ p_reg->IFTIMING |= qspi_cfg->RDC4IO; /* LOG_DBG("%04x : IFTIMING", p_reg->IFTIMING & qspi_cfg->RDC4IO); */ /* ACTIVATE task fails for slave bitfile so ignore it */ return NRFX_SUCCESS; } /** * @brief Main configuration structure */ static struct qspi_nor_data qspi_nor_memory_data = { #ifdef CONFIG_MULTITHREADING .trans = Z_SEM_INITIALIZER(qspi_nor_memory_data.trans, 1, 1), .sem = Z_SEM_INITIALIZER(qspi_nor_memory_data.sem, 1, 1), .sync = Z_SEM_INITIALIZER(qspi_nor_memory_data.sync, 0, 1), .count = Z_SEM_INITIALIZER(qspi_nor_memory_data.count, 0, K_SEM_MAX_LIMIT), #endif /* CONFIG_MULTITHREADING */ }; NRF_DT_CHECK_NODE_HAS_PINCTRL_SLEEP(QSPI_IF_BUS_NODE); IF_ENABLED(CONFIG_PINCTRL, (PINCTRL_DT_DEFINE(QSPI_IF_BUS_NODE))); /** * @brief Converts NRFX return codes to the zephyr ones */ static inline int qspi_get_zephyr_ret_code(nrfx_err_t res) { switch (res) { case NRFX_SUCCESS: return 0; case NRFX_ERROR_INVALID_PARAM: case NRFX_ERROR_INVALID_ADDR: return -EINVAL; case NRFX_ERROR_INVALID_STATE: return -ECANCELED; #if NRF53_ERRATA_159_ENABLE_WORKAROUND case NRFX_ERROR_FORBIDDEN: LOG_ERR("nRF5340 anomaly 159 conditions detected"); LOG_ERR("Set the CPU clock to 64 MHz before starting QSPI operation"); return -ECANCELED; #endif case NRFX_ERROR_BUSY: case NRFX_ERROR_TIMEOUT: default: return -EBUSY; } } static inline struct qspi_nor_data *get_dev_data(const struct device *dev) { return dev->data; } static inline void qspi_lock(const struct device *dev) { #ifdef CONFIG_MULTITHREADING struct qspi_nor_data *dev_data = get_dev_data(dev); k_sem_take(&dev_data->sem, K_FOREVER); #else /* CONFIG_MULTITHREADING */ ARG_UNUSED(dev); #endif /* CONFIG_MULTITHREADING */ /* * Change the base clock divider only for the time the driver is locked * to perform a QSPI operation, otherwise the power consumption would be * increased also when the QSPI peripheral is idle. */ #if defined(CONFIG_SOC_SERIES_NRF53X) nrf_clock_hfclk192m_div_set(NRF_CLOCK, BASE_CLOCK_DIV); #endif } static inline void qspi_unlock(const struct device *dev) { #if defined(CONFIG_SOC_SERIES_NRF53X) /* Restore the default base clock divider to reduce power consumption. */ nrf_clock_hfclk192m_div_set(NRF_CLOCK, NRF_CLOCK_HFCLK_DIV_4); #endif #ifdef CONFIG_MULTITHREADING struct qspi_nor_data *dev_data = get_dev_data(dev); k_sem_give(&dev_data->sem); #else /* CONFIG_MULTITHREADING */ ARG_UNUSED(dev); #endif /* CONFIG_MULTITHREADING */ } static inline void qspi_trans_lock(const struct device *dev) { #ifdef CONFIG_MULTITHREADING struct qspi_nor_data *dev_data = get_dev_data(dev); k_sem_take(&dev_data->trans, K_FOREVER); #else /* CONFIG_MULTITHREADING */ ARG_UNUSED(dev); #endif /* CONFIG_MULTITHREADING */ } static inline void qspi_trans_unlock(const struct device *dev) { #ifdef CONFIG_MULTITHREADING struct qspi_nor_data *dev_data = get_dev_data(dev); k_sem_give(&dev_data->trans); #else /* CONFIG_MULTITHREADING */ ARG_UNUSED(dev); #endif /* CONFIG_MULTITHREADING */ } static inline void qspi_wait_for_completion(const struct device *dev, nrfx_err_t res) { struct qspi_nor_data *dev_data = get_dev_data(dev); if (res == NRFX_SUCCESS) { #ifdef CONFIG_MULTITHREADING k_sem_take(&dev_data->sync, K_FOREVER); #else /* CONFIG_MULTITHREADING */ unsigned int key = irq_lock(); while (!dev_data->ready) { k_cpu_atomic_idle(key); key = irq_lock(); } dev_data->ready = false; irq_unlock(key); #endif /* CONFIG_MULTITHREADING */ } } static inline void qspi_complete(struct qspi_nor_data *dev_data) { #ifdef CONFIG_MULTITHREADING k_sem_give(&dev_data->sync); #else /* CONFIG_MULTITHREADING */ dev_data->ready = true; #endif /* CONFIG_MULTITHREADING */ } static inline void _qspi_complete(struct qspi_nor_data *dev_data) { if (!qspi_cfg->easydma) return; qspi_complete(dev_data); } static inline void _qspi_wait_for_completion(const struct device *dev, nrfx_err_t res) { if (!qspi_cfg->easydma) return; qspi_wait_for_completion(dev, res); } /** * @brief QSPI handler * * @param event Driver event type * @param p_context Pointer to context. Use in interrupt handler. * @retval None */ static void qspi_handler(nrfx_qspi_evt_t event, void *p_context) { struct qspi_nor_data *dev_data = p_context; if (event == NRFX_QSPI_EVENT_DONE) _qspi_complete(dev_data); } static bool qspi_initialized; static int qspi_device_init(const struct device *dev) { struct qspi_nor_data *dev_data = get_dev_data(dev); nrfx_err_t res; int ret = 0; if (!IS_ENABLED(CONFIG_NRF70_QSPI_LOW_POWER)) { return 0; } qspi_lock(dev); /* In multithreading, driver can call qspi_device_init more than once * before calling qspi_device_uninit. Keepping count, so QSPI is * uninitialized only at the last call (count == 0). */ #ifdef CONFIG_MULTITHREADING k_sem_give(&dev_data->count); #endif if (!qspi_initialized) { res = nrfx_qspi_init(&QSPIconfig, qspi_handler, dev_data); ret = qspi_get_zephyr_ret_code(res); NRF_QSPI->IFTIMING |= qspi_cfg->RDC4IO; qspi_initialized = (ret == 0); } qspi_unlock(dev); return ret; } static void qspi_device_uninit(const struct device *dev) { bool last = true; if (!IS_ENABLED(CONFIG_NRF70_QSPI_LOW_POWER)) { return; } qspi_lock(dev); #ifdef CONFIG_MULTITHREADING struct qspi_nor_data *dev_data = get_dev_data(dev); /* The last thread to finish using the driver uninit the QSPI */ (void)k_sem_take(&dev_data->count, K_NO_WAIT); last = (k_sem_count_get(&dev_data->count) == 0); #endif if (last) { while (nrfx_qspi_mem_busy_check() != NRFX_SUCCESS) { if (IS_ENABLED(CONFIG_MULTITHREADING)) k_msleep(50); else k_busy_wait(50000); } nrfx_qspi_uninit(); #ifndef CONFIG_PINCTRL nrf_gpio_cfg_output(QSPI_PROP_AT(csn_pins, 0)); nrf_gpio_pin_set(QSPI_PROP_AT(csn_pins, 0)); #endif qspi_initialized = false; } qspi_unlock(dev); } /* QSPI send custom command. * * If this is used for both send and receive the buffer sizes must be * equal and cover the whole transaction. */ static int qspi_send_cmd(const struct device *dev, const struct qspi_cmd *cmd, bool wren) { /* Check input parameters */ if (!cmd) return -EINVAL; const void *tx_buf = NULL; size_t tx_len = 0; void *rx_buf = NULL; size_t rx_len = 0; size_t xfer_len = sizeof(cmd->op_code); if (cmd->tx_buf) { tx_buf = cmd->tx_buf->buf; tx_len = cmd->tx_buf->len; } if (cmd->rx_buf) { rx_buf = cmd->rx_buf->buf; rx_len = cmd->rx_buf->len; } if ((rx_len != 0) && (tx_len != 0)) { if (rx_len != tx_len) return -EINVAL; xfer_len += tx_len; } else /* At least one of these is zero. */ xfer_len += tx_len + rx_len; if (xfer_len > NRF_QSPI_CINSTR_LEN_9B) { LOG_WRN("cinstr %02x transfer too long: %zu", cmd->op_code, xfer_len); return -EINVAL; } nrf_qspi_cinstr_conf_t cinstr_cfg = { .opcode = cmd->op_code, .length = xfer_len, .io2_level = true, .io3_level = true, .wipwait = false, .wren = wren, }; qspi_lock(dev); int res = nrfx_qspi_cinstr_xfer(&cinstr_cfg, tx_buf, rx_buf); qspi_unlock(dev); return qspi_get_zephyr_ret_code(res); } /* RDSR wrapper. Negative value is error. */ static int qspi_rdsr(const struct device *dev) { uint8_t sr = -1; const struct qspi_buf sr_buf = { .buf = &sr, .len = sizeof(sr), }; struct qspi_cmd cmd = { .op_code = SPI_NOR_CMD_RDSR, .rx_buf = &sr_buf, }; int ret = qspi_send_cmd(dev, &cmd, false); return (ret < 0) ? ret : sr; } /* Wait until RDSR confirms write is not in progress. */ static int qspi_wait_while_writing(const struct device *dev) { int ret; do { ret = qspi_rdsr(dev); } while ((ret >= 0) && ((ret & SPI_NOR_WIP_BIT) != 0U)); return (ret < 0) ? ret : 0; } /** * @brief Fills init struct * * @param config Pointer to the config struct provided by user * @param initstruct Pointer to the configuration struct * @retval None */ static inline void qspi_fill_init_struct(nrfx_qspi_config_t *initstruct) { /* Configure XIP offset */ initstruct->xip_offset = 0; #ifdef CONFIG_PINCTRL initstruct->skip_gpio_cfg = true, initstruct->skip_psel_cfg = true, #else /* Configure pins */ initstruct->pins.sck_pin = QSPI_IF_BUS_SCK_PIN; initstruct->pins.csn_pin = QSPI_IF_BUS_CSN_PIN; initstruct->pins.io0_pin = QSPI_IF_BUS_IO0_PIN; initstruct->pins.io1_pin = QSPI_IF_BUS_IO1_PIN; #if QSPI_IF_BUS_HAS_4_IO_PINS initstruct->pins.io2_pin = QSPI_IF_BUS_IO2_PIN; initstruct->pins.io3_pin = QSPI_IF_BUS_IO3_PIN; #else initstruct->pins.io2_pin = NRF_QSPI_PIN_NOT_CONNECTED; initstruct->pins.io3_pin = NRF_QSPI_PIN_NOT_CONNECTED; #endif #endif /* CONFIG_PINCTRL */ /* Configure Protocol interface */ initstruct->prot_if.addrmode = NRF_QSPI_ADDRMODE_24BIT; initstruct->prot_if.dpmconfig = false; /* Configure physical interface */ initstruct->phy_if.sck_freq = INST_0_SCK_CFG; /* Using MHZ fails checkpatch constant check */ if (QSPI_IF_DEVICE_FREQUENCY >= 16000000) { qspi_cfg->qspi_slave_latency = 1; } initstruct->phy_if.sck_delay = QSPI_IF_DEVICE_RX_DELAY; initstruct->phy_if.spi_mode = qspi_get_mode(QSPI_IF_DEVICE_CPOL, QSPI_IF_DEVICE_CPHA); if (QSPI_IF_DEVICE_QUAD_MODE) { initstruct->prot_if.readoc = NRF_QSPI_READOC_READ4IO; initstruct->prot_if.writeoc = NRF_QSPI_WRITEOC_PP4IO; } else { initstruct->prot_if.readoc = NRF_QSPI_READOC_FASTREAD; initstruct->prot_if.writeoc = NRF_QSPI_WRITEOC_PP; } initstruct->phy_if.dpmen = false; } /* Configures QSPI memory for the transfer */ static int qspi_nrfx_configure(const struct device *dev) { if (!dev) return -ENXIO; struct qspi_nor_data *dev_data = dev->data; qspi_fill_init_struct(&QSPIconfig); #if defined(CONFIG_SOC_SERIES_NRF53X) /* When the QSPI peripheral is activated, during the nrfx_qspi driver * initialization, it reads the status of the connected flash chip. * Make sure this transaction is performed with a valid base clock * divider. */ nrf_clock_hfclk192m_div_set(NRF_CLOCK, BASE_CLOCK_DIV); #endif nrfx_err_t res = _nrfx_qspi_init(&QSPIconfig, qspi_handler, dev_data); #if defined(CONFIG_SOC_SERIES_NRF53X) /* Restore the default /4 divider after the QSPI initialization. */ nrf_clock_hfclk192m_div_set(NRF_CLOCK, NRF_CLOCK_HFCLK_DIV_4); #endif int ret = qspi_get_zephyr_ret_code(res); if (ret == 0) { /* Set QE to match transfer mode. If not using quad * it's OK to leave QE set, but doing so prevents use * of WP#/RESET#/HOLD# which might be useful. * * Note build assert above ensures QER is S1B6. Other * options require more logic. */ ret = qspi_rdsr(dev); if (ret < 0) { LOG_ERR("RDSR failed: %d", ret); return ret; } uint8_t sr = (uint8_t)ret; bool qe_value = (qspi_write_is_quad(QSPIconfig.prot_if.writeoc)) || (qspi_read_is_quad(QSPIconfig.prot_if.readoc)); const uint8_t qe_mask = BIT(6); /* only S1B6 */ bool qe_state = ((sr & qe_mask) != 0U); LOG_DBG("RDSR %02x QE %d need %d: %s", sr, qe_state, qe_value, (qe_state != qe_value) ? "updating" : "no-change"); ret = 0; if (qe_state != qe_value) { const struct qspi_buf sr_buf = { .buf = &sr, .len = sizeof(sr), }; struct qspi_cmd cmd = { .op_code = SPI_NOR_CMD_WRSR, .tx_buf = &sr_buf, }; sr ^= qe_mask; ret = qspi_send_cmd(dev, &cmd, true); /* Writing SR can take some time, and further * commands sent while it's happening can be * corrupted. Wait. */ if (ret == 0) ret = qspi_wait_while_writing(dev); } if (ret < 0) LOG_ERR("QE %s failed: %d", qe_value ? "set" : "clear", ret); } return ret; } static inline nrfx_err_t read_non_aligned(const struct device *dev, int addr, void *dest, size_t size) { uint8_t __aligned(WORD_SIZE) buf[WORD_SIZE * 2]; uint8_t *dptr = dest; int flash_prefix = (WORD_SIZE - (addr % WORD_SIZE)) % WORD_SIZE; if (flash_prefix > size) flash_prefix = size; int dest_prefix = (WORD_SIZE - (int)dptr % WORD_SIZE) % WORD_SIZE; if (dest_prefix > size) dest_prefix = size; int flash_suffix = (size - flash_prefix) % WORD_SIZE; int flash_middle = size - flash_prefix - flash_suffix; int dest_middle = size - dest_prefix - (size - dest_prefix) % WORD_SIZE; if (flash_middle > dest_middle) { flash_middle = dest_middle; flash_suffix = size - flash_prefix - flash_middle; } nrfx_err_t res = NRFX_SUCCESS; /* read from aligned flash to aligned memory */ if (flash_middle != 0) { res = _nrfx_qspi_read(dptr + dest_prefix, flash_middle, addr + flash_prefix); _qspi_wait_for_completion(dev, res); if (res != NRFX_SUCCESS) return res; /* perform shift in RAM */ if (flash_prefix != dest_prefix) memmove(dptr + flash_prefix, dptr + dest_prefix, flash_middle); } /* read prefix */ if (flash_prefix != 0) { res = _nrfx_qspi_read(buf, WORD_SIZE, addr - (WORD_SIZE - flash_prefix)); _qspi_wait_for_completion(dev, res); if (res != NRFX_SUCCESS) return res; memcpy(dptr, buf + WORD_SIZE - flash_prefix, flash_prefix); } /* read suffix */ if (flash_suffix != 0) { res = _nrfx_qspi_read(buf, WORD_SIZE * 2, addr + flash_prefix + flash_middle); _qspi_wait_for_completion(dev, res); if (res != NRFX_SUCCESS) return res; memcpy(dptr + flash_prefix + flash_middle, buf, flash_suffix); } return res; } static int qspi_nor_read(const struct device *dev, int addr, void *dest, size_t size) { if (!dest) return -EINVAL; /* read size must be non-zero */ if (!size) return 0; int rc = qspi_device_init(dev); if (rc != 0) goto out; qspi_lock(dev); nrfx_err_t res = read_non_aligned(dev, addr, dest, size); qspi_unlock(dev); rc = qspi_get_zephyr_ret_code(res); out: qspi_device_uninit(dev); return rc; } /* addr aligned, sptr not null, slen less than 4 */ static inline nrfx_err_t write_sub_word(const struct device *dev, int addr, const void *sptr, size_t slen) { uint8_t __aligned(4) buf[4]; nrfx_err_t res; /* read out the whole word so that unchanged data can be * written back */ res = _nrfx_qspi_read(buf, sizeof(buf), addr); _qspi_wait_for_completion(dev, res); if (res == NRFX_SUCCESS) { memcpy(buf, sptr, slen); res = _nrfx_qspi_write(buf, sizeof(buf), addr); _qspi_wait_for_completion(dev, res); } return res; } static int qspi_nor_write(const struct device *dev, int addr, const void *src, size_t size) { if (!src) return -EINVAL; /* write size must be non-zero, less than 4, or a multiple of 4 */ if ((size == 0) || ((size > 4) && ((size % 4U) != 0))) return -EINVAL; /* address must be 4-byte aligned */ if ((addr % 4U) != 0) return -EINVAL; nrfx_err_t res = NRFX_SUCCESS; int rc = qspi_device_init(dev); if (rc != 0) goto out; qspi_trans_lock(dev); qspi_lock(dev); if (size < 4U) res = write_sub_word(dev, addr, src, size); else { res = _nrfx_qspi_write(src, size, addr); _qspi_wait_for_completion(dev, res); } qspi_unlock(dev); qspi_trans_unlock(dev); rc = qspi_get_zephyr_ret_code(res); out: qspi_device_uninit(dev); return rc; } /** * @brief Configure the flash * * @param dev The flash device structure * @param info The flash info structure * @return 0 on success, negative errno code otherwise */ static int qspi_nor_configure(const struct device *dev) { int ret = qspi_nrfx_configure(dev); if (ret != 0) return ret; qspi_device_uninit(dev); return 0; } /** * @brief Initialize and configure the flash * * @param name The flash name * @return 0 on success, negative errno code otherwise */ static int qspi_nor_init(const struct device *dev) { #ifdef CONFIG_PINCTRL int ret = pinctrl_apply_state(QSPI_IF_BUS_PINCTRL_DT_DEV_CONFIG_GET, PINCTRL_STATE_DEFAULT); if (ret < 0) { return ret; } #endif IRQ_CONNECT(QSPI_IF_BUS_IRQN, QSPI_IF_BUS_IRQ_PRIO, nrfx_isr, nrfx_qspi_irq_handler, 0); return qspi_nor_configure(dev); } #if defined(CONFIG_SOC_SERIES_NRF53X) static int qspi_cmd_encryption(const struct device *dev, nrf_qspi_encryption_t *p_cfg) { const struct qspi_buf tx_buf = { .buf = (uint8_t *)&p_cfg->nonce[1], .len = sizeof(p_cfg->nonce[1]) }; const struct qspi_cmd cmd = { .op_code = 0x4f, .tx_buf = &tx_buf, }; int ret = qspi_device_init(dev); if (ret == 0) ret = qspi_send_cmd(dev, &cmd, false); qspi_device_uninit(dev); if (ret < 0) LOG_DBG("cmd_encryption failed %d", ret); return ret; } #endif int qspi_RDSR2(const struct device *dev, uint8_t *rdsr2) { int ret = 0; uint8_t sr = 0; const struct qspi_buf sr_buf = { .buf = &sr, .len = sizeof(sr), }; struct qspi_cmd cmd = { .op_code = 0x2f, .rx_buf = &sr_buf, }; ret = qspi_device_init(dev); ret = qspi_send_cmd(dev, &cmd, false); qspi_device_uninit(dev); LOG_DBG("RDSR2 = 0x%x", sr); if (ret == 0) *rdsr2 = sr; return ret; } /* Wait until RDSR2 confirms RPU_WAKE write is successful */ int qspi_validate_rpu_wake_writecmd(const struct device *dev) { int ret = 0; uint8_t rdsr2 = 0; for (int ii = 0; ii < 1; ii++) { ret = qspi_RDSR2(dev, &rdsr2); if (!ret && (rdsr2 & RPU_WAKEUP_NOW)) { return 0; } } return -1; } int qspi_RDSR1(const struct device *dev, uint8_t *rdsr1) { int ret = 0; uint8_t sr = 0; const struct qspi_buf sr_buf = { .buf = &sr, .len = sizeof(sr), }; struct qspi_cmd cmd = { .op_code = 0x1f, .rx_buf = &sr_buf, }; ret = qspi_device_init(dev); ret = qspi_send_cmd(dev, &cmd, false); qspi_device_uninit(dev); LOG_DBG("RDSR1 = 0x%x", sr); if (ret == 0) *rdsr1 = sr; return ret; } /* Wait until RDSR1 confirms RPU_AWAKE/RPU_READY */ int qspi_wait_while_rpu_awake(const struct device *dev) { int ret; uint8_t val = 0; for (int ii = 0; ii < 10; ii++) { ret = qspi_RDSR1(dev, &val); LOG_DBG("RDSR1 = 0x%x", val); if (!ret && (val & RPU_AWAKE_BIT)) { break; } k_msleep(1); } if (ret || !(val & RPU_AWAKE_BIT)) { LOG_ERR("RPU is not awake even after 10ms"); return -1; } /* Restore QSPI clock frequency from DTS */ QSPIconfig.phy_if.sck_freq = INST_0_SCK_CFG; return val; } int qspi_WRSR2(const struct device *dev, uint8_t data) { const struct qspi_buf tx_buf = { .buf = &data, .len = sizeof(data), }; const struct qspi_cmd cmd = { .op_code = 0x3f, .tx_buf = &tx_buf, }; int ret = qspi_device_init(dev); if (ret == 0) ret = qspi_send_cmd(dev, &cmd, false); qspi_device_uninit(dev); if (ret < 0) LOG_ERR("cmd_wakeup RPU failed %d", ret); return ret; } int qspi_cmd_wakeup_rpu(const struct device *dev, uint8_t data) { int ret; /* Waking RPU works reliably only with lowest frequency (8MHz) */ QSPIconfig.phy_if.sck_freq = INST_0_SCK_CFG_WAKE; ret = qspi_WRSR2(dev, data); return ret; } struct device qspi_perip = { .data = &qspi_nor_memory_data, }; int qspi_deinit(void) { LOG_DBG("TODO : %s", __func__); return 0; } int qspi_init(struct qspi_config *config) { unsigned int rc; qspi_cfg = config; config->readoc = config->quad_spi ? NRF_QSPI_READOC_READ4IO : NRF_QSPI_READOC_FASTREAD; config->writeoc = config->quad_spi ? NRF_QSPI_WRITEOC_PP4IO : NRF_QSPI_WRITEOC_PP; rc = qspi_nor_init(&qspi_perip); k_sem_init(&qspi_cfg->lock, 1, 1); return rc; } void qspi_update_nonce(unsigned int addr, int len, int hlread) { #if NRF_QSPI_HAS_XIP_ENC || NRF_QSPI_HAS_DMA_ENC NRF_QSPI_Type *p_reg = NRF_QSPI; if (!qspi_cfg->encryption) return; if (nonce_last_addr == 0 || hlread) p_reg->DMA_ENC.NONCE2 = ++nonce_cnt; else if ((nonce_last_addr + 4) != addr) p_reg->DMA_ENC.NONCE2 = ++nonce_cnt; nonce_last_addr = addr + len - 4; #endif /*NRF_QSPI_HAS_XIP_ENC || NRF_QSPI_HAS_DMA_ENC*/ } void qspi_addr_check(unsigned int addr, const void *data, unsigned int len) { if ((addr % 4 != 0) || (((unsigned int)data) % 4 != 0) || (len % 4 != 0)) { LOG_ERR("%s : Unaligned address %x %x %d %x %x", __func__, addr, (unsigned int)data, (addr % 4 != 0), (((unsigned int)data) % 4 != 0), (len % 4 != 0)); } } int qspi_write(unsigned int addr, const void *data, int len) { int status; qspi_addr_check(addr, data, len); addr |= qspi_cfg->addrmask; k_sem_take(&qspi_cfg->lock, K_FOREVER); qspi_update_nonce(addr, len, 0); status = qspi_nor_write(&qspi_perip, addr, data, len); k_sem_give(&qspi_cfg->lock); return status; } int qspi_read(unsigned int addr, void *data, int len) { int status; qspi_addr_check(addr, data, len); addr |= qspi_cfg->addrmask; k_sem_take(&qspi_cfg->lock, K_FOREVER); qspi_update_nonce(addr, len, 0); status = qspi_nor_read(&qspi_perip, addr, data, len); k_sem_give(&qspi_cfg->lock); return status; } int qspi_hl_readw(unsigned int addr, void *data) { int status; uint8_t *rxb = NULL; uint32_t len = 4; len = len + (4 * qspi_cfg->qspi_slave_latency); rxb = k_malloc(len); if (rxb == NULL) { LOG_ERR("%s: ERROR ENOMEM line %d", __func__, __LINE__); return -ENOMEM; } memset(rxb, 0, len); k_sem_take(&qspi_cfg->lock, K_FOREVER); qspi_update_nonce(addr, 4, 1); status = qspi_nor_read(&qspi_perip, addr, rxb, len); k_sem_give(&qspi_cfg->lock); *(uint32_t *)data = *(uint32_t *)(rxb + (len - 4)); k_free(rxb); return status; } int qspi_hl_read(unsigned int addr, void *data, int len) { int count = 0; qspi_addr_check(addr, data, len); while (count < (len / 4)) { qspi_hl_readw(addr + (4 * count), ((char *)data + (4 * count))); count++; } return 0; } int qspi_cmd_sleep_rpu(const struct device *dev) { uint8_t data = 0x0; /* printf("TODO : %s:", __func__); */ const struct qspi_buf tx_buf = { .buf = &data, .len = sizeof(data), }; const struct qspi_cmd cmd = { .op_code = 0x3f, /* 0x3f, //WRSR2(0x3F) WakeUP RPU. */ .tx_buf = &tx_buf, }; int ret = qspi_device_init(dev); if (ret == 0) { ret = qspi_send_cmd(dev, &cmd, false); } qspi_device_uninit(dev); if (ret < 0) { LOG_ERR("cmd_wakeup RPU failed: %d", ret); } return ret; } /* Encryption public API */ int qspi_enable_encryption(uint8_t *key) { #if defined(CONFIG_SOC_SERIES_NRF53X) int err = 0; if (qspi_cfg->encryption) return -EALREADY; int ret = qspi_device_init(&qspi_perip); if (ret != 0) { LOG_ERR("qspi_device_init failed: %d", ret); return -EIO; } memcpy(qspi_cfg->p_cfg.key, key, 16); err = nrfx_qspi_dma_encrypt(&qspi_cfg->p_cfg); if (err != NRFX_SUCCESS) { LOG_ERR("nrfx_qspi_dma_encrypt failed: %d", err); return -EIO; } err = qspi_cmd_encryption(&qspi_perip, &qspi_cfg->p_cfg); if (err != 0) { LOG_ERR("qspi_cmd_encryption failed: %d", err); return -EIO; } qspi_cfg->encryption = true; qspi_device_uninit(&qspi_perip); return 0; #else return -ENOTSUP; #endif } ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/qspi/src/qspi_if.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
9,166
```c /* * */ /** * @brief File containing QSPI device specific definitions for the * Zephyr OS layer of the Wi-Fi driver. */ #include <zephyr/kernel.h> #include <zephyr/sys/printk.h> #include <zephyr/drivers/gpio.h> #include <stdio.h> #include <string.h> #include "qspi_if.h" #include "spi_if.h" static struct qspi_config config; #if defined(CONFIG_NRF70_ON_QSPI) static struct qspi_dev qspi = { .init = qspi_init, .deinit = qspi_deinit, .read = qspi_read, .write = qspi_write, .hl_read = qspi_hl_read }; #else static struct qspi_dev spim = { .init = spim_init, .deinit = spim_deinit, .read = spim_read, .write = spim_write, .hl_read = spim_hl_read }; #endif struct qspi_config *qspi_defconfig(void) { memset(&config, 0, sizeof(struct qspi_config)); #if defined(CONFIG_NRF70_ON_QSPI) config.addrmode = NRF_QSPI_ADDRMODE_24BIT; config.RDC4IO = 0xA0; config.easydma = true; config.quad_spi = true; #endif config.addrmask = 0x800000; /* set bit23 (incr. addr mode) */ config.test_name = "QSPI TEST"; config.test_hlread = false; config.test_iteration = 0; config.qspi_slave_latency = 0; config.encryption = config.CMD_CNONCE = false; #if defined(CONFIG_NRF70_ON_QSPI) && (NRF_QSPI_HAS_XIP_ENC || NRF_QSPI_HAS_DMA_ENC) /*For #Bit 6 Enable below: i.e ALL Ones for QSPI Key*/ memset(&config.p_cfg.key, 0xff, sizeof(config.p_cfg.key)); config.p_cfg.nonce[0] = 0x16181648; config.p_cfg.nonce[1] = 0x0; config.p_cfg.nonce[2] = 0x1; #endif /*CONFIG_NRF70_ON_QSPI && (NRF_QSPI_HAS_XIP_ENC || NRF_QSPI_HAS_DMA_ENC)*/ return &config; } struct qspi_config *qspi_get_config(void) { return &config; } struct qspi_dev *qspi_dev(void) { #if CONFIG_NRF70_ON_QSPI return &qspi; #else return &spim; #endif } ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/qspi/src/device.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
535
```c /* * */ /** * @brief File containing WPA supplicant interface specific definitions for the * Zephyr OS layer of the Wi-Fi driver. */ #include <stdlib.h> #include <zephyr/device.h> #include <zephyr/logging/log.h> #include "fmac_main.h" #include "fmac_util.h" #include "wifi_mgmt.h" #include "wpa_supp_if.h" LOG_MODULE_DECLARE(wifi_nrf, CONFIG_WIFI_NRF70_LOG_LEVEL); K_SEM_DEFINE(wait_for_event_sem, 0, 1); K_SEM_DEFINE(wait_for_scan_resp_sem, 0, 1); static K_MUTEX_DEFINE(mgmt_tx_lock); #define ACTION_FRAME_RESP_TIMEOUT_MS 5000 #define SET_IFACE_EVENT_TIMEOUT_MS 5000 #define CARR_ON_TIMEOUT_MS 5000 static int get_nrf_wifi_auth_type(int wpa_auth_alg) { if (wpa_auth_alg & WPA_AUTH_ALG_OPEN) { return NRF_WIFI_AUTHTYPE_OPEN_SYSTEM; } if (wpa_auth_alg & WPA_AUTH_ALG_SHARED) { return NRF_WIFI_AUTHTYPE_SHARED_KEY; } if (wpa_auth_alg & WPA_AUTH_ALG_LEAP) { return NRF_WIFI_AUTHTYPE_NETWORK_EAP; } if (wpa_auth_alg & WPA_AUTH_ALG_FT) { return NRF_WIFI_AUTHTYPE_FT; } if (wpa_auth_alg & WPA_AUTH_ALG_SAE) { return NRF_WIFI_AUTHTYPE_SAE; } return NRF_WIFI_AUTHTYPE_MAX; } static unsigned int wpa_alg_to_cipher_suite(enum wpa_alg alg, size_t key_len) { switch (alg) { case WPA_ALG_WEP: if (key_len == 5) { return RSN_CIPHER_SUITE_WEP40; } return RSN_CIPHER_SUITE_WEP104; case WPA_ALG_TKIP: return RSN_CIPHER_SUITE_TKIP; case WPA_ALG_CCMP: return RSN_CIPHER_SUITE_CCMP; case WPA_ALG_GCMP: return RSN_CIPHER_SUITE_GCMP; case WPA_ALG_CCMP_256: return RSN_CIPHER_SUITE_CCMP_256; case WPA_ALG_GCMP_256: return RSN_CIPHER_SUITE_GCMP_256; case WPA_ALG_BIP_CMAC_128: return RSN_CIPHER_SUITE_AES_128_CMAC; case WPA_ALG_BIP_GMAC_128: return RSN_CIPHER_SUITE_BIP_GMAC_128; case WPA_ALG_BIP_GMAC_256: return RSN_CIPHER_SUITE_BIP_GMAC_256; case WPA_ALG_BIP_CMAC_256: return RSN_CIPHER_SUITE_BIP_CMAC_256; case WPA_ALG_SMS4: return RSN_CIPHER_SUITE_SMS4; case WPA_ALG_KRK: return RSN_CIPHER_SUITE_KRK; case WPA_ALG_NONE: LOG_ERR("%s: Unexpected encryption algorithm %d", __func__, alg); return 0; } LOG_ERR("%s: Unsupported encryption algorithm %d", __func__, alg); return 0; } static enum chan_width drv2supp_chan_width(int width) { switch (width) { case NRF_WIFI_CHAN_WIDTH_20_NOHT: return CHAN_WIDTH_20_NOHT; case NRF_WIFI_CHAN_WIDTH_20: return CHAN_WIDTH_20; case NRF_WIFI_CHAN_WIDTH_40: return CHAN_WIDTH_40; case NRF_WIFI_CHAN_WIDTH_80: return CHAN_WIDTH_80; case NRF_WIFI_CHAN_WIDTH_80P80: return CHAN_WIDTH_80P80; case NRF_WIFI_CHAN_WIDTH_160: return CHAN_WIDTH_160; default: break; } return CHAN_WIDTH_UNKNOWN; } void nrf_wifi_wpa_supp_event_proc_scan_start(void *if_priv) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; vif_ctx_zep = if_priv; if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.scan_start) { vif_ctx_zep->supp_callbk_fns.scan_start(vif_ctx_zep->supp_drv_if_ctx); } } void nrf_wifi_wpa_supp_event_proc_scan_done(void *if_priv, struct nrf_wifi_umac_event_trigger_scan *scan_done_event, unsigned int event_len, int aborted) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; union wpa_event_data event; struct scan_info *info = NULL; vif_ctx_zep = if_priv; memset(&event, 0, sizeof(event)); info = &event.scan_info; info->aborted = aborted; info->external_scan = 0; info->nl_scan_event = 1; if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.scan_done) { vif_ctx_zep->supp_callbk_fns.scan_done(vif_ctx_zep->supp_drv_if_ctx, &event); } k_work_cancel_delayable(&vif_ctx_zep->scan_timeout_work); vif_ctx_zep->scan_in_progress = false; k_sem_give(&wait_for_scan_resp_sem); } void nrf_wifi_wpa_supp_event_proc_scan_res(void *if_priv, struct nrf_wifi_umac_event_new_scan_results *scan_res, unsigned int event_len, bool more_res) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct wpa_scan_res *r = NULL; const unsigned char *ie = NULL; const unsigned char *beacon_ie = NULL; unsigned int ie_len = 0; unsigned int beacon_ie_len = 0; unsigned char *pos = NULL; vif_ctx_zep = if_priv; if (scan_res->valid_fields & NRF_WIFI_EVENT_NEW_SCAN_RESULTS_IES_VALID) { ie = scan_res->ies; ie_len = scan_res->ies_len; } if (scan_res->valid_fields & NRF_WIFI_EVENT_NEW_SCAN_RESULTS_BEACON_IES_VALID) { beacon_ie = scan_res->ies + scan_res->ies_len; beacon_ie_len = scan_res->beacon_ies_len; } r = k_calloc(sizeof(*r) + ie_len + beacon_ie_len, sizeof(char)); if (!r) { LOG_ERR("%s: Unable to allocate memory for scan result", __func__); return; } if (scan_res->valid_fields & NRF_WIFI_EVENT_NEW_SCAN_RESULTS_MAC_ADDR_VALID) { memcpy(r->bssid, scan_res->mac_addr, ETH_ALEN); } r->freq = scan_res->frequency; if (scan_res->valid_fields & NRF_WIFI_EVENT_NEW_SCAN_RESULTS_BEACON_INTERVAL_VALID) { r->beacon_int = scan_res->beacon_interval; } r->caps = scan_res->capability; r->flags |= WPA_SCAN_NOISE_INVALID; if (scan_res->signal.signal_type == NRF_WIFI_SIGNAL_TYPE_MBM) { r->level = scan_res->signal.signal.mbm_signal; r->level /= 100; /* mBm to dBm */ r->flags |= (WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID); } else if (scan_res->signal.signal_type == NRF_WIFI_SIGNAL_TYPE_UNSPEC) { r->level = scan_res->signal.signal.unspec_signal; r->flags |= WPA_SCAN_QUAL_INVALID; } else { r->flags |= (WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID); } if (scan_res->valid_fields & NRF_WIFI_EVENT_NEW_SCAN_RESULTS_IES_TSF_VALID) { r->tsf = scan_res->ies_tsf; } if (scan_res->valid_fields & NRF_WIFI_EVENT_NEW_SCAN_RESULTS_BEACON_IES_TSF_VALID) { if (scan_res->beacon_ies_tsf > r->tsf) { r->tsf = scan_res->beacon_ies_tsf; } } if (scan_res->seen_ms_ago) { r->age = scan_res->seen_ms_ago; } r->ie_len = ie_len; pos = (unsigned char *)(r + 1); if (ie) { memcpy(pos, ie, ie_len); pos += ie_len; } r->beacon_ie_len = beacon_ie_len; if (beacon_ie) { memcpy(pos, beacon_ie, beacon_ie_len); } if (scan_res->valid_fields & NRF_WIFI_EVENT_NEW_SCAN_RESULTS_STATUS_VALID) { switch (scan_res->status) { case NRF_WIFI_BSS_STATUS_ASSOCIATED: r->flags |= WPA_SCAN_ASSOCIATED; break; default: break; } } if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.scan_res) { vif_ctx_zep->supp_callbk_fns.scan_res(vif_ctx_zep->supp_drv_if_ctx, r, more_res); } if (!more_res) { vif_ctx_zep->scan_in_progress = false; } k_free(r); } void nrf_wifi_wpa_supp_event_proc_auth_resp(void *if_priv, struct nrf_wifi_umac_event_mlme *auth_resp, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; union wpa_event_data event; const struct ieee80211_mgmt *mgmt = NULL; const unsigned char *frame = NULL; unsigned int frame_len = 0; vif_ctx_zep = if_priv; frame = auth_resp->frame.frame; frame_len = auth_resp->frame.frame_len; mgmt = (const struct ieee80211_mgmt *)frame; if (frame_len < 4 + (2 * NRF_WIFI_ETH_ADDR_LEN)) { LOG_ERR("%s: MLME event too short", __func__); return; } if (frame_len < 24 + sizeof(mgmt->u.auth)) { LOG_ERR("%s: Authentication response frame too short", __func__); return; } memset(&event, 0, sizeof(event)); memcpy(event.auth.peer, mgmt->sa, ETH_ALEN); event.auth.auth_type = le_to_host16(mgmt->u.auth.auth_alg); event.auth.auth_transaction = le_to_host16(mgmt->u.auth.auth_transaction); event.auth.status_code = le_to_host16(mgmt->u.auth.status_code); if (frame_len > 24 + sizeof(mgmt->u.auth)) { event.auth.ies = mgmt->u.auth.variable; event.auth.ies_len = (frame_len - 24 - sizeof(mgmt->u.auth)); } if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.auth_resp) { vif_ctx_zep->supp_callbk_fns.auth_resp(vif_ctx_zep->supp_drv_if_ctx, &event); } } void nrf_wifi_wpa_supp_event_proc_assoc_resp(void *if_priv, struct nrf_wifi_umac_event_mlme *assoc_resp, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; union wpa_event_data event; const struct ieee80211_mgmt *mgmt = NULL; const unsigned char *frame = NULL; unsigned int frame_len = 0; unsigned short status = WLAN_STATUS_UNSPECIFIED_FAILURE; vif_ctx_zep = if_priv; frame = assoc_resp->frame.frame; frame_len = assoc_resp->frame.frame_len; mgmt = (const struct ieee80211_mgmt *)frame; if (frame_len < 24 + sizeof(mgmt->u.assoc_resp)) { LOG_ERR("%s: Association response frame too short", __func__); return; } memset(&event, 0, sizeof(event)); status = le_to_host16(mgmt->u.assoc_resp.status_code); if (status != WLAN_STATUS_SUCCESS) { event.assoc_reject.bssid = mgmt->bssid; if (frame_len > 24 + sizeof(mgmt->u.assoc_resp)) { event.assoc_reject.resp_ies = (unsigned char *)mgmt->u.assoc_resp.variable; event.assoc_reject.resp_ies_len = (frame_len - 24 - sizeof(mgmt->u.assoc_resp)); } event.assoc_reject.status_code = status; } else { event.assoc_info.addr = mgmt->bssid; event.assoc_info.resp_frame = frame; event.assoc_info.resp_frame_len = frame_len; event.assoc_info.freq = vif_ctx_zep->assoc_freq; if (frame_len > 24 + sizeof(mgmt->u.assoc_resp)) { event.assoc_info.resp_ies = (unsigned char *)mgmt->u.assoc_resp.variable; event.assoc_info.resp_ies_len = (frame_len - 24 - sizeof(mgmt->u.assoc_resp)); } if (assoc_resp->req_ie_len > 0) { event.assoc_info.req_ies = (unsigned char *)assoc_resp->req_ie; event.assoc_info.req_ies_len = assoc_resp->req_ie_len; } } if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.assoc_resp) { vif_ctx_zep->supp_callbk_fns.assoc_resp(vif_ctx_zep->supp_drv_if_ctx, &event, status); } } void nrf_wifi_wpa_supp_event_proc_deauth(void *if_priv, struct nrf_wifi_umac_event_mlme *deauth, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; union wpa_event_data event; const struct ieee80211_mgmt *mgmt = NULL; const unsigned char *frame = NULL; unsigned int frame_len = 0; vif_ctx_zep = if_priv; frame = deauth->frame.frame; frame_len = deauth->frame.frame_len; mgmt = (const struct ieee80211_mgmt *)frame; if (frame_len < 24 + sizeof(mgmt->u.deauth)) { LOG_ERR("%s: Deauthentication frame too short", __func__); return; } memset(&event, 0, sizeof(event)); event.deauth_info.addr = &mgmt->sa[0]; event.deauth_info.reason_code = le_to_host16(mgmt->u.deauth.reason_code); if (frame + frame_len > mgmt->u.deauth.variable) { event.deauth_info.ie = mgmt->u.deauth.variable; event.deauth_info.ie_len = (frame + frame_len - mgmt->u.deauth.variable); } if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.deauth) { vif_ctx_zep->supp_callbk_fns.deauth(vif_ctx_zep->supp_drv_if_ctx, &event, mgmt); } } void nrf_wifi_wpa_supp_event_proc_disassoc(void *if_priv, struct nrf_wifi_umac_event_mlme *disassoc, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; union wpa_event_data event; const struct ieee80211_mgmt *mgmt = NULL; const unsigned char *frame = NULL; unsigned int frame_len = 0; vif_ctx_zep = if_priv; frame = disassoc->frame.frame; frame_len = disassoc->frame.frame_len; mgmt = (const struct ieee80211_mgmt *)frame; if (frame_len < 24 + sizeof(mgmt->u.disassoc)) { LOG_ERR("%s: Disassociation frame too short", __func__); return; } memset(&event, 0, sizeof(event)); event.disassoc_info.addr = &mgmt->sa[0]; event.disassoc_info.reason_code = le_to_host16(mgmt->u.disassoc.reason_code); if (frame + frame_len > mgmt->u.disassoc.variable) { event.disassoc_info.ie = mgmt->u.disassoc.variable; event.disassoc_info.ie_len = (frame + frame_len - mgmt->u.disassoc.variable); } if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.disassoc) { vif_ctx_zep->supp_callbk_fns.disassoc(vif_ctx_zep->supp_drv_if_ctx, &event); } (void) nrf_wifi_twt_teardown_flows(vif_ctx_zep, 0, NRF_WIFI_MAX_TWT_FLOWS); } void *nrf_wifi_wpa_supp_dev_init(void *supp_drv_if_ctx, const char *iface_name, struct zep_wpa_supp_dev_callbk_fns *supp_callbk_fns) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; const struct device *device = DEVICE_DT_GET(DT_CHOSEN(zephyr_wifi)); if (!device) { LOG_ERR("%s: Interface %s not found", __func__, iface_name); return NULL; } vif_ctx_zep = device->data; if (!vif_ctx_zep || !vif_ctx_zep->rpu_ctx_zep) { LOG_ERR("%s: Interface %s not properly initialized", __func__, iface_name); return NULL; } /* Needed to make sure that during initialization, commands like setting regdomain * does not access it. */ k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); vif_ctx_zep->supp_drv_if_ctx = supp_drv_if_ctx; memcpy(&vif_ctx_zep->supp_callbk_fns, supp_callbk_fns, sizeof(vif_ctx_zep->supp_callbk_fns)); k_mutex_unlock(&vif_ctx_zep->vif_lock); return vif_ctx_zep; } void nrf_wifi_wpa_supp_dev_deinit(void *if_priv) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; vif_ctx_zep = if_priv; vif_ctx_zep->supp_drv_if_ctx = NULL; } int nrf_wifi_wpa_supp_scan2(void *if_priv, struct wpa_driver_scan_params *params) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_umac_scan_info *scan_info = NULL; int indx = 0; int ret = -1; int num_freqs = 0; if (!if_priv || !params) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep->rpu_ctx) { LOG_ERR("%s: RPU context not initialized", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } if (vif_ctx_zep->scan_in_progress) { LOG_ERR("%s: Scan already in progress", __func__); ret = -EBUSY; goto out; } if (params->freqs) { for (indx = 0; params->freqs[indx]; indx++) num_freqs++; } scan_info = k_calloc(sizeof(*scan_info) + (num_freqs * sizeof(unsigned int)), sizeof(char)); if (!scan_info) { LOG_ERR("%s: Unable to allocate memory for scan info", __func__); ret = -ENOMEM; goto out; } memset(scan_info, 0x0, sizeof(*scan_info)); if (params->freqs) { for (indx = 0; params->freqs[indx]; indx++) { scan_info->scan_params.center_frequency[indx] = params->freqs[indx]; } scan_info->scan_params.num_scan_channels = indx; } if (params->filter_ssids) { scan_info->scan_params.num_scan_ssids = params->num_filter_ssids; for (indx = 0; indx < params->num_filter_ssids; indx++) { memcpy(scan_info->scan_params.scan_ssids[indx].nrf_wifi_ssid, params->filter_ssids[indx].ssid, params->filter_ssids[indx].ssid_len); scan_info->scan_params.scan_ssids[indx].nrf_wifi_ssid_len = params->filter_ssids[indx].ssid_len; } } scan_info->scan_reason = SCAN_CONNECT; /* Copy extra_ies */ if (params->extra_ies_len && params->extra_ies_len <= NRF_WIFI_MAX_IE_LEN) { memcpy(scan_info->scan_params.ie.ie, params->extra_ies, params->extra_ies_len); scan_info->scan_params.ie.ie_len = params->extra_ies_len; } else if (params->extra_ies_len) { LOG_ERR("%s: extra_ies_len %d is greater than max IE len %d", __func__, params->extra_ies_len, NRF_WIFI_MAX_IE_LEN); goto out; } status = nrf_wifi_fmac_scan(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, scan_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Scan trigger failed", __func__); goto out; } vif_ctx_zep->scan_type = SCAN_CONNECT; vif_ctx_zep->scan_in_progress = true; k_work_schedule(&vif_ctx_zep->scan_timeout_work, K_SECONDS(CONFIG_WIFI_NRF70_SCAN_TIMEOUT_S)); ret = 0; out: if (scan_info) k_free(scan_info); k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_scan_abort(void *if_priv) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int sem_ret; vif_ctx_zep = if_priv; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); return -1; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return -1; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } if (!vif_ctx_zep->scan_in_progress) { LOG_ERR("%s:Ignore scan abort, no scan in progress", __func__); goto out; } status = nrf_wifi_fmac_abort_scan(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_abort_scan failed", __func__); goto out; } k_sem_reset(&wait_for_scan_resp_sem); sem_ret = k_sem_take(&wait_for_scan_resp_sem, K_MSEC(RPU_RESP_EVENT_TIMEOUT)); if (sem_ret) { LOG_ERR("%s: Timedout waiting for scan abort response, ret = %d", __func__, sem_ret); status = NRF_WIFI_STATUS_FAIL; goto out; } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return status; } int nrf_wifi_wpa_supp_scan_results_get(void *if_priv) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; int ret = -1; if (!if_priv) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } status = nrf_wifi_fmac_scan_res_get(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, SCAN_CONNECT); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_scan_res_get failed", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_deauthenticate(void *if_priv, const char *addr, unsigned short reason_code) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_umac_disconn_info deauth_info; int ret = -1; if ((!if_priv) || (!addr)) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } memset(&deauth_info, 0, sizeof(deauth_info)); deauth_info.reason_code = reason_code; memcpy(deauth_info.mac_addr, addr, sizeof(deauth_info.mac_addr)); status = nrf_wifi_fmac_deauth(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &deauth_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_deauth failed", __func__); goto out; } ret = nrf_wifi_twt_teardown_flows(vif_ctx_zep, 0, NRF_WIFI_MAX_TWT_FLOWS); out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_add_key(struct nrf_wifi_umac_key_info *key_info, enum wpa_alg alg, int key_idx, int defkey, const unsigned char *seq, size_t seq_len, const unsigned char *key, size_t key_len) { unsigned int suite = 0; suite = wpa_alg_to_cipher_suite(alg, key_len); if (!suite) { return -1; } if (defkey && alg == WPA_ALG_BIP_CMAC_128) { key_info->nrf_wifi_flags = NRF_WIFI_KEY_DEFAULT_MGMT; } else if (defkey) { key_info->nrf_wifi_flags = NRF_WIFI_KEY_DEFAULT; } key_info->key_idx = key_idx; key_info->cipher_suite = suite; if (key && key_len) { memcpy(key_info->key.nrf_wifi_key, key, key_len); key_info->key.nrf_wifi_key_len = key_len; } if (seq && seq_len) { memcpy(key_info->seq.nrf_wifi_seq, seq, seq_len); key_info->seq.nrf_wifi_seq_len = seq_len; } return 0; } int nrf_wifi_wpa_supp_authenticate(void *if_priv, struct wpa_driver_auth_params *params, struct wpa_bss *curr_bss) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_umac_auth_info auth_info; int ret = -1; int type; int count = 0; int max_ie_len = 0; if ((!if_priv) || (!params)) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } #ifdef CONFIG_NRF70_RAW_DATA_RX if (vif_ctx_zep->if_type == NRF_WIFI_IFTYPE_MONITOR) { LOG_ERR("%s: Interface is in Monitor mode - cannot connect to a BSS", __func__); goto out; } #endif /* CONFIG_NRF70_RAW_DATA_RX */ memset(&auth_info, 0, sizeof(auth_info)); if (params->bssid) { memcpy(auth_info.nrf_wifi_bssid, params->bssid, ETH_ALEN); } if (params->freq) { auth_info.frequency = params->freq; } if (params->ssid) { memcpy(auth_info.ssid.nrf_wifi_ssid, params->ssid, params->ssid_len); auth_info.ssid.nrf_wifi_ssid_len = params->ssid_len; } if (params->ie) { max_ie_len = (params->ie_len > NRF_WIFI_MAX_IE_LEN) ? NRF_WIFI_MAX_IE_LEN : params->ie_len; memcpy(&auth_info.ie.ie, params->ie, max_ie_len); auth_info.ie.ie_len = max_ie_len; } else { auth_info.scan_width = 0; /* hard coded */ auth_info.nrf_wifi_signal = curr_bss->level; auth_info.capability = curr_bss->caps; auth_info.beacon_interval = curr_bss->beacon_int; auth_info.tsf = curr_bss->tsf; auth_info.from_beacon = 0; /* hard coded */ } if (params->auth_data) { auth_info.sae.sae_data_len = params->auth_data_len; memcpy(auth_info.sae.sae_data, params->auth_data, params->auth_data_len); } type = get_nrf_wifi_auth_type(params->auth_alg); if (type != NRF_WIFI_AUTHTYPE_MAX) { auth_info.auth_type = type; } if (type == NRF_WIFI_AUTHTYPE_SHARED_KEY) { size_t key_len = params->wep_key_len[params->wep_tx_keyidx]; struct nrf_wifi_umac_key_info *key_info = &auth_info.key_info; key_info->cipher_suite = wpa_alg_to_cipher_suite(params->auth_alg, key_len); memcpy(key_info->key.nrf_wifi_key, params->wep_key[params->wep_tx_keyidx], key_len); key_info->key.nrf_wifi_key_len = key_len; key_info->valid_fields |= NRF_WIFI_KEY_VALID | NRF_WIFI_KEY_IDX_VALID | NRF_WIFI_CIPHER_SUITE_VALID; } if (params->local_state_change) { auth_info.nrf_wifi_flags |= NRF_WIFI_CMD_AUTHENTICATE_LOCAL_STATE_CHANGE; } status = nrf_wifi_fmac_auth(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &auth_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: MLME command failed (auth): count=%d ret=%d", __func__, count, ret); count++; ret = -1; } else { LOG_DBG("%s:Authentication request sent successfully", __func__); ret = 0; } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_associate(void *if_priv, struct wpa_driver_associate_params *params) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_umac_assoc_info assoc_info; int ret = -1; if ((!if_priv) || (!params)) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } memset(&assoc_info, 0, sizeof(assoc_info)); if (params->bssid) { memcpy(assoc_info.nrf_wifi_bssid, params->bssid, sizeof(assoc_info.nrf_wifi_bssid)); } if (params->freq.freq) { assoc_info.center_frequency = params->freq.freq; vif_ctx_zep->assoc_freq = params->freq.freq; } else { vif_ctx_zep->assoc_freq = 0; } if (params->prev_bssid) { assoc_info.prev_bssid_flag = 1; memcpy(assoc_info.prev_bssid, params->prev_bssid, ETH_ALEN); } if (params->ssid) { assoc_info.ssid.nrf_wifi_ssid_len = params->ssid_len; memcpy(assoc_info.ssid.nrf_wifi_ssid, params->ssid, params->ssid_len); } if (params->wpa_ie) { assoc_info.wpa_ie.ie_len = params->wpa_ie_len; memcpy(assoc_info.wpa_ie.ie, params->wpa_ie, params->wpa_ie_len); } assoc_info.control_port = 1; if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED) { assoc_info.use_mfp = NRF_WIFI_MFP_REQUIRED; } if (params->bss_max_idle_period) { assoc_info.bss_max_idle_time = params->bss_max_idle_period; } status = nrf_wifi_fmac_assoc(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &assoc_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: MLME command failed (assoc)", __func__); } else { LOG_DBG("%s: Association request sent successfully", __func__); ret = 0; } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_set_key(void *if_priv, const unsigned char *ifname, enum wpa_alg alg, const unsigned char *addr, int key_idx, int set_tx, const unsigned char *seq, size_t seq_len, const unsigned char *key, size_t key_len, enum key_flag key_flag) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_umac_key_info key_info; const unsigned char *mac_addr = NULL; unsigned int suite; int ret = -1; if ((!if_priv) || (!ifname)) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep->rpu_ctx) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } /* Can happen in a positive case where "net if down" is completed, but WPA * supplicant is still deleting keys. */ if (!rpu_ctx_zep->rpu_ctx) { goto out; } memset(&key_info, 0, sizeof(key_info)); if (alg != WPA_ALG_NONE) { suite = wpa_alg_to_cipher_suite(alg, key_len); if (!suite) { goto out; } memcpy(key_info.key.nrf_wifi_key, key, key_len); key_info.key.nrf_wifi_key_len = key_len; key_info.cipher_suite = suite; key_info.valid_fields |= (NRF_WIFI_CIPHER_SUITE_VALID | NRF_WIFI_KEY_VALID); } if (seq && seq_len) { memcpy(key_info.seq.nrf_wifi_seq, seq, seq_len); key_info.seq.nrf_wifi_seq_len = seq_len; key_info.valid_fields |= NRF_WIFI_SEQ_VALID; } /* TODO: Implement/check set_tx */ if (addr && !is_broadcast_ether_addr(addr)) { mac_addr = addr; key_info.key_type = NRF_WIFI_KEYTYPE_PAIRWISE; key_info.valid_fields |= NRF_WIFI_KEY_TYPE_VALID; } else if (addr && is_broadcast_ether_addr(addr)) { mac_addr = NULL; key_info.key_type = NRF_WIFI_KEYTYPE_GROUP; key_info.valid_fields |= NRF_WIFI_KEY_TYPE_VALID; key_info.nrf_wifi_flags |= NRF_WIFI_KEY_DEFAULT_TYPE_MULTICAST; } key_info.key_idx = key_idx; key_info.valid_fields |= NRF_WIFI_KEY_IDX_VALID; if (alg == WPA_ALG_NONE) { status = nrf_wifi_fmac_del_key(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &key_info, mac_addr); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_del_key failed", __func__); } else { ret = 0; } } else { status = nrf_wifi_fmac_add_key(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &key_info, mac_addr); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_add_key failed", __func__); } else { ret = 0; } } /* * If we failed or don't need to set the default TX key (below), * we're done here. */ if (ret || !set_tx || alg == WPA_ALG_NONE) { goto out; } memset(&key_info, 0, sizeof(key_info)); key_info.key_idx = key_idx; key_info.valid_fields |= NRF_WIFI_KEY_IDX_VALID; if (alg == WPA_ALG_BIP_CMAC_128 || alg == WPA_ALG_BIP_GMAC_128 || alg == WPA_ALG_BIP_GMAC_256 || alg == WPA_ALG_BIP_CMAC_256) { key_info.nrf_wifi_flags = NRF_WIFI_KEY_DEFAULT_MGMT; } else { key_info.nrf_wifi_flags = NRF_WIFI_KEY_DEFAULT; } if (addr && is_broadcast_ether_addr(addr)) { key_info.nrf_wifi_flags |= NRF_WIFI_KEY_DEFAULT_TYPE_MULTICAST; } else if (addr) { key_info.nrf_wifi_flags |= NRF_WIFI_KEY_DEFAULT_TYPE_UNICAST; } status = nrf_wifi_fmac_set_key(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &key_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_set_key failed", __func__); ret = -1; } else { ret = 0; } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_set_supp_port(void *if_priv, int authorized, char *bssid) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_umac_chg_sta_info chg_sta_info; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int ret = -1; if (!if_priv || !bssid) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } if (vif_ctx_zep->if_op_state != NRF_WIFI_FMAC_IF_OP_STATE_UP) { LOG_DBG("%s: Interface not UP, ignoring", __func__); ret = 0; goto out; } memset(&chg_sta_info, 0x0, sizeof(chg_sta_info)); memcpy(chg_sta_info.mac_addr, bssid, ETH_ALEN); vif_ctx_zep->authorized = authorized; if (authorized) { /* BIT(NL80211_STA_FLAG_AUTHORIZED) */ chg_sta_info.sta_flags2.nrf_wifi_mask = 1 << 1; /* BIT(NL80211_STA_FLAG_AUTHORIZED) */ chg_sta_info.sta_flags2.nrf_wifi_set = 1 << 1; } status = nrf_wifi_fmac_chg_sta(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &chg_sta_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_chg_sta failed", __func__); ret = -1; goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_signal_poll(void *if_priv, struct wpa_signal_info *si, unsigned char *bssid) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; enum nrf_wifi_status ret = NRF_WIFI_STATUS_FAIL; int sem_ret; int rssi_record_elapsed_time_ms = 0; if (!if_priv || !si || !bssid) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; vif_ctx_zep->signal_info = si; rssi_record_elapsed_time_ms = nrf_wifi_osal_time_elapsed_us(fmac_dev_ctx->fpriv->opriv, vif_ctx_zep->rssi_record_timestamp_us) / 1000; if (rssi_record_elapsed_time_ms > CONFIG_NRF70_RSSI_STALE_TIMEOUT_MS) { ret = nrf_wifi_fmac_get_station(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, bssid); if (ret != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Failed to send get station info command", __func__); goto out; } sem_ret = k_sem_take(&wait_for_event_sem, K_MSEC(RPU_RESP_EVENT_TIMEOUT)); if (sem_ret) { LOG_ERR("%s: Failed to get station info, ret = %d", __func__, sem_ret); ret = NRF_WIFI_STATUS_FAIL; goto out; } } else { si->current_signal = (int)vif_ctx_zep->rssi; } ret = nrf_wifi_fmac_get_interface(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx); if (ret != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Failed to send get interface info command", __func__); goto out; } sem_ret = k_sem_take(&wait_for_event_sem, K_MSEC(RPU_RESP_EVENT_TIMEOUT)); if (sem_ret) { LOG_ERR("%s: Failed to get interface info, ret = %d", __func__, sem_ret); ret = NRF_WIFI_STATUS_FAIL; goto out; } vif_ctx_zep->signal_info->frequency = vif_ctx_zep->assoc_freq; out: vif_ctx_zep->signal_info = NULL; k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } void nrf_wifi_wpa_supp_event_proc_get_sta(void *if_priv, struct nrf_wifi_umac_event_new_station *info, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct wpa_signal_info *signal_info = NULL; if (!if_priv || !info) { LOG_ERR("%s: Invalid params", __func__); goto out; } vif_ctx_zep = if_priv; if (!vif_ctx_zep) { LOG_ERR("%s: vif_ctx_zep is NULL", __func__); goto out; } #ifdef CONFIG_NRF70_AP_MODE vif_ctx_zep->inactive_time_sec = info->sta_info.inactive_time; #endif /* CONFIG_NRF70_AP_MODE */ signal_info = vif_ctx_zep->signal_info; /* Semaphore timedout */ if (!signal_info) { goto out; } if (info->sta_info.valid_fields & NRF_WIFI_STA_INFO_SIGNAL_VALID) { signal_info->current_signal = info->sta_info.signal; } else { signal_info->current_signal = -WPA_INVALID_NOISE; } if (info->sta_info.valid_fields & NRF_WIFI_STA_INFO_SIGNAL_AVG_VALID) { signal_info->avg_signal = info->sta_info.signal_avg; } else { signal_info->avg_signal = -WPA_INVALID_NOISE; } if (info->sta_info.valid_fields & NRF_WIFI_STA_INFO_RX_BEACON_SIGNAL_AVG_VALID) { signal_info->avg_beacon_signal = info->sta_info.rx_beacon_signal_avg; } else { signal_info->avg_beacon_signal = -WPA_INVALID_NOISE; } signal_info->current_txrate = 0; if (info->sta_info.valid_fields & NRF_WIFI_STA_INFO_TX_BITRATE_VALID) { if (info->sta_info.tx_bitrate.valid_fields & NRF_WIFI_RATE_INFO_BITRATE_VALID) { signal_info->current_txrate = info->sta_info.tx_bitrate.bitrate * 100; } } out: k_sem_give(&wait_for_event_sem); } void nrf_wifi_wpa_supp_event_proc_get_if(void *if_priv, struct nrf_wifi_interface_info *info, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_chan_definition *chan_def_info = NULL; struct wpa_signal_info *signal_info = NULL; if (!if_priv || !info) { LOG_ERR("%s: Invalid params", __func__); k_sem_give(&wait_for_event_sem); return; } vif_ctx_zep = if_priv; signal_info = vif_ctx_zep->signal_info; /* Semaphore timedout */ if (!signal_info) { LOG_DBG("%s: Get interface Semaphore timedout", __func__); return; } chan_def_info = (struct nrf_wifi_chan_definition *)(&info->chan_def); signal_info->chanwidth = drv2supp_chan_width(chan_def_info->width); signal_info->center_frq1 = chan_def_info->center_frequency1; signal_info->center_frq2 = chan_def_info->center_frequency2; k_sem_give(&wait_for_event_sem); } void nrf_wifi_wpa_supp_event_mgmt_tx_status(void *if_priv, struct nrf_wifi_umac_event_mlme *mlme_event, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; bool acked = false; if (!if_priv) { LOG_ERR("%s: Missing interface context", __func__); return; } vif_ctx_zep = if_priv; if (!mlme_event) { LOG_ERR("%s: Missing MLME event data", __func__); return; } acked = mlme_event->nrf_wifi_flags & NRF_WIFI_EVENT_MLME_ACK ? true : false; LOG_DBG("%s: Mgmt frame %llx tx status: %s", __func__, mlme_event->cookie, acked ? "ACK" : "NOACK"); if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.mgmt_tx_status) { vif_ctx_zep->supp_callbk_fns.mgmt_tx_status(vif_ctx_zep->supp_drv_if_ctx, mlme_event->frame.frame, mlme_event->frame.frame_len, acked); } } void nrf_wifi_wpa_supp_event_proc_unprot_mgmt(void *if_priv, struct nrf_wifi_umac_event_mlme *unprot_mgmt, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; union wpa_event_data event; const struct ieee80211_mgmt *mgmt = NULL; const unsigned char *frame = NULL; unsigned int frame_len = 0; int cmd_evnt = 0; vif_ctx_zep = if_priv; frame = unprot_mgmt->frame.frame; frame_len = unprot_mgmt->frame.frame_len; mgmt = (const struct ieee80211_mgmt *)frame; cmd_evnt = ((struct nrf_wifi_umac_hdr *)unprot_mgmt)->cmd_evnt; if (frame_len < 24 + sizeof(mgmt->u.deauth)) { LOG_ERR("%s: Unprotected mgmt frame too short", __func__); return; } memset(&event, 0, sizeof(event)); event.unprot_deauth.sa = &mgmt->sa[0]; event.unprot_deauth.da = &mgmt->da[0]; if (cmd_evnt == NRF_WIFI_UMAC_EVENT_UNPROT_DEAUTHENTICATE) { event.unprot_deauth.reason_code = le_to_host16(mgmt->u.deauth.reason_code); if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.unprot_deauth) { vif_ctx_zep->supp_callbk_fns.unprot_deauth(vif_ctx_zep->supp_drv_if_ctx, &event); } } else if (cmd_evnt == NRF_WIFI_UMAC_EVENT_UNPROT_DISASSOCIATE) { event.unprot_disassoc.reason_code = le_to_host16(mgmt->u.deauth.reason_code); if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.unprot_disassoc) { vif_ctx_zep->supp_callbk_fns.unprot_disassoc(vif_ctx_zep->supp_drv_if_ctx, &event); } } } int nrf_wifi_nl80211_send_mlme(void *if_priv, const u8 *data, size_t data_len, int noack, unsigned int freq, int no_cck, int offchanok, unsigned int wait_time, int cookie) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_umac_mgmt_tx_info *mgmt_tx_info = NULL; unsigned int timeout = 0; if (!if_priv || !data) { LOG_ERR("%s: Invalid params", __func__); return -1; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return -1; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } k_mutex_lock(&mgmt_tx_lock, K_FOREVER); mgmt_tx_info = k_calloc(sizeof(*mgmt_tx_info), sizeof(char)); if (!mgmt_tx_info) { LOG_ERR("%s: Unable to allocate memory", __func__); goto out; } if (offchanok) mgmt_tx_info->nrf_wifi_flags |= NRF_WIFI_CMD_FRAME_OFFCHANNEL_TX_OK; if (noack) mgmt_tx_info->nrf_wifi_flags |= NRF_WIFI_CMD_FRAME_DONT_WAIT_FOR_ACK; if (no_cck) mgmt_tx_info->nrf_wifi_flags |= NRF_WIFI_CMD_FRAME_TX_NO_CCK_RATE; if (freq) mgmt_tx_info->frequency = freq; if (wait_time) mgmt_tx_info->dur = wait_time; if (data_len) { memcpy(mgmt_tx_info->frame.frame, data, data_len); mgmt_tx_info->frame.frame_len = data_len; } mgmt_tx_info->freq_params.frequency = freq; mgmt_tx_info->freq_params.channel_width = NRF_WIFI_CHAN_WIDTH_20; mgmt_tx_info->freq_params.center_frequency1 = freq; mgmt_tx_info->freq_params.center_frequency2 = 0; mgmt_tx_info->freq_params.channel_type = NRF_WIFI_CHAN_HT20; /* Going to RPU */ mgmt_tx_info->host_cookie = cookie; vif_ctx_zep->cookie_resp_received = false; LOG_DBG("%s: Sending frame to RPU: cookie=%d wait_time=%d no_ack=%d", __func__, cookie, wait_time, noack); status = nrf_wifi_fmac_mgmt_tx(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, mgmt_tx_info); if (status == NRF_WIFI_STATUS_FAIL) { LOG_ERR("%s: nrf_wifi_fmac_mgmt_tx failed", __func__); goto out; } /* Both are needed as we use this to send_action where noack is hardcoded * to 0 always. */ if (wait_time || !noack) { if (!noack && !wait_time) { wait_time = ACTION_FRAME_RESP_TIMEOUT_MS; } while (!vif_ctx_zep->cookie_resp_received && timeout++ < wait_time) { k_sleep(K_MSEC(1)); } if (!vif_ctx_zep->cookie_resp_received) { LOG_ERR("%s: cookie response not received (%dms)", __func__, timeout); status = NRF_WIFI_STATUS_FAIL; goto out; } status = NRF_WIFI_STATUS_SUCCESS; } out: if (mgmt_tx_info) k_free(mgmt_tx_info); k_mutex_unlock(&mgmt_tx_lock); k_mutex_unlock(&vif_ctx_zep->vif_lock); return status; } enum nrf_wifi_status nrf_wifi_parse_sband( struct nrf_wifi_event_supported_band *event, struct wpa_supp_event_supported_band *band ) { int count; if (event && (event->nrf_wifi_n_bitrates == 0 || event->nrf_wifi_n_channels == 0)) { return NRF_WIFI_STATUS_FAIL; } memset(band, 0, sizeof(*band)); band->wpa_supp_n_channels = event->nrf_wifi_n_channels; band->wpa_supp_n_bitrates = event->nrf_wifi_n_bitrates; for (count = 0; count < band->wpa_supp_n_channels; count++) { struct wpa_supp_event_channel *chan = &band->channels[count]; if (count >= WPA_SUPP_SBAND_MAX_CHANNELS) { LOG_ERR("%s: Failed to add channel", __func__); break; } chan->wpa_supp_flags = event->channels[count].nrf_wifi_flags; chan->wpa_supp_max_power = event->channels[count].nrf_wifi_max_power; chan->wpa_supp_time = event->channels[count].nrf_wifi_time; chan->dfs_cac_msec = event->channels[count].dfs_cac_msec; chan->ch_valid = event->channels[count].ch_valid; chan->center_frequency = event->channels[count].center_frequency; chan->dfs_state = event->channels[count].dfs_state; } for (count = 0; count < band->wpa_supp_n_bitrates; count++) { struct wpa_supp_event_rate *rate = &band->bitrates[count]; if (count >= WPA_SUPP_SBAND_MAX_RATES) { LOG_ERR("%s: Failed to add bitrate", __func__); break; } rate->wpa_supp_flags = event->bitrates[count].nrf_wifi_flags; rate->wpa_supp_bitrate = event->bitrates[count].nrf_wifi_bitrate; } band->ht_cap.wpa_supp_ht_supported = event->ht_cap.nrf_wifi_ht_supported; band->ht_cap.wpa_supp_cap = event->ht_cap.nrf_wifi_cap; band->ht_cap.mcs.wpa_supp_rx_highest = event->ht_cap.mcs.nrf_wifi_rx_highest; for (count = 0; count < WPA_SUPP_HT_MCS_MASK_LEN; count++) { band->ht_cap.mcs.wpa_supp_rx_mask[count] = event->ht_cap.mcs.nrf_wifi_rx_mask[count]; } band->ht_cap.mcs.wpa_supp_tx_params = event->ht_cap.mcs.nrf_wifi_tx_params; for (count = 0; count < NRF_WIFI_HT_MCS_RES_LEN; count++) { if (count >= WPA_SUPP_HT_MCS_RES_LEN) { LOG_ERR("%s: Failed to add reserved bytes", __func__); break; } band->ht_cap.mcs.wpa_supp_reserved[count] = event->ht_cap.mcs.nrf_wifi_reserved[count]; } band->ht_cap.wpa_supp_ampdu_factor = event->ht_cap.nrf_wifi_ampdu_factor; band->ht_cap.wpa_supp_ampdu_density = event->ht_cap.nrf_wifi_ampdu_density; band->vht_cap.wpa_supp_vht_supported = event->vht_cap.nrf_wifi_vht_supported; band->vht_cap.wpa_supp_cap = event->vht_cap.nrf_wifi_cap; band->vht_cap.vht_mcs.rx_mcs_map = event->vht_cap.vht_mcs.rx_mcs_map; band->vht_cap.vht_mcs.rx_highest = event->vht_cap.vht_mcs.rx_highest; band->vht_cap.vht_mcs.tx_mcs_map = event->vht_cap.vht_mcs.tx_mcs_map; band->vht_cap.vht_mcs.tx_highest = event->vht_cap.vht_mcs.tx_highest; band->band = event->band; return WLAN_STATUS_SUCCESS; } void nrf_wifi_wpa_supp_event_get_wiphy(void *if_priv, struct nrf_wifi_event_get_wiphy *wiphy_info, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct wpa_supp_event_supported_band band; if (!if_priv || !wiphy_info || !event_len) { LOG_ERR("%s: Invalid parameters", __func__); return; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; memset(&band, 0, sizeof(band)); for (int i = 0; i < NRF_WIFI_EVENT_GET_WIPHY_NUM_BANDS; i++) { if (nrf_wifi_parse_sband(&wiphy_info->sband[i], &band) != WLAN_STATUS_SUCCESS) { continue; } if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.get_wiphy_res) { vif_ctx_zep->supp_callbk_fns.get_wiphy_res(vif_ctx_zep->supp_drv_if_ctx, &band); } } if ((wiphy_info->params_valid & NRF_WIFI_GET_WIPHY_VALID_EXTENDED_CAPABILITIES) && rpu_ctx_zep->extended_capa == NULL) { rpu_ctx_zep->extended_capa = k_malloc(wiphy_info->extended_capabilities_len); if (rpu_ctx_zep->extended_capa) { memcpy(rpu_ctx_zep->extended_capa, wiphy_info->extended_capabilities, wiphy_info->extended_capabilities_len); } rpu_ctx_zep->extended_capa_mask = k_malloc(wiphy_info->extended_capabilities_len); if (rpu_ctx_zep->extended_capa_mask) { memcpy(rpu_ctx_zep->extended_capa_mask, wiphy_info->extended_capabilities_mask, wiphy_info->extended_capabilities_len); } else { free(rpu_ctx_zep->extended_capa); rpu_ctx_zep->extended_capa = NULL; rpu_ctx_zep->extended_capa_len = 0; } } if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.get_wiphy_res) { vif_ctx_zep->supp_callbk_fns.get_wiphy_res(vif_ctx_zep->supp_drv_if_ctx, NULL); } } int nrf_wifi_supp_get_wiphy(void *if_priv) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; if (!if_priv) { LOG_ERR("%s: Missing interface context", __func__); return -1; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return -1; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } status = nrf_wifi_fmac_get_wiphy(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_get_wiphy failed", __func__); goto out; } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return status; } int nrf_wifi_supp_register_frame(void *if_priv, u16 type, const u8 *match, size_t match_len, bool multicast) { enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_umac_mgmt_frame_info frame_info; if (!if_priv || !match || !match_len) { LOG_ERR("%s: Invalid parameters", __func__); return -1; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return -1; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } memset(&frame_info, 0, sizeof(frame_info)); frame_info.frame_type = type; frame_info.frame_match.frame_match_len = match_len; memcpy(frame_info.frame_match.frame_match, match, match_len); status = nrf_wifi_fmac_register_frame(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &frame_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_register_frame failed", __func__); goto out; } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return status; } void nrf_wifi_wpa_supp_event_mgmt_rx_callbk_fn(void *if_priv, struct nrf_wifi_umac_event_mlme *mlme_event, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; if (!if_priv) { LOG_ERR("%s: Missing interface context", __func__); return; } vif_ctx_zep = if_priv; if (!mlme_event || !event_len) { LOG_ERR("%s: Missing MLME event data", __func__); return; } if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.mgmt_rx) { vif_ctx_zep->supp_callbk_fns.mgmt_rx(vif_ctx_zep->supp_drv_if_ctx, mlme_event->frame.frame, mlme_event->frame.frame_len, mlme_event->frequency, mlme_event->rx_signal_dbm); } } int nrf_wifi_supp_get_capa(void *if_priv, struct wpa_driver_capa *capa) { enum nrf_wifi_status status = NRF_WIFI_STATUS_SUCCESS; struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; if (!if_priv || !capa) { LOG_ERR("%s: Invalid parameters", __func__); return -1; } memset(capa, 0, sizeof(*capa)); vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return -1; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } /* TODO: Get these from RPU*/ /* Use SME */ capa->flags = 0; capa->flags |= WPA_DRIVER_FLAGS_SME; capa->flags |= WPA_DRIVER_FLAGS_SAE; capa->flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE; capa->rrm_flags |= WPA_DRIVER_FLAGS_SUPPORT_RRM; capa->rrm_flags |= WPA_DRIVER_FLAGS_SUPPORT_BEACON_REPORT; if (IS_ENABLED(CONFIG_NRF70_AP_MODE)) { capa->flags |= WPA_DRIVER_FLAGS_AP; } capa->enc |= WPA_DRIVER_CAPA_ENC_WEP40 | WPA_DRIVER_CAPA_ENC_WEP104 | WPA_DRIVER_CAPA_ENC_TKIP | WPA_DRIVER_CAPA_ENC_CCMP | WPA_DRIVER_CAPA_ENC_CCMP | WPA_DRIVER_CAPA_ENC_CCMP_256 | WPA_DRIVER_CAPA_ENC_GCMP_256; if (rpu_ctx_zep->extended_capa && rpu_ctx_zep->extended_capa_mask) { capa->extended_capa = rpu_ctx_zep->extended_capa; capa->extended_capa_mask = rpu_ctx_zep->extended_capa_mask; capa->extended_capa_len = rpu_ctx_zep->extended_capa_len; } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return status; } void nrf_wifi_wpa_supp_event_mac_chgd(void *if_priv) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; if (!if_priv) { LOG_ERR("%s: Invalid parameters", __func__); return; } vif_ctx_zep = if_priv; if (vif_ctx_zep->supp_drv_if_ctx && vif_ctx_zep->supp_callbk_fns.mac_changed) { vif_ctx_zep->supp_callbk_fns.mac_changed(vif_ctx_zep->supp_drv_if_ctx); } } int nrf_wifi_supp_get_conn_info(void *if_priv, struct wpa_conn_info *info) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_fmac_dev_ctx *fmac_dev_ctx = NULL; enum nrf_wifi_status ret = NRF_WIFI_STATUS_FAIL; int sem_ret; if (!if_priv || !info) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } fmac_dev_ctx = rpu_ctx_zep->rpu_ctx; vif_ctx_zep->conn_info = info; ret = nrf_wifi_fmac_get_conn_info(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx); if (ret != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_get_conn_info failed", __func__); goto out; } sem_ret = k_sem_take(&wait_for_event_sem, K_MSEC(RPU_RESP_EVENT_TIMEOUT)); if (sem_ret) { LOG_ERR("%s: Timeout: failed to get connection info, ret = %d", __func__, sem_ret); ret = NRF_WIFI_STATUS_FAIL; goto out; } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } void nrf_wifi_supp_event_proc_get_conn_info(void *if_priv, struct nrf_wifi_umac_event_conn_info *info, unsigned int event_len) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct wpa_conn_info *conn_info = NULL; if (!if_priv || !info) { LOG_ERR("%s: Invalid params", __func__); k_sem_give(&wait_for_event_sem); return; } vif_ctx_zep = if_priv; conn_info = vif_ctx_zep->conn_info; conn_info->beacon_interval = info->beacon_interval; conn_info->dtim_period = info->dtim_interval; conn_info->twt_capable = info->twt_capable; k_sem_give(&wait_for_event_sem); } #ifdef CONFIG_NRF70_AP_MODE static int nrf_wifi_vif_state_change(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep, enum nrf_wifi_fmac_if_op_state state) { struct nrf_wifi_umac_chg_vif_state_info vif_state_info = {0}; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; unsigned int timeout = 0; struct nrf_wifi_fmac_vif_ctx *vif_ctx = NULL; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_fmac_dev_ctx_def *def_dev_ctx = NULL; int ret = -1; if (!vif_ctx_zep) { LOG_ERR("%s: Invalid params", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } def_dev_ctx = wifi_dev_priv(rpu_ctx_zep->rpu_ctx); vif_ctx = def_dev_ctx->vif_ctx[vif_ctx_zep->vif_idx]; vif_state_info.state = state; vif_state_info.if_index = vif_ctx_zep->vif_idx; vif_ctx->ifflags = false; status = nrf_wifi_fmac_chg_vif_state(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &vif_state_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_chg_vif_state failed", __func__); goto out; } while (!vif_ctx->ifflags && timeout++ < SET_IFACE_EVENT_TIMEOUT_MS) { k_sleep(K_MSEC(1)); } if (!vif_ctx->ifflags) { LOG_ERR("%s: set interface state event not received (%dms)", __func__, timeout); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } static int nrf_wifi_iftype_change(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep, int iftype) { struct nrf_wifi_umac_chg_vif_attr_info chg_vif_info = {0}; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; int ret = -1; unsigned int timeout = 0; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; if (!vif_ctx_zep) { LOG_ERR("%s: Invalid params", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } ret = nrf_wifi_vif_state_change(vif_ctx_zep, NRF_WIFI_FMAC_IF_OP_STATE_DOWN); if (ret) { LOG_ERR("%s: Failed to set interface down", __func__); goto out; } chg_vif_info.iftype = iftype; vif_ctx_zep->set_if_event_received = false; vif_ctx_zep->set_if_status = 0; status = nrf_wifi_fmac_chg_vif(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &chg_vif_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_chg_vif failed", __func__); goto out; } while (!vif_ctx_zep->set_if_event_received && timeout++ < SET_IFACE_EVENT_TIMEOUT_MS) { k_sleep(K_MSEC(1)); } if (!vif_ctx_zep->set_if_event_received) { LOG_ERR("%s: set interface event not received (%dms)", __func__, timeout); goto out; } if (vif_ctx_zep->set_if_status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: set interface failed: %d", __func__, vif_ctx_zep->set_if_status); goto out; } ret = nrf_wifi_vif_state_change(vif_ctx_zep, NRF_WIFI_FMAC_IF_OP_STATE_UP); if (ret) { LOG_ERR("%s: Failed to set interface up", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } static int nrf_wifi_wait_for_carrier_status(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep, enum nrf_wifi_fmac_if_carr_state carrier_status) { struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; int ret = -1; unsigned int timeout = 0; if (!vif_ctx_zep) { LOG_ERR("%s: Invalid params", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } while (vif_ctx_zep->if_carr_state != carrier_status && timeout++ < CARR_ON_TIMEOUT_MS) { k_sleep(K_MSEC(1)); } if (vif_ctx_zep->if_carr_state != carrier_status) { LOG_ERR("%s: Carrier %s event not received in %dms", __func__, carrier_status == NRF_WIFI_FMAC_IF_CARR_STATE_ON ? "ON" : "OFF", timeout); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_init_ap(void *if_priv, struct wpa_driver_associate_params *params) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; int ret = -1; if (!if_priv || !params) { LOG_ERR("%s: Invalid params", __func__); return ret; } if (params->mode != IEEE80211_MODE_AP) { LOG_ERR("%s: Invalid mode", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } ret = nrf_wifi_iftype_change(vif_ctx_zep, NRF_WIFI_IFTYPE_AP); if (ret) { LOG_ERR("%s: Failed to set interface type to AP: %d", __func__, ret); goto out; } out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } static int wpas_cipher_to_nrf(int cipher) { switch (cipher) { case WPA_CIPHER_NONE: return 0; case WPA_CIPHER_WEP40: return NRF_WIFI_FMAC_CIPHER_SUITE_WEP40; case WPA_CIPHER_WEP104: return NRF_WIFI_FMAC_CIPHER_SUITE_WEP104; case WPA_CIPHER_TKIP: return NRF_WIFI_FMAC_CIPHER_SUITE_TKIP; case WPA_CIPHER_CCMP: return NRF_WIFI_FMAC_CIPHER_SUITE_CCMP; case WPA_CIPHER_CCMP_256: return NRF_WIFI_FMAC_CIPHER_SUITE_CCMP_256; default: return -1; } } static int nrf_wifi_set_beacon_data(const struct wpa_driver_ap_params *params, struct nrf_wifi_beacon_data *beacon_data) { int ret = -1; if (params->head_len > ARRAY_SIZE(beacon_data->head)) { LOG_ERR("%s: head_len too big", __func__); goto out; } if (params->tail_len > ARRAY_SIZE(beacon_data->tail)) { LOG_ERR("%s: tail_len too big", __func__); goto out; } if (params->proberesp_len > ARRAY_SIZE(beacon_data->probe_resp)) { LOG_ERR("%s: proberesp_len too big", __func__); goto out; } beacon_data->head_len = params->head_len; beacon_data->tail_len = params->tail_len; beacon_data->probe_resp_len = params->proberesp_len; if (params->head_len) { memcpy(&beacon_data->head, params->head, params->head_len); } if (params->tail_len) { memcpy(&beacon_data->tail, params->tail, params->tail_len); } if (params->proberesp_len) { memcpy(&beacon_data->probe_resp, params->proberesp_ies, params->proberesp_len); } ret = 0; out: return ret; } int nrf_wifi_supp_register_mgmt_frame(void *if_priv, u16 frame_type, size_t match_len, const u8 *match) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; struct nrf_wifi_umac_mgmt_frame_info mgmt_frame_info = {0}; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int ret = -1; if (!if_priv || (match_len && !match)) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } mgmt_frame_info.frame_type = frame_type; mgmt_frame_info.frame_match.frame_match_len = match_len; if (match_len >= NRF_WIFI_FRAME_MATCH_MAX_LEN) { LOG_ERR("%s: match_len too big: %d (max %d)", __func__, match_len, NRF_WIFI_FRAME_MATCH_MAX_LEN); goto out; } memcpy(mgmt_frame_info.frame_match.frame_match, match, match_len); status = nrf_wifi_fmac_mgmt_frame_reg(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &mgmt_frame_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_mgmt_frame_reg failed", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } /* As per current design default is always STA */ static int is_ap_dynamic_iface(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep) { return (vif_ctx_zep->vif_idx != 0); } static int nrf_wifi_set_bss(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep, struct wpa_driver_ap_params *params) { struct nrf_wifi_umac_bss_info bss_info = {0}; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; int ret = -1; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int i; if (!vif_ctx_zep || !params) { LOG_ERR("%s: Invalid params", __func__); return ret; } rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } if (params->basic_rates) { for (i = 0; params->basic_rates[i] != -1; i++) { if (i >= ARRAY_SIZE(bss_info.basic_rates)) { LOG_ERR("%s: basic_rates too big: %d (max %d)", __func__, i, ARRAY_SIZE(bss_info.basic_rates)); goto out; } bss_info.basic_rates[i] = params->basic_rates[i]; } bss_info.num_basic_rates = i; } bss_info.p2p_go_ctwindow = params->p2p_go_ctwindow; bss_info.ht_opmode = params->ht_opmode; bss_info.nrf_wifi_cts = params->cts_protect; bss_info.preamble = params->preamble; bss_info.nrf_wifi_slot = params->short_slot_time; bss_info.ap_isolate = params->isolate; status = nrf_wifi_fmac_set_bss(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &bss_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_set_bss failed", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } static enum nrf_wifi_chan_width wpa_supp_chan_width_to_nrf(enum hostapd_hw_mode mode, int bandwidth, int cfreq1, int cfreq2) { switch (bandwidth) { case 20: if (mode == HOSTAPD_MODE_IEEE80211B) { return NRF_WIFI_CHAN_WIDTH_20_NOHT; } else { return NRF_WIFI_CHAN_WIDTH_20; }; case 40: return NRF_WIFI_CHAN_WIDTH_40; case 80: if (cfreq2) { return NRF_WIFI_CHAN_WIDTH_80P80; } else { return NRF_WIFI_CHAN_WIDTH_80; } case 160: return NRF_WIFI_CHAN_WIDTH_160; }; return NRF_WIFI_CHAN_WIDTH_20; } int nrf_wifi_wpa_supp_start_ap(void *if_priv, struct wpa_driver_ap_params *params) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; int ret = -1; struct nrf_wifi_umac_start_ap_info start_ap_info = {0}; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int ch_width = 0; if (!if_priv || !params) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } nrf_wifi_set_beacon_data(params, &start_ap_info.beacon_data); start_ap_info.beacon_interval = params->beacon_int; start_ap_info.dtim_period = params->dtim_period; start_ap_info.ssid.nrf_wifi_ssid_len = params->ssid_len; memcpy(start_ap_info.ssid.nrf_wifi_ssid, params->ssid, params->ssid_len); for (int i = 0; i < 32; i++) { if ((params->pairwise_ciphers & BIT(i)) && start_ap_info.connect_common_info.num_cipher_suites_pairwise < 7) { if (wpas_cipher_to_nrf(i) < 0) { LOG_DBG("%s: Unsupported cipher %d ignored", __func__, i); continue; } start_ap_info.connect_common_info.cipher_suites_pairwise[i] = wpas_cipher_to_nrf(i); start_ap_info.connect_common_info.num_cipher_suites_pairwise++; } } ch_width = wpa_supp_chan_width_to_nrf(params->freq->mode, params->freq->bandwidth, params->freq->center_freq1, params->freq->center_freq2); start_ap_info.freq_params.frequency = params->freq->freq; start_ap_info.freq_params.channel_width = ch_width; start_ap_info.freq_params.center_frequency1 = params->freq->center_freq1; start_ap_info.freq_params.center_frequency2 = params->freq->center_freq2; start_ap_info.freq_params.channel_type = params->freq->ht_enabled ? NRF_WIFI_CHAN_HT20 : NRF_WIFI_CHAN_NO_HT; start_ap_info.freq_params.valid_fields = NRF_WIFI_SET_FREQ_PARAMS_FREQ_VALID | NRF_WIFI_SET_FREQ_PARAMS_CHANNEL_WIDTH_VALID | NRF_WIFI_SET_FREQ_PARAMS_CENTER_FREQ1_VALID | NRF_WIFI_SET_FREQ_PARAMS_CENTER_FREQ2_VALID | NRF_WIFI_SET_FREQ_PARAMS_CHANNEL_TYPE_VALID; vif_ctx_zep->if_carr_state = NRF_WIFI_FMAC_IF_CARR_STATE_OFF; status = nrf_wifi_fmac_start_ap(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &start_ap_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_start_ap failed", __func__); goto out; } ret = nrf_wifi_wait_for_carrier_status(vif_ctx_zep, NRF_WIFI_FMAC_IF_CARR_STATE_ON); if (ret) { goto out; } ret = nrf_wifi_set_bss(vif_ctx_zep, params); if (ret) { LOG_ERR("%s: Failed to set BSS", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_change_beacon(void *if_priv, struct wpa_driver_ap_params *params) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; int ret = -1; struct nrf_wifi_umac_set_beacon_info chg_bcn_info = {0}; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; if (!if_priv || !params) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } nrf_wifi_set_beacon_data(params, &chg_bcn_info.beacon_data); status = nrf_wifi_fmac_chg_bcn(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &chg_bcn_info); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_chg_bcn failed", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_stop_ap(void *if_priv) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int ret = -1; if (!if_priv) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } status = nrf_wifi_fmac_stop_ap(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_stop_ap failed", __func__); goto out; } ret = nrf_wifi_wait_for_carrier_status(vif_ctx_zep, NRF_WIFI_FMAC_IF_CARR_STATE_OFF); if (ret) { goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_deinit_ap(void *if_priv) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int ret = -1; if (!if_priv) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_DBG("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } status = nrf_wifi_wpa_supp_stop_ap(if_priv); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: Failed to stop AP", __func__); goto out; } if (!is_ap_dynamic_iface(vif_ctx_zep)) { ret = nrf_wifi_iftype_change(vif_ctx_zep, NRF_WIFI_IFTYPE_STATION); if (ret) { LOG_ERR("%s: Failed to set interface type to STATION: %d", __func__, ret); goto out; } } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_sta_flags_to_nrf(int wpas_sta_flags) { int nrf_sta_flags = 0; if (wpas_sta_flags & WPA_STA_AUTHORIZED) { nrf_sta_flags |= NRF_WIFI_STA_FLAG_AUTHORIZED; } if (wpas_sta_flags & WPA_STA_WMM) { nrf_sta_flags |= NRF_WIFI_STA_FLAG_WME; } if (wpas_sta_flags & WPA_STA_SHORT_PREAMBLE) { nrf_sta_flags |= NRF_WIFI_STA_FLAG_SHORT_PREAMBLE; } if (wpas_sta_flags & WPA_STA_MFP) { nrf_sta_flags |= NRF_WIFI_STA_FLAG_MFP; } if (wpas_sta_flags & WPA_STA_TDLS_PEER) { nrf_sta_flags |= NRF_WIFI_STA_FLAG_TDLS_PEER; } /* Note: Do not set flags > NRF_WIFI_STA_FLAG_TDLS_PEER, else * nrf_wifi_fmac_chg_sta will fail. This is equivalent to not * setting WPA_DRIVER_FLAGS_FULL_AP_CLIENT_STATE flag. */ return nrf_sta_flags; } int nrf_wifi_wpa_supp_sta_add(void *if_priv, struct hostapd_sta_add_params *params) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; struct nrf_wifi_umac_add_sta_info sta_info = {0}; int ret = -1; int i; if (!if_priv || !params) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_ERR("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } sta_info.nrf_wifi_listen_interval = params->listen_interval; sta_info.aid = params->aid; sta_info.sta_capability = params->capability; sta_info.supp_rates.nrf_wifi_num_rates = params->supp_rates_len; /* TODO: sta_info.supp_rates.band */ for (i = 0; i < params->supp_rates_len; i++) { sta_info.supp_rates.rates[i] = params->supp_rates[i] & 0x7f; } sta_info.ext_capability.ext_capability_len = params->ext_capab_len; if (params->ext_capab_len >= NRF_WIFI_EXT_CAPABILITY_MAX_LEN) { LOG_ERR("%s: ext_capab_len too big: %d (max %d)", __func__, params->ext_capab_len, NRF_WIFI_EXT_CAPABILITY_MAX_LEN); goto out; } memcpy(sta_info.ext_capability.ext_capability, params->ext_capab, params->ext_capab_len); sta_info.supported_channels.supported_channels_len = params->supp_channels_len; if (params->supp_channels_len >= NRF_WIFI_SUPPORTED_CHANNELS_MAX_LEN) { LOG_ERR("%s: supp_channels_len too big: %d (max %d)", __func__, params->supp_channels_len, NRF_WIFI_SUPPORTED_CHANNELS_MAX_LEN); goto out; } memcpy(sta_info.supported_channels.supported_channels, params->supp_channels, params->supp_channels_len); sta_info.supported_oper_classes.supported_oper_classes_len = params->supp_oper_classes_len; if (params->supp_oper_classes_len >= NRF_WIFI_OPER_CLASSES_MAX_LEN) { LOG_ERR("%s: supp_oper_classes_len too big: %d (max %d)", __func__, params->supp_oper_classes_len, NRF_WIFI_OPER_CLASSES_MAX_LEN); goto out; } memcpy(sta_info.supported_oper_classes.supported_oper_classes, params->supp_oper_classes, params->supp_oper_classes_len); sta_info.sta_flags2.nrf_wifi_set = nrf_wifi_sta_flags_to_nrf(params->flags); sta_info.sta_flags2.nrf_wifi_mask = sta_info.sta_flags2.nrf_wifi_set | nrf_wifi_sta_flags_to_nrf(params->flags_mask); if (params->ht_capabilities) { memcpy(sta_info.ht_capability, params->ht_capabilities, sizeof(sta_info.ht_capability)); } if (params->vht_capabilities) { memcpy(sta_info.vht_capability, params->vht_capabilities, sizeof(sta_info.vht_capability)); } memcpy(sta_info.mac_addr, params->addr, sizeof(sta_info.mac_addr)); LOG_DBG("%s: %x, %x", __func__, sta_info.sta_flags2.nrf_wifi_set, sta_info.sta_flags2.nrf_wifi_mask); if (params->set) { status = nrf_wifi_fmac_chg_sta(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, (struct nrf_wifi_umac_chg_sta_info *)&sta_info); } else { status = nrf_wifi_fmac_add_sta(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &sta_info); } if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_add_sta failed", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_sta_remove(void *if_priv, const u8 *addr) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_umac_del_sta_info del_sta = {0}; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int ret = -1; if (!if_priv || !addr) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_DBG("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } memcpy(del_sta.mac_addr, addr, sizeof(del_sta.mac_addr)); status = nrf_wifi_fmac_del_sta(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &del_sta); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_del_sta failed", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_sta_set_flags(void *if_priv, const u8 *addr, unsigned int total_flags, unsigned int flags_or, unsigned int flags_and) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_umac_chg_sta_info chg_sta = {0}; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int ret = -1; if (!if_priv || !addr) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_DBG("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } memcpy(chg_sta.mac_addr, addr, sizeof(chg_sta.mac_addr)); chg_sta.sta_flags2.nrf_wifi_mask = nrf_wifi_sta_flags_to_nrf(flags_or | ~flags_and); chg_sta.sta_flags2.nrf_wifi_set = nrf_wifi_sta_flags_to_nrf(flags_or); LOG_DBG("%s %x, %x", __func__, chg_sta.sta_flags2.nrf_wifi_set, chg_sta.sta_flags2.nrf_wifi_mask); status = nrf_wifi_fmac_chg_sta(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, &chg_sta); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_chg_sta failed", __func__); goto out; } ret = 0; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return ret; } int nrf_wifi_wpa_supp_sta_get_inact_sec(void *if_priv, const u8 *addr) { struct nrf_wifi_vif_ctx_zep *vif_ctx_zep = NULL; struct nrf_wifi_ctx_zep *rpu_ctx_zep = NULL; enum nrf_wifi_status status = NRF_WIFI_STATUS_FAIL; int ret = -1, sem_ret; int inactive_time_sec = -1; if (!if_priv || !addr) { LOG_ERR("%s: Invalid params", __func__); return ret; } vif_ctx_zep = if_priv; rpu_ctx_zep = vif_ctx_zep->rpu_ctx_zep; if (!rpu_ctx_zep) { LOG_DBG("%s: rpu_ctx_zep is NULL", __func__); return ret; } k_mutex_lock(&vif_ctx_zep->vif_lock, K_FOREVER); if (!rpu_ctx_zep->rpu_ctx) { LOG_DBG("%s: RPU context not initialized", __func__); goto out; } status = nrf_wifi_fmac_get_station(rpu_ctx_zep->rpu_ctx, vif_ctx_zep->vif_idx, (unsigned char *) addr); if (status != NRF_WIFI_STATUS_SUCCESS) { LOG_ERR("%s: nrf_wifi_fmac_get_station failed", __func__); goto out; } sem_ret = k_sem_take(&wait_for_event_sem, K_MSEC(RPU_RESP_EVENT_TIMEOUT)); if (sem_ret) { LOG_ERR("%s: Timed out to get station info, ret = %d", __func__, sem_ret); ret = NRF_WIFI_STATUS_FAIL; goto out; } inactive_time_sec = vif_ctx_zep->inactive_time_sec; out: k_mutex_unlock(&vif_ctx_zep->vif_lock); return inactive_time_sec; } #endif /* CONFIG_NRF70_AP_MODE */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/wpa_supp_if.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
23,614
```c /* * */ /** * @brief File containing SPI device interface specific definitions for the * Zephyr OS layer of the Wi-Fi driver. */ #include <string.h> #include <zephyr/drivers/spi.h> #include <zephyr/logging/log.h> #include "qspi_if.h" #include "spi_if.h" LOG_MODULE_DECLARE(wifi_nrf_bus, CONFIG_WIFI_NRF70_BUS_LOG_LEVEL); #define NRF7002_NODE DT_NODELABEL(nrf70) static struct qspi_config *spim_config; static const struct spi_dt_spec spi_spec = SPI_DT_SPEC_GET(NRF7002_NODE, SPI_WORD_SET(8) | SPI_TRANSFER_MSB, 0); static int spim_xfer_tx(unsigned int addr, void *data, unsigned int len) { int err; uint8_t hdr[4] = { 0x02, /* PP opcode */ (((addr >> 16) & 0xFF) | 0x80), (addr >> 8) & 0xFF, (addr & 0xFF) }; const struct spi_buf tx_buf[] = { {.buf = hdr, .len = sizeof(hdr) }, {.buf = data, .len = len }, }; const struct spi_buf_set tx = { .buffers = tx_buf, .count = 2 }; err = spi_transceive_dt(&spi_spec, &tx, NULL); return err; } static int spim_xfer_rx(unsigned int addr, void *data, unsigned int len, unsigned int discard_bytes) { uint8_t hdr[] = { 0x0b, /* FASTREAD opcode */ (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF, 0 /* dummy byte */ }; const struct spi_buf tx_buf[] = { {.buf = hdr, .len = sizeof(hdr) }, {.buf = NULL, .len = len }, }; const struct spi_buf_set tx = { .buffers = tx_buf, .count = 2 }; const struct spi_buf rx_buf[] = { {.buf = NULL, .len = sizeof(hdr) + discard_bytes}, {.buf = data, .len = len }, }; const struct spi_buf_set rx = { .buffers = rx_buf, .count = 2 }; return spi_transceive_dt(&spi_spec, &tx, &rx); } int spim_read_reg(uint32_t reg_addr, uint8_t *reg_value) { int err; uint8_t tx_buffer[6] = { reg_addr }; const struct spi_buf tx_buf = { .buf = tx_buffer, .len = sizeof(tx_buffer) }; const struct spi_buf_set tx = { .buffers = &tx_buf, .count = 1 }; uint8_t sr[6]; struct spi_buf rx_buf = { .buf = &sr, .len = sizeof(sr), }; const struct spi_buf_set rx = { .buffers = &rx_buf, .count = 1 }; err = spi_transceive_dt(&spi_spec, &tx, &rx); LOG_DBG("err: %d -> %x %x %x %x %x %x", err, sr[0], sr[1], sr[2], sr[3], sr[4], sr[5]); if (err == 0) *reg_value = sr[1]; return err; } int spim_write_reg(uint32_t reg_addr, const uint8_t reg_value) { int err; uint8_t tx_buffer[] = { reg_addr, reg_value }; const struct spi_buf tx_buf = { .buf = tx_buffer, .len = sizeof(tx_buffer) }; const struct spi_buf_set tx = { .buffers = &tx_buf, .count = 1 }; err = spi_transceive_dt(&spi_spec, &tx, NULL); if (err) { LOG_ERR("SPI error: %d", err); } return err; } int spim_RDSR1(const struct device *dev, uint8_t *rdsr1) { uint8_t val = 0; return spim_read_reg(0x1F, &val); } int spim_RDSR2(const struct device *dev, uint8_t *rdsr1) { uint8_t val = 0; return spim_read_reg(0x2F, &val); } int spim_WRSR2(const struct device *dev, const uint8_t wrsr2) { return spim_write_reg(0x3F, wrsr2); } int _spim_wait_while_rpu_awake(void) { int ret; uint8_t val = 0; for (int ii = 0; ii < 10; ii++) { ret = spim_read_reg(0x1F, &val); LOG_DBG("RDSR1 = 0x%x", val); if (!ret && (val & RPU_AWAKE_BIT)) { break; } k_msleep(1); } if (ret || !(val & RPU_AWAKE_BIT)) { LOG_ERR("RPU is not awake even after 10ms"); return -1; } return val; } /* Wait until RDSR2 confirms RPU_WAKEUP_NOW write is successful */ int spim_wait_while_rpu_wake_write(void) { int ret; uint8_t val = 0; for (int ii = 0; ii < 10; ii++) { ret = spim_read_reg(0x2F, &val); LOG_DBG("RDSR2 = 0x%x", val); if (!ret && (val & RPU_WAKEUP_NOW)) { break; } k_msleep(1); } if (ret || !(val & RPU_WAKEUP_NOW)) { LOG_ERR("RPU wakeup write ACK failed even after 10ms"); return -1; } return ret; } int spim_cmd_rpu_wakeup(uint32_t data) { return spim_write_reg(0x3F, data); } unsigned int spim_cmd_sleep_rpu(void) { int err; uint8_t tx_buffer[] = { 0x3f, 0x0 }; const struct spi_buf tx_buf = { .buf = tx_buffer, .len = sizeof(tx_buffer) }; const struct spi_buf_set tx = { .buffers = &tx_buf, .count = 1 }; err = spi_transceive_dt(&spi_spec, &tx, NULL); if (err) { LOG_ERR("SPI error: %d", err); } return 0; } int spim_init(struct qspi_config *config) { if (!spi_is_ready_dt(&spi_spec)) { LOG_ERR("Device %s is not ready", spi_spec.bus->name); return -ENODEV; } spim_config = config; k_sem_init(&spim_config->lock, 1, 1); if (spi_spec.config.frequency >= MHZ(16)) { spim_config->qspi_slave_latency = 1; } LOG_INF("SPIM %s: freq = %d MHz", spi_spec.bus->name, spi_spec.config.frequency / MHZ(1)); LOG_INF("SPIM %s: latency = %d", spi_spec.bus->name, spim_config->qspi_slave_latency); return 0; } int spim_deinit(void) { LOG_DBG("TODO : %s", __func__); return 0; } static void spim_addr_check(unsigned int addr, const void *data, unsigned int len) { if ((addr % 4 != 0) || (((unsigned int)data) % 4 != 0) || (len % 4 != 0)) { LOG_ERR("%s : Unaligned address %x %x %d %x %x", __func__, addr, (unsigned int)data, (addr % 4 != 0), (((unsigned int)data) % 4 != 0), (len % 4 != 0)); } } int spim_write(unsigned int addr, const void *data, int len) { int status; spim_addr_check(addr, data, len); addr |= spim_config->addrmask; k_sem_take(&spim_config->lock, K_FOREVER); status = spim_xfer_tx(addr, (void *)data, len); k_sem_give(&spim_config->lock); return status; } int spim_read(unsigned int addr, void *data, int len) { int status; spim_addr_check(addr, data, len); addr |= spim_config->addrmask; k_sem_take(&spim_config->lock, K_FOREVER); status = spim_xfer_rx(addr, data, len, 0); k_sem_give(&spim_config->lock); return status; } static int spim_hl_readw(unsigned int addr, void *data) { int status = -1; k_sem_take(&spim_config->lock, K_FOREVER); status = spim_xfer_rx(addr, data, 4, 4 * spim_config->qspi_slave_latency); k_sem_give(&spim_config->lock); return status; } int spim_hl_read(unsigned int addr, void *data, int len) { int count = 0; spim_addr_check(addr, data, len); while (count < (len / 4)) { spim_hl_readw(addr + (4 * count), (char *)data + (4 * count)); count++; } return 0; } /* ------------------------------added for wifi utils -------------------------------- */ int spim_cmd_rpu_wakeup_fn(uint32_t data) { return spim_cmd_rpu_wakeup(data); } int spim_cmd_sleep_rpu_fn(void) { return spim_cmd_sleep_rpu(); } int spim_wait_while_rpu_awake(void) { return _spim_wait_while_rpu_awake(); } int spi_validate_rpu_wake_writecmd(void) { return spim_wait_while_rpu_wake_write(); } ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/qspi/src/spi_if.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,173
```objective-c /* * */ /** * @brief Header containing SPI device interface specific declarations for the * Zephyr OS layer of the Wi-Fi driver. */ /* SPIM driver config */ int spim_init(struct qspi_config *config); int spim_deinit(void); int spim_write(unsigned int addr, const void *data, int len); int spim_read(unsigned int addr, void *data, int len); int spim_hl_read(unsigned int addr, void *data, int len); int spim_cmd_rpu_wakeup_fn(uint32_t data); int spim_wait_while_rpu_awake(void); int spi_validate_rpu_wake_writecmd(void); int spim_cmd_sleep_rpu_fn(void); int spim_RDSR1(const struct device *dev, uint8_t *rdsr1); int spim_RDSR2(const struct device *dev, uint8_t *rdsr2); int spim_WRSR2(const struct device *dev, const uint8_t wrsr2); ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/qspi/inc/spi_if.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
213
```c /* * */ /** * @brief File containing common functions for RPU hardware interaction * using QSPI and SPI that can be invoked by shell or the driver. */ #include <string.h> #include <sys/time.h> #include <zephyr/kernel.h> #include <zephyr/sys/printk.h> #include <zephyr/devicetree.h> #include <zephyr/dt-bindings/gpio/nordic-nrf-gpio.h> #include <zephyr/logging/log.h> #include "rpu_hw_if.h" #include "qspi_if.h" #include "spi_if.h" LOG_MODULE_REGISTER(wifi_nrf_bus, CONFIG_WIFI_NRF70_BUS_LOG_LEVEL); #define NRF7002_NODE DT_NODELABEL(nrf70) static const struct gpio_dt_spec host_irq_spec = GPIO_DT_SPEC_GET(NRF7002_NODE, host_irq_gpios); static const struct gpio_dt_spec iovdd_ctrl_spec = GPIO_DT_SPEC_GET(NRF7002_NODE, iovdd_ctrl_gpios); static const struct gpio_dt_spec bucken_spec = GPIO_DT_SPEC_GET(NRF7002_NODE, bucken_gpios); char blk_name[][15] = { "SysBus", "ExtSysBus", "PBus", "PKTRAM", "GRAM", "LMAC_ROM", "LMAC_RET_RAM", "LMAC_SRC_RAM", "UMAC_ROM", "UMAC_RET_RAM", "UMAC_SRC_RAM" }; uint32_t rpu_7002_memmap[][3] = { { 0x000000, 0x008FFF, 1 }, { 0x009000, 0x03FFFF, 2 }, { 0x040000, 0x07FFFF, 1 }, { 0x0C0000, 0x0F0FFF, 0 }, { 0x080000, 0x092000, 1 }, { 0x100000, 0x134000, 1 }, { 0x140000, 0x14C000, 1 }, { 0x180000, 0x190000, 1 }, { 0x200000, 0x261800, 1 }, { 0x280000, 0x2A4000, 1 }, { 0x300000, 0x338000, 1 } }; static const struct qspi_dev *qdev; static struct qspi_config *cfg; static int validate_addr_blk(uint32_t start_addr, uint32_t end_addr, uint32_t block_no, bool *hl_flag, int *selected_blk) { uint32_t *block_map = rpu_7002_memmap[block_no]; if (((start_addr >= block_map[0]) && (start_addr <= block_map[1])) && ((end_addr >= block_map[0]) && (end_addr <= block_map[1]))) { if (block_no == PKTRAM) { *hl_flag = 0; } *selected_blk = block_no; return 0; } return -1; } static int rpu_validate_addr(uint32_t start_addr, uint32_t len, bool *hl_flag) { int ret = 0, i; uint32_t end_addr; int selected_blk; end_addr = start_addr + len - 1; *hl_flag = 1; for (i = 0; i < NUM_MEM_BLOCKS; i++) { ret = validate_addr_blk(start_addr, end_addr, i, hl_flag, &selected_blk); if (!ret) { break; } } if (ret) { LOG_ERR("Address validation failed - pls check memmory map and re-try"); return -1; } if ((selected_blk == LMAC_ROM) || (selected_blk == UMAC_ROM)) { LOG_ERR("Error: Cannot write to ROM blocks"); return -1; } cfg->qspi_slave_latency = (*hl_flag) ? rpu_7002_memmap[selected_blk][2] : 0; return 0; } int rpu_irq_config(struct gpio_callback *irq_callback_data, void (*irq_handler)()) { int ret; if (!device_is_ready(host_irq_spec.port)) { LOG_ERR("Host IRQ GPIO %s is not ready", host_irq_spec.port->name); return -ENODEV; } ret = gpio_pin_configure_dt(&host_irq_spec, GPIO_INPUT); if (ret) { LOG_ERR("Failed to configure host_irq pin %d", host_irq_spec.pin); goto out; } ret = gpio_pin_interrupt_configure_dt(&host_irq_spec, GPIO_INT_EDGE_TO_ACTIVE); if (ret) { LOG_ERR("Failed to configure interrupt on host_irq pin %d", host_irq_spec.pin); goto out; } gpio_init_callback(irq_callback_data, irq_handler, BIT(host_irq_spec.pin)); ret = gpio_add_callback(host_irq_spec.port, irq_callback_data); if (ret) { LOG_ERR("Failed to add callback on host_irq pin %d", host_irq_spec.pin); goto out; } LOG_DBG("Finished Interrupt config\n"); out: return ret; } int rpu_irq_remove(struct gpio_callback *irq_callback_data) { int ret; ret = gpio_pin_configure_dt(&host_irq_spec, GPIO_DISCONNECTED); if (ret) { LOG_ERR("Failed to remove host_irq pin %d", host_irq_spec.pin); goto out; } ret = gpio_remove_callback(host_irq_spec.port, irq_callback_data); if (ret) { LOG_ERR("Failed to remove callback on host_irq pin %d", host_irq_spec.pin); goto out; } out: return ret; } static int rpu_gpio_config(void) { int ret; if (!device_is_ready(iovdd_ctrl_spec.port)) { LOG_ERR("IOVDD GPIO %s is not ready", iovdd_ctrl_spec.port->name); return -ENODEV; } if (!device_is_ready(bucken_spec.port)) { LOG_ERR("BUCKEN GPIO %s is not ready", bucken_spec.port->name); return -ENODEV; } ret = gpio_pin_configure_dt(&bucken_spec, (GPIO_OUTPUT | NRF_GPIO_DRIVE_H0H1)); if (ret) { LOG_ERR("BUCKEN GPIO configuration failed..."); return ret; } ret = gpio_pin_configure_dt(&iovdd_ctrl_spec, GPIO_OUTPUT); if (ret) { LOG_ERR("IOVDD GPIO configuration failed..."); gpio_pin_configure_dt(&bucken_spec, GPIO_DISCONNECTED); return ret; } LOG_DBG("GPIO configuration done...\n"); return 0; } static int rpu_gpio_remove(void) { int ret; ret = gpio_pin_configure_dt(&bucken_spec, GPIO_DISCONNECTED); if (ret) { LOG_ERR("BUCKEN GPIO remove failed..."); return ret; } ret = gpio_pin_configure_dt(&iovdd_ctrl_spec, GPIO_DISCONNECTED); if (ret) { LOG_ERR("IOVDD GPIO remove failed..."); return ret; } LOG_DBG("GPIO remove done...\n"); return ret; } static int rpu_pwron(void) { int ret; ret = gpio_pin_set_dt(&bucken_spec, 1); if (ret) { LOG_ERR("BUCKEN GPIO set failed..."); return ret; } /* Settling time is 50us (H0) or 100us (L0) */ k_msleep(1); ret = gpio_pin_set_dt(&iovdd_ctrl_spec, 1); if (ret) { LOG_ERR("IOVDD GPIO set failed..."); gpio_pin_set_dt(&bucken_spec, 0); return ret; } /* Settling time for iovdd nRF7002 DK/EK - switch (TCK106AG): ~600us */ k_msleep(1); if (IS_ENABLED(CONFIG_NRF_WIFI_COMBINED_BUCKEN_IOVDD_GPIO)) { /* When a single GPIO is used, we need a total wait time after bucken assertion * to be 6ms (1ms + 1ms + 4ms). */ k_msleep(4); } LOG_DBG("Bucken = %d, IOVDD = %d", gpio_pin_get_dt(&bucken_spec), gpio_pin_get_dt(&iovdd_ctrl_spec)); return ret; } static int rpu_pwroff(void) { int ret; ret = gpio_pin_set_dt(&bucken_spec, 0); /* BUCKEN = 0 */ if (ret) { LOG_ERR("BUCKEN GPIO set failed..."); return ret; } ret = gpio_pin_set_dt(&iovdd_ctrl_spec, 0); /* IOVDD CNTRL = 0 */ if (ret) { LOG_ERR("IOVDD GPIO set failed..."); return ret; } return ret; } int rpu_read(unsigned int addr, void *data, int len) { bool hl_flag; if (rpu_validate_addr(addr, len, &hl_flag)) { return -1; } if (hl_flag) return qdev->hl_read(addr, data, len); else return qdev->read(addr, data, len); } int rpu_write(unsigned int addr, const void *data, int len) { bool hl_flag; if (rpu_validate_addr(addr, len, &hl_flag)) { return -1; } return qdev->write(addr, data, len); } int rpu_sleep(void) { #if CONFIG_NRF70_ON_QSPI return qspi_cmd_sleep_rpu(&qspi_perip); #else return spim_cmd_sleep_rpu_fn(); #endif } int rpu_wakeup(void) { int ret; ret = rpu_wrsr2(1); if (ret) { LOG_ERR("Error: WRSR2 failed"); return ret; } ret = rpu_rdsr2(); if (ret < 0) { LOG_ERR("Error: RDSR2 failed"); return ret; } ret = rpu_rdsr1(); if (ret < 0) { LOG_ERR("Error: RDSR1 failed"); return ret; } return 0; } int rpu_sleep_status(void) { return rpu_rdsr1(); } void rpu_get_sleep_stats(uint32_t addr, uint32_t *buff, uint32_t wrd_len) { int ret; ret = rpu_wakeup(); if (ret) { LOG_ERR("Error: RPU wakeup failed"); return; } ret = rpu_read(addr, buff, wrd_len * 4); if (ret) { LOG_ERR("Error: RPU read failed"); return; } ret = rpu_sleep(); if (ret) { LOG_ERR("Error: RPU sleep failed"); return; } } int rpu_wrsr2(uint8_t data) { int ret; #if CONFIG_NRF70_ON_QSPI ret = qspi_cmd_wakeup_rpu(&qspi_perip, data); #else ret = spim_cmd_rpu_wakeup_fn(data); #endif LOG_DBG("Written 0x%x to WRSR2", data); return ret; } int rpu_rdsr2(void) { #if CONFIG_NRF70_ON_QSPI return qspi_validate_rpu_wake_writecmd(&qspi_perip); #else return spi_validate_rpu_wake_writecmd(); #endif } int rpu_rdsr1(void) { #if CONFIG_NRF70_ON_QSPI return qspi_wait_while_rpu_awake(&qspi_perip); #else return spim_wait_while_rpu_awake(); #endif } int rpu_clks_on(void) { uint32_t rpu_clks = 0x100; /* Enable RPU Clocks */ qdev->write(0x048C20, &rpu_clks, 4); LOG_DBG("RPU Clocks ON..."); return 0; } int rpu_init(void) { int ret; qdev = qspi_dev(); cfg = qspi_get_config(); ret = rpu_gpio_config(); if (ret) { goto out; } #ifdef CONFIG_NRF70_SR_COEX_RF_SWITCH ret = sr_gpio_config(); if (ret) { goto remove_rpu_gpio; } #endif ret = rpu_pwron(); if (ret) { #ifdef CONFIG_NRF70_SR_COEX_RF_SWITCH goto remove_sr_gpio; #else goto remove_rpu_gpio; #endif } return 0; #ifdef CONFIG_NRF70_SR_COEX_RF_SWITCH remove_sr_gpio: sr_gpio_remove(); #endif remove_rpu_gpio: rpu_gpio_remove(); out: return ret; } int rpu_enable(void) { int ret; ret = rpu_wakeup(); if (ret) { goto rpu_pwroff; } ret = rpu_clks_on(); if (ret) { goto rpu_pwroff; } return 0; rpu_pwroff: rpu_pwroff(); return ret; } int rpu_disable(void) { int ret; ret = rpu_pwroff(); if (ret) { goto out; } ret = rpu_gpio_remove(); if (ret) { goto out; } #ifdef CONFIG_NRF70_SR_COEX_RF_SWITCH ret = sr_gpio_remove(); if (ret) { goto out; } #endif qdev = NULL; cfg = NULL; out: return ret; } ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/qspi/src/rpu_hw_if.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,916
```objective-c /* * */ /** * @brief Header containing address/offets and functions for writing * the FICR fields of the OTP memory on nRF7002 device */ #ifndef __OTP_PROG_H_ #define __OTP_PROG_H_ #include <stdio.h> #include <stdlib.h> int write_otp_memory(unsigned int otp_addr, unsigned int *write_val); int read_otp_memory(unsigned int otp_addr, unsigned int *read_val, int len); unsigned int check_protection(unsigned int *buff, unsigned int off1, unsigned int off2, unsigned int off3, unsigned int off4); #endif /* __OTP_PROG_H_ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/qspi/inc/ficr_prog.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
135
```objective-c /* * */ /** * @brief Header containing common functions for RPU hardware interaction * using QSPI and SPI that can be invoked by shell or the driver. */ #ifndef __RPU_HW_IF_H_ #define __RPU_HW_IF_H_ #include <stdio.h> #include <stdlib.h> #include <zephyr/drivers/gpio.h> enum { SYSBUS = 0, EXT_SYS_BUS, PBUS, PKTRAM, GRAM, LMAC_ROM, LMAC_RET_RAM, LMAC_SRC_RAM, UMAC_ROM, UMAC_RET_RAM, UMAC_SRC_RAM, NUM_MEM_BLOCKS }; extern char blk_name[][15]; extern uint32_t rpu_7002_memmap[][3]; int rpu_read(unsigned int addr, void *data, int len); int rpu_write(unsigned int addr, const void *data, int len); int rpu_sleep(void); int rpu_wakeup(void); int rpu_sleep_status(void); void rpu_get_sleep_stats(uint32_t addr, uint32_t *buff, uint32_t wrd_len); int rpu_irq_config(struct gpio_callback *irq_callback_data, void (*irq_handler)()); int rpu_irq_remove(struct gpio_callback *irq_callback_data); int rpu_wrsr2(uint8_t data); int rpu_rdsr2(void); int rpu_rdsr1(void); int rpu_clks_on(void); int rpu_init(void); int rpu_enable(void); int rpu_disable(void); #ifdef CONFIG_NRF70_SR_COEX_RF_SWITCH int sr_ant_switch(unsigned int ant_switch); int sr_gpio_remove(void); int sr_gpio_config(void); #endif /* CONFIG_NRF70_SR_COEX_RF_SWITCH */ #endif /* __RPU_HW_IF_H_ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/qspi/inc/rpu_hw_if.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
373
```objective-c /* * */ /** * @brief Header containing SPI device specific declarations for the * Zephyr OS layer of the Wi-Fi driver. */ #ifndef __SPI_NOR_H__ #define __SPI_NOR_H__ #include <zephyr/sys/util.h> #define SPI_NOR_MAX_ID_LEN 3 /* Status register bits */ #define SPI_NOR_WIP_BIT BIT(0) /* Write in progress */ #define SPI_NOR_WEL_BIT BIT(1) /* Write enable latch */ /* Flash opcodes */ #define SPI_NOR_CMD_WRSR 0x01 /* Write status register */ #define SPI_NOR_CMD_RDSR 0x05 /* Read status register */ #define SPI_NOR_CMD_READ 0x03 /* Read data */ #define SPI_NOR_CMD_WREN 0x06 /* Write enable */ #define SPI_NOR_CMD_WRDI 0x04 /* Write disable */ #define SPI_NOR_CMD_PP 0x02 /* Page program */ #define SPI_NOR_CMD_SE 0x20 /* Sector erase */ #define SPI_NOR_CMD_BE_32K 0x52 /* Block erase 32KB */ #define SPI_NOR_CMD_BE 0xD8 /* Block erase */ #define SPI_NOR_CMD_CE 0xC7 /* Chip erase */ #define SPI_NOR_CMD_RDID 0x9F /* Read JEDEC ID */ #define SPI_NOR_CMD_ULBPR 0x98 /* Global Block Protection Unlock */ #define SPI_NOR_CMD_4BA 0xB7 /* Enter 4-Byte Address Mode */ #define SPI_NOR_CMD_DPD 0xB9 /* Deep Power Down */ #define SPI_NOR_CMD_RDPD 0xAB /* Release from Deep Power Down */ /* Page, sector, and block size are standard, not configurable. */ #define SPI_NOR_PAGE_SIZE 0x0100U #define SPI_NOR_SECTOR_SIZE 0x1000U #define SPI_NOR_BLOCK_SIZE 0x10000U /* Test whether offset is aligned to a given number of bits. */ #define SPI_NOR_IS_ALIGNED(_ofs, _bits) (((_ofs)&BIT_MASK(_bits)) == 0) #define SPI_NOR_IS_SECTOR_ALIGNED(_ofs) SPI_NOR_IS_ALIGNED(_ofs, 12) #endif /*__SPI_NOR_H__*/ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/qspi/inc/spi_nor.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
478
```objective-c /* * */ /** * @brief Header containing display scan specific declarations for the * Zephyr OS layer of the Wi-Fi driver. */ #ifndef __ZEPHYR_DISP_SCAN_H__ #define __ZEPHYR_DISP_SCAN_H__ #include <zephyr/device.h> #include <zephyr/net/wifi_mgmt.h> #include "osal_api.h" int nrf_wifi_disp_scan_zep(const struct device *dev, struct wifi_scan_params *params, scan_result_cb_t cb); enum nrf_wifi_status nrf_wifi_disp_scan_res_get_zep(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep); void nrf_wifi_event_proc_disp_scan_res_zep(void *vif_ctx, struct nrf_wifi_umac_event_new_scan_display_results *scan_res, unsigned int event_len, bool is_last); #ifdef CONFIG_WIFI_MGMT_RAW_SCAN_RESULTS void nrf_wifi_rx_bcn_prb_resp_frm(void *vif_ctx, void *frm, unsigned short frequency, signed short signal); #endif /* CONFIG_WIFI_MGMT_RAW_SCAN_RESULTS */ #endif /* __ZEPHYR_DISP_SCAN_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/inc/wifi_mgmt_scan.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
240
```objective-c /* * */ /** * @brief Header containing QSPI device interface specific declarations for the * Zephyr OS layer of the Wi-Fi driver. */ #ifndef __QSPI_IF_H__ #define __QSPI_IF_H__ #include <zephyr/kernel.h> #include <zephyr/drivers/gpio.h> #ifdef CONFIG_NRF70_ON_QSPI #include <nrfx_qspi.h> #endif #define RPU_WAKEUP_NOW BIT(0) /* WAKEUP RPU - RW */ #define RPU_AWAKE_BIT BIT(1) /* RPU AWAKE FROM SLEEP - RO */ #define RPU_READY_BIT BIT(2) /* RPU IS READY - RO*/ struct qspi_config { #ifdef CONFIG_NRF70_ON_QSPI nrf_qspi_addrmode_t addrmode; nrf_qspi_readoc_t readoc; nrf_qspi_writeoc_t writeoc; nrf_qspi_frequency_t sckfreq; #endif unsigned char RDC4IO; bool easydma; bool single_op; bool quad_spi; bool encryption; bool CMD_CNONCE; bool enc_enabled; struct k_sem lock; unsigned int addrmask; unsigned char qspi_slave_latency; #if defined(CONFIG_NRF70_ON_QSPI) && (NRF_QSPI_HAS_XIP_ENC || NRF_QSPI_HAS_DMA_ENC) nrf_qspi_encryption_t p_cfg; #endif /*CONFIG_NRF70_ON_QSPI && (NRF_QSPI_HAS_XIP_ENC || NRF_QSPI_HAS_DMA_ENC)*/ int test_hlread; char *test_name; int test_start; int test_end; int test_iterations; int test_timediff_read; int test_timediff_write; int test_status; int test_iteration; }; struct qspi_dev { int (*deinit)(void); void *config; int (*init)(struct qspi_config *config); int (*write)(unsigned int addr, const void *data, int len); int (*read)(unsigned int addr, void *data, int len); int (*hl_read)(unsigned int addr, void *data, int len); void (*hard_reset)(void); }; int qspi_cmd_wakeup_rpu(const struct device *dev, uint8_t data); int qspi_init(struct qspi_config *config); int qspi_write(unsigned int addr, const void *data, int len); int qspi_read(unsigned int addr, void *data, int len); int qspi_hl_read(unsigned int addr, void *data, int len); int qspi_deinit(void); void gpio_free_irq(int pin, struct gpio_callback *button_cb_data); int gpio_request_irq(int pin, struct gpio_callback *button_cb_data, void (*irq_handler)()); struct qspi_config *qspi_defconfig(void); struct qspi_dev *qspi_dev(void); struct qspi_config *qspi_get_config(void); int qspi_cmd_sleep_rpu(const struct device *dev); void hard_reset(void); void get_sleep_stats(uint32_t addr, uint32_t *buff, uint32_t wrd_len); extern struct device qspi_perip; int qspi_validate_rpu_wake_writecmd(const struct device *dev); int qspi_cmd_wakeup_rpu(const struct device *dev, uint8_t data); int qspi_wait_while_rpu_awake(const struct device *dev); int qspi_RDSR1(const struct device *dev, uint8_t *rdsr1); int qspi_RDSR2(const struct device *dev, uint8_t *rdsr2); int qspi_WRSR2(const struct device *dev, const uint8_t wrsr2); #ifdef CONFIG_NRF_WIFI_LOW_POWER int func_rpu_sleep(void); int func_rpu_wake(void); int func_rpu_sleep_status(void); #endif /* CONFIG_NRF_WIFI_LOW_POWER */ #define QSPI_KEY_LEN_BYTES 16 /*! \brief Enable encryption * * \param key Pointer to the 128-bit key * \return 0 on success, negative errno code on failure. */ int qspi_enable_encryption(uint8_t *key); #endif /* __QSPI_IF_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/src/qspi/inc/qspi_if.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
861
```objective-c /* * */ /** * @brief Header containing network stack interface specific declarations for * the Zephyr OS layer of the Wi-Fi driver. */ #ifndef __ZEPHYR_NET_IF_H__ #define __ZEPHYR_NET_IF_H__ #include <zephyr/device.h> #include <zephyr/net/net_pkt.h> #include <zephyr/net/net_if.h> #include <zephyr/net/ethernet.h> #include <fmac_structs.h> #include <zephyr/net/wifi_mgmt.h> #define UNICAST_MASK GENMASK(7, 1) #define LOCAL_BIT BIT(1) void nrf_wifi_if_init_zep(struct net_if *iface); int nrf_wifi_if_start_zep(const struct device *dev); int nrf_wifi_if_stop_zep(const struct device *dev); int nrf_wifi_if_set_config_zep(const struct device *dev, enum ethernet_config_type type, const struct ethernet_config *config); int nrf_wifi_if_get_config_zep(const struct device *dev, enum ethernet_config_type type, struct ethernet_config *config); enum ethernet_hw_caps nrf_wifi_if_caps_get(const struct device *dev); int nrf_wifi_if_send(const struct device *dev, struct net_pkt *pkt); void nrf_wifi_if_rx_frm(void *os_vif_ctx, void *frm); #if defined(CONFIG_NRF70_RAW_DATA_RX) || defined(CONFIG_NRF70_PROMISC_DATA_RX) void nrf_wifi_if_sniffer_rx_frm(void *os_vif_ctx, void *frm, struct raw_rx_pkt_header *raw_rx_hdr, bool pkt_free); #endif /* CONFIG_NRF70_RAW_DATA_RX || CONFIG_NRF70_PROMISC_DATA_RX */ enum nrf_wifi_status nrf_wifi_if_carr_state_chg(void *os_vif_ctx, enum nrf_wifi_fmac_if_carr_state carr_state); int nrf_wifi_stats_get(const struct device *dev, struct net_stats_wifi *stats); struct net_stats_eth *nrf_wifi_eth_stats_get(const struct device *dev); void nrf_wifi_set_iface_event_handler(void *os_vif_ctx, struct nrf_wifi_umac_event_set_interface *event, unsigned int event_len); #endif /* __ZEPHYR_NET_IF_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/inc/net_if.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
477
```objective-c /* * */ /** * @brief Header containing WiFi management operation implementations * for the Zephyr OS. */ #ifndef __ZEPHYR_WIFI_MGMT_H__ #define __ZEPHYR_WIFI_MGMT_H__ #include <math.h> #include <zephyr/device.h> #include <zephyr/net/wifi_mgmt.h> #include "osal_api.h" /** Filter setting defines for sniffer mode. */ #define WIFI_MGMT_DATA_CTRL_FILTER_SETTING 0xE #define WIFI_ALL_FILTER_SETTING 0xF struct twt_interval_float { unsigned short mantissa; unsigned char exponent; }; int nrf_wifi_set_power_save(const struct device *dev, struct wifi_ps_params *params); int nrf_wifi_set_twt(const struct device *dev, struct wifi_twt_params *twt_params); void nrf_wifi_event_proc_twt_setup_zep(void *vif_ctx, struct nrf_wifi_umac_cmd_config_twt *twt_setup_info, unsigned int event_len); void nrf_wifi_event_proc_twt_teardown_zep(void *vif_ctx, struct nrf_wifi_umac_cmd_teardown_twt *twt_teardown_info, unsigned int event_len); void nrf_wifi_event_proc_twt_sleep_zep(void *vif_ctx, struct nrf_wifi_umac_event_twt_sleep *twt_sleep_info, unsigned int event_len); int nrf_wifi_twt_teardown_flows(struct nrf_wifi_vif_ctx_zep *vif_ctx_zep, unsigned char start_flow_id, unsigned char end_flow_id); int nrf_wifi_get_power_save_config(const struct device *dev, struct wifi_ps_config *ps_config); void nrf_wifi_event_proc_get_power_save_info(void *vif_ctx, struct nrf_wifi_umac_event_power_save_info *ps_info, unsigned int event_len); #ifdef CONFIG_NRF70_SYSTEM_WITH_RAW_MODES int nrf_wifi_mode(const struct device *dev, struct wifi_mode_info *mode); #endif #if defined(CONFIG_NRF70_RAW_DATA_TX) || defined(CONFIG_NRF70_RAW_DATA_RX) int nrf_wifi_channel(const struct device *dev, struct wifi_channel_info *channel); #endif /* CONFIG_NRF70_RAW_DATA_TX || CONFIG_NRF70_RAW_DATA_RX */ #if defined(CONFIG_NRF70_RAW_DATA_RX) || defined(CONFIG_NRF70_PROMISC_DATA_RX) int nrf_wifi_filter(const struct device *dev, struct wifi_filter_info *filter); #endif /* CONFIG_NRF70_RAW_DATA_RX || CONFIG_NRF70_PROMISC_DATA_RX */ int nrf_wifi_set_rts_threshold(const struct device *dev, unsigned int rts_threshold); #endif /* __ZEPHYR_WIFI_MGMT_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/inc/wifi_mgmt.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
572
```objective-c /* * */ /** * @brief Header containing FMAC interface specific declarations for the * Zephyr OS layer of the Wi-Fi driver. */ #ifndef __ZEPHYR_FMAC_MAIN_H__ #define __ZEPHYR_FMAC_MAIN_H__ #include <stdio.h> #include <version.h> #include <zephyr/kernel.h> #include <zephyr/net/net_if.h> #ifndef CONFIG_NRF70_RADIO_TEST #include <zephyr/net/wifi_mgmt.h> #include <zephyr/net/ethernet.h> #ifdef CONFIG_NETWORKING #include <net_if.h> #endif /* CONFIG_NETWORKING */ #ifdef CONFIG_NRF70_STA_MODE #include <drivers/driver_zephyr.h> #endif /* CONFIG_NRF70_STA_MODE */ #endif /* !CONFIG_NRF70_RADIO_TEST */ #include <fmac_api.h> #include <host_rpu_umac_if.h> #define NRF70_DRIVER_VERSION "1."KERNEL_VERSION_STRING #ifndef CONFIG_NRF70_RADIO_TEST struct nrf_wifi_vif_ctx_zep { const struct device *zep_dev_ctx; struct net_if *zep_net_if_ctx; void *supp_drv_if_ctx; void *rpu_ctx_zep; unsigned char vif_idx; struct k_mutex vif_lock; scan_result_cb_t disp_scan_cb; bool scan_in_progress; int scan_type; uint16_t max_bss_cnt; unsigned int scan_res_cnt; struct k_work_delayable scan_timeout_work; struct net_eth_addr mac_addr; int if_type; char ifname[16]; enum nrf_wifi_fmac_if_op_state if_op_state; bool set_if_event_received; int set_if_status; #ifdef CONFIG_NET_STATISTICS_ETHERNET struct net_stats_eth eth_stats; #endif /* CONFIG_NET_STATISTICS_ETHERNET */ #ifdef CONFIG_NRF70_STA_MODE unsigned int assoc_freq; enum nrf_wifi_fmac_if_carr_state if_carr_state; struct wpa_signal_info *signal_info; struct wpa_conn_info *conn_info; struct zep_wpa_supp_dev_callbk_fns supp_callbk_fns; unsigned char twt_flows_map; unsigned char twt_flow_in_progress_map; struct wifi_ps_config *ps_info; bool ps_config_info_evnt; bool authorized; bool cookie_resp_received; #ifdef CONFIG_NRF70_DATA_TX struct k_work nrf_wifi_net_iface_work; #endif /* CONFIG_NRF70_DATA_TX */ unsigned long rssi_record_timestamp_us; signed short rssi; #endif /* CONFIG_NRF70_STA_MODE */ #ifdef CONFIG_NRF70_AP_MODE int inactive_time_sec; #endif /* CONFIG_NRF70_AP_MODE */ #ifdef CONFIG_NRF_WIFI_RPU_RECOVERY struct k_work nrf_wifi_rpu_recovery_work; #endif /* CONFIG_NRF_WIFI_RPU_RECOVERY */ }; struct nrf_wifi_vif_ctx_map { const char *ifname; struct nrf_wifi_vif_ctx_zep *vif_ctx; }; #endif /* !CONFIG_NRF70_RADIO_TEST */ struct nrf_wifi_ctx_zep { void *drv_priv_zep; void *rpu_ctx; #ifdef CONFIG_NRF70_RADIO_TEST struct rpu_conf_params conf_params; bool rf_test_run; unsigned char rf_test; #else /* CONFIG_NRF70_RADIO_TEST */ struct nrf_wifi_vif_ctx_zep vif_ctx_zep[MAX_NUM_VIFS]; #ifdef CONFIG_NRF70_UTIL struct rpu_conf_params conf_params; #endif /* CONFIG_NRF70_UTIL */ #endif /* CONFIG_NRF70_RADIO_TEST */ unsigned char *extended_capa, *extended_capa_mask; unsigned int extended_capa_len; struct k_mutex rpu_lock; }; struct nrf_wifi_drv_priv_zep { struct nrf_wifi_fmac_priv *fmac_priv; /* TODO: Replace with a linked list to handle unlimited RPUs */ struct nrf_wifi_ctx_zep rpu_ctx_zep; }; extern struct nrf_wifi_drv_priv_zep rpu_drv_priv_zep; void nrf_wifi_scan_timeout_work(struct k_work *work); void configure_tx_pwr_settings(struct nrf_wifi_tx_pwr_ctrl_params *tx_pwr_ctrl_params, struct nrf_wifi_tx_pwr_ceil_params *tx_pwr_ceil_params); void configure_board_dep_params(struct nrf_wifi_board_params *board_params); void set_tx_pwr_ceil_default(struct nrf_wifi_tx_pwr_ceil_params *pwr_ceil_params); const char *nrf_wifi_get_drv_version(void); enum nrf_wifi_status nrf_wifi_fmac_dev_add_zep(struct nrf_wifi_drv_priv_zep *drv_priv_zep); enum nrf_wifi_status nrf_wifi_fmac_dev_rem_zep(struct nrf_wifi_drv_priv_zep *drv_priv_zep); enum nrf_wifi_status nrf_wifi_fw_load(void *rpu_ctx); struct nrf_wifi_vif_ctx_zep *nrf_wifi_get_vif_ctx(struct net_if *iface); void nrf_wifi_rpu_recovery_cb(void *vif_ctx, void *event_data, unsigned int event_len); #endif /* __ZEPHYR_FMAC_MAIN_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/inc/fmac_main.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,056
```objective-c /* * */ /** * @brief Header containing WPA supplicant interface specific declarations for * the Zephyr OS layer of the Wi-Fi driver. */ #ifndef __ZEPHYR_WPA_SUPP_IF_H__ #define __ZEPHYR_WPA_SUPP_IF_H__ #define RPU_RESP_EVENT_TIMEOUT 5000 #ifdef CONFIG_NRF70_STA_MODE #include <drivers/driver_zephyr.h> void *nrf_wifi_wpa_supp_dev_init(void *supp_drv_if_ctx, const char *iface_name, struct zep_wpa_supp_dev_callbk_fns *supp_callbk_fns); void nrf_wifi_wpa_supp_dev_deinit(void *if_priv); int nrf_wifi_wpa_supp_scan2(void *if_priv, struct wpa_driver_scan_params *params); int nrf_wifi_wpa_supp_scan_abort(void *if_priv); int nrf_wifi_wpa_supp_scan_results_get(void *if_priv); int nrf_wifi_wpa_supp_deauthenticate(void *if_priv, const char *addr, unsigned short reason_code); int nrf_wifi_wpa_supp_authenticate(void *if_priv, struct wpa_driver_auth_params *params, struct wpa_bss *curr_bss); int nrf_wifi_wpa_supp_associate(void *if_priv, struct wpa_driver_associate_params *params); int nrf_wifi_wpa_set_supp_port(void *if_priv, int authorized, char *bssid); int nrf_wifi_wpa_supp_signal_poll(void *if_priv, struct wpa_signal_info *si, unsigned char *bssid); int nrf_wifi_nl80211_send_mlme(void *if_priv, const u8 *data, size_t data_len, int noack, unsigned int freq, int no_cck, int offchanok, unsigned int wait_time, int cookie); int nrf_wifi_supp_get_wiphy(void *if_priv); int nrf_wifi_supp_register_frame(void *if_priv, u16 type, const u8 *match, size_t match_len, bool multicast); int nrf_wifi_wpa_supp_set_key(void *if_priv, const unsigned char *ifname, enum wpa_alg alg, const unsigned char *addr, int key_idx, int set_tx, const unsigned char *seq, size_t seq_len, const unsigned char *key, size_t key_len, enum key_flag key_flag); void nrf_wifi_wpa_supp_event_proc_scan_start(void *if_priv); void nrf_wifi_wpa_supp_event_proc_scan_done(void *if_priv, struct nrf_wifi_umac_event_trigger_scan *scan_done_event, unsigned int event_len, int aborted); void nrf_wifi_wpa_supp_event_proc_scan_res(void *if_priv, struct nrf_wifi_umac_event_new_scan_results *scan_res, unsigned int event_len, bool more_res); void nrf_wifi_wpa_supp_event_proc_auth_resp(void *if_priv, struct nrf_wifi_umac_event_mlme *auth_resp, unsigned int event_len); void nrf_wifi_wpa_supp_event_proc_assoc_resp(void *if_priv, struct nrf_wifi_umac_event_mlme *assoc_resp, unsigned int event_len); void nrf_wifi_wpa_supp_event_proc_deauth(void *if_priv, struct nrf_wifi_umac_event_mlme *deauth, unsigned int event_len); void nrf_wifi_wpa_supp_event_proc_disassoc(void *if_priv, struct nrf_wifi_umac_event_mlme *disassoc, unsigned int event_len); void nrf_wifi_wpa_supp_event_proc_get_sta(void *if_priv, struct nrf_wifi_umac_event_new_station *info, unsigned int event_len); void nrf_wifi_wpa_supp_event_proc_get_if(void *if_priv, struct nrf_wifi_interface_info *info, unsigned int event_len); void nrf_wifi_wpa_supp_event_mgmt_tx_status(void *if_priv, struct nrf_wifi_umac_event_mlme *mlme_event, unsigned int event_len); void nrf_wifi_wpa_supp_event_proc_unprot_mgmt(void *if_priv, struct nrf_wifi_umac_event_mlme *unprot_mgmt, unsigned int event_len); void nrf_wifi_wpa_supp_event_get_wiphy(void *if_priv, struct nrf_wifi_event_get_wiphy *get_wiphy, unsigned int event_len); void nrf_wifi_wpa_supp_event_mgmt_rx_callbk_fn(void *if_priv, struct nrf_wifi_umac_event_mlme *mgmt_rx_event, unsigned int event_len); int nrf_wifi_supp_get_capa(void *if_priv, struct wpa_driver_capa *capa); void nrf_wifi_wpa_supp_event_mac_chgd(void *if_priv); int nrf_wifi_supp_get_conn_info(void *if_priv, struct wpa_conn_info *info); void nrf_wifi_supp_event_proc_get_conn_info(void *os_vif_ctx, struct nrf_wifi_umac_event_conn_info *info, unsigned int event_len); #endif /* CONFIG_NRF70_STA_MODE */ #ifdef CONFIG_NRF70_AP_MODE int nrf_wifi_wpa_supp_init_ap(void *if_priv, struct wpa_driver_associate_params *params); int nrf_wifi_wpa_supp_start_ap(void *if_priv, struct wpa_driver_ap_params *params); int nrf_wifi_wpa_supp_change_beacon(void *if_priv, struct wpa_driver_ap_params *params); int nrf_wifi_wpa_supp_stop_ap(void *if_priv); int nrf_wifi_wpa_supp_deinit_ap(void *if_priv); int nrf_wifi_wpa_supp_sta_add(void *if_priv, struct hostapd_sta_add_params *params); int nrf_wifi_wpa_supp_sta_remove(void *if_priv, const u8 *addr); int nrf_wifi_supp_register_mgmt_frame(void *if_priv, u16 frame_type, size_t match_len, const u8 *match); int nrf_wifi_wpa_supp_sta_set_flags(void *if_priv, const u8 *addr, unsigned int total_flags, unsigned int flags_or, unsigned int flags_and); int nrf_wifi_wpa_supp_sta_get_inact_sec(void *if_priv, const u8 *addr); #endif /* CONFIG_NRF70_AP_MODE */ #endif /* __ZEPHYR_WPA_SUPP_IF_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/inc/wpa_supp_if.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,343
```objective-c /** * */ /** * @brief Structures and related enumerations used in Coexistence. */ #ifndef __COEX_STRUCT_H__ #define __COEX_STRUCT_H__ #include <stdint.h> #include <stdbool.h> /* Max size of message buffer (exchanged between host and MAC). This is in "bytes" */ #define MAX_MESSAGE_BUF_SIZE 320 /* Number of elements in coex_ch_configuration other than configbuf[] */ #define NUM_ELEMENTS_EXCL_CONFIGBUF 4 /* Each configuration value is of type uint32_t */ #define MAX_NUM_CONFIG_VALUES ((MAX_MESSAGE_BUF_SIZE-\ (NUM_ELEMENTS_EXCL_CONFIGBUF*sizeof(uint32_t)))>>2) /* Number of elements in coex_sr_traffic_info other than sr_traffic_info[] */ #define NUM_ELEMENTS_EXCL_SRINFOBUF 1 /* Each SR Traffic Info is of type uint32_t */ #define MAX_SR_TRAFFIC_BUF_SIZE 32 enum { /** Used two different values for AGGREGATION module because offset from base is * beyond supported message buffer size for WAIT_STATE_1_TIME register */ COEX_HARDWARE = 1, MAC_CTRL, MAC_CTRL_AGG_WAIT_STATE_1_TIME, MAC_CTRL_AGG, MAC_CTRL_DEAGG, WLAN_CTRL, }; /* IDs of different messages posted from Coexistence Driver to Coexistence Manager */ enum { /* To insturct Coexistence Manager to collect and post SR traffic information */ COLLECT_SR_TRAFFIC_INFO = 1, /* To insturct Coexistence Manager to allocate a priority window to SR */ ALLOCATE_PTI_WINDOW, /* To do configuration of hardware related to coexistence */ HW_CONFIGURATION, /* To start allocating periodic priority windows to Wi-Fi and SR */ ALLOCATE_PPW, /* To start allocating virtual priority windows to Wi-Fi */ ALLOCATE_VPW, /* To configure CM SW parameters */ SW_CONFIGURATION, /* To control sheliak side switch */ UPDATE_SWITCH_CONFIG }; /* ID(s) of different messages posted from Coexistence Manager to Coexistence Driver */ enum { /* To post SR traffic information */ SR_TRAFFIC_INFO = 1 }; /** * struct coex_collect_sr_traffic_info - Message from CD to CM to request SR traffic info. * @message_id: Indicates message ID. This is to be set to COLLECT_SR_TRAFFIC_INFO. * @num_sets_requested: Indicates the number of sets of duration and periodicity to be collected. * * Message from CD to CM to request SR traffic information. */ struct coex_collect_sr_traffic_info { uint32_t message_id; uint32_t num_sets_requested; }; /** * struct coex_ch_configuration -Message from CD to CM to configure CH. * @message_id: Indicates message ID. This is to be set to HW_CONFIGURATION. * @num_reg_to_config: Indicates the number of registers to be configured. * @hw_to_config: Indicates the hardware block that is to be configured. * @hw_block_base_addr: Base address of the hardware block to be configured. * @configbuf: Configuration buffer that holds packed offset and configuration value. * * Message from CD to CM to configure CH */ struct coex_ch_configuration { uint32_t message_id; uint32_t num_reg_to_config; uint32_t hw_to_config; uint32_t hw_block_base_addr; uint32_t configbuf[MAX_NUM_CONFIG_VALUES]; }; /** * struct coex_allocate_pti_window - Message to CM to request a priority window. * @message_id: Indicates message ID. This is to be set to ALLOCATE_PTI_WINDOW. * @device_req_window: Indicates device requesting a priority window. * @window_start_or_end: Indicates if request is posted to START or END a priority window. * @imp_of_request: Indicates importance of activity for which the window is requested. * @can_be_deferred: activity of Wi-Fi/SR, for which window is requested can be deferred or not. * * Message to CM to request a priority window */ struct coex_allocate_pti_window { uint32_t message_id; uint32_t device_req_window; uint32_t window_start_or_end; uint32_t imp_of_request; uint32_t can_be_deferred; }; /** * struct coex_allocate_ppw - Message from CD to CM to allocate Periodic Priority Windows. * @message_id: Indicates message ID. This is to be set to ALLOCATE_PPW. * @start_or_stop: Indiates start or stop allocation of PPWs. * @first_pti_window: Indicates first priority window in the series of PPWs. * @ps_mechanism: Indicates recommended powersave mechanism for Wi-Fi's downlink. * @wifi_window_duration: Indicates duration of Wi-Fi priority window. * @sr_window_duration: Indicates duration of SR priority window. * * Message from CD to CM to allocate Periodic Priority Windows. */ struct coex_allocate_ppw { uint32_t message_id; uint32_t start_or_stop; uint32_t first_pti_window; uint32_t ps_mechanism; uint32_t wifi_window_duration; uint32_t sr_window_duration; }; /** * struct coex_allocate_vpw - Message from CD to CM to allocate Virtual Priority Windows. * @message_id: Indicates message ID. This is to be set to ALLOCATE_VPW. * @start_or_stop: Indicates start or stop allocation of VPWs. * @wifi_window_duration: Indicates duration of Wi-Fi virtual priority window. * @ps_mechanism: Indicates recommended powersave mechanism for Wi-Fi's downlink. * * Message from CD to CM to allocate Virtual Priority Windows. */ struct coex_allocate_vpw { uint32_t message_id; uint32_t start_or_stop; uint32_t wifi_window_duration; uint32_t ps_mechanism; }; /** * struct coex_config_cm_params - Message from CD to CM to configure CM parameters * @message_id: Indicates message ID. This is to be set to SW_CONFIGURATION. * @first_isr_trigger_period: microseconds . used to trigger the ISR mechanism. * @sr_window_poll_periodicity_vpw: microseconds. This is used to poll through SR window. * that comes after Wi-Fi window ends and next SR activity starts, in the case of VPWs. * @lead_time_from_end_of_wlan_win: microseconds. Lead time from the end of Wi-Fi window. * (to inform AP that Wi-Fi is entering powersave) in the case of PPW and VPW generation. * @sr_window_poll_count_threshold: This is equal to "Wi-Fi contention timeout. * threshold"/sr_window_poll_periodicity_vpw. * * Message from CD to CM to configure CM parameters. */ struct coex_config_cm_params { uint32_t message_id; uint32_t first_isr_trigger_period; uint32_t sr_window_poll_periodicity_vpw; uint32_t lead_time_from_end_of_wlan_win; uint32_t sr_window_poll_count_threshold; }; /** * struct coex_sr_traffic_info - Message from CM to CD to post SR traffic information. * @message_id: Indicates message ID. This is to be set to SR_TRAFFIC_INFO. * @sr_traffic_info: Traffic information buffer. * * Message from CM to CD to post SR traffic inforamtion */ struct coex_sr_traffic_info { uint32_t message_id; uint32_t sr_traffic_info[MAX_SR_TRAFFIC_BUF_SIZE]; }; #endif /* __COEX_STRUCT_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/inc/coex_struct.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,574
```objective-c /* * */ /** * @brief Header containing Coexistence APIs. */ #ifndef __COEX_H__ #define __COEX_H__ #include <stdbool.h> /* Indicates WLAN frequency band of operation */ enum nrf_wifi_pta_wlan_op_band { NRF_WIFI_PTA_WLAN_OP_BAND_2_4_GHZ = 0, NRF_WIFI_PTA_WLAN_OP_BAND_5_GHZ, NRF_WIFI_PTA_WLAN_OP_BAND_NONE = 0xFF }; /** * @function nrf_wifi_coex_config_pta(enum nrf_wifi_pta_wlan_op_band wlan_band, * bool separate_antennas, bool is_sr_protocol_ble) * * @brief Function used to configure PTA tables of coexistence hardware. * * @param[in] enum nrf_wifi_pta_wlan_op_band wlan_band * @param[in] separate_antennas * Indicates whether separate antenans are used or not. * @param[in] is_sr_protocol_ble * Indicates if SR protocol is Bluetooth LE or not. * @return Returns status of configuration. * Returns zero upon successful configuration. * Returns non-zero upon unsuccessful configuration. */ int nrf_wifi_coex_config_pta(enum nrf_wifi_pta_wlan_op_band wlan_band, bool separate_antennas, bool is_sr_protocol_ble); #if defined(CONFIG_NRF70_SR_COEX_RF_SWITCH) || defined(__DOXYGEN__) /** * @function nrf_wifi_config_sr_switch(bool separate_antennas) * * @brief Function used to configure SR side switch (nRF5340 side switch in nRF7002 DK). * * @param[in] separate_antennas * Indicates whether separate antenans are used or not. * * @return Returns status of configuration. * Returns zero upon successful configuration. * Returns non-zero upon unsuccessful configuration. */ int nrf_wifi_config_sr_switch(bool separate_antennas); #endif /* CONFIG_NRF70_SR_COEX_RF_SWITCH */ /** * @function nrf_wifi_coex_config_non_pta(bool separate_antennas) * * @brief Function used to configure non-PTA registers of coexistence hardware. * * @param[in] separate_antennas * Indicates whether separate antenans are used or not. * @param[in] is_sr_protocol_ble * Indicates if SR protocol is Bluetooth LE or not. * * @return Returns status of configuration. * Returns zero upon successful configuration. * Returns non-zero upon unsuccessful configuration. */ int nrf_wifi_coex_config_non_pta(bool separate_antennas, bool is_sr_protocol_ble); /** * @function nrf_wifi_coex_hw_reset(void) * * @brief Function used to reset coexistence hardware. * * @return Returns status of configuration. * Returns zero upon successful configuration. * Returns non-zero upon unsuccessful configuration. */ int nrf_wifi_coex_hw_reset(void); #endif /* __COEX_H__ */ ```
/content/code_sandbox/drivers/wifi/nrfwifi/inc/coex.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
635
```c /** * * @file nxp_wifi_shell.c * Wi-Fi driver shell adapter layer */ #include <zephyr/kernel.h> #include <zephyr/shell/shell.h> #include "nxp_wifi_drv.h" static struct nxp_wifi_dev *nxp_wifi; void nxp_wifi_shell_register(struct nxp_wifi_dev *dev) { /* only one instance supported */ if (nxp_wifi) { return; } nxp_wifi = dev; } static int nxp_wifi_shell_cmd(const struct shell *sh, size_t argc, char **argv) { if (nxp_wifi == NULL) { shell_print(sh, "no nxp_wifi device registered"); return -ENOEXEC; } if (argc < 2) { shell_help(sh); return -ENOEXEC; } k_mutex_lock(&nxp_wifi->mutex, K_FOREVER); nxp_wifi_request(argc, argv); k_mutex_unlock(&nxp_wifi->mutex); return 0; } SHELL_CMD_ARG_REGISTER(nxp_wifi, NULL, "NXP Wi-Fi commands (Use help)", nxp_wifi_shell_cmd, 2, CONFIG_SHELL_ARGC_MAX); ```
/content/code_sandbox/drivers/wifi/nxp/nxp_wifi_shell.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
250
```unknown menuconfig WIFI_NXP bool "NXP Wi-Fi driver support" select NET_L2_WIFI_MGMT if NETWORKING select WIFI_USE_NATIVE_NETWORKING if NETWORKING select NET_L2_ETHERNET_MGMT if NETWORKING && NET_L2_ETHERNET select SDHC if !SOC_SERIES_RW6XX select SDIO_STACK if !SOC_SERIES_RW6XX select WIFI_NM if WIFI_NM_WPA_SUPPLICANT depends on DT_HAS_NXP_WIFI_ENABLED help Enable NXP SoC Wi-Fi support. if WIFI_NXP module = WIFI_NXP config WIFI_MGMT_SCAN_CHAN_MAX_MANUAL default 50 config NXP_WIFI_CUSTOM bool "Custom NXP Wi-Fi part" help Customize NXP Wi-Fi chip support. choice NXP_WIFI_PART prompt "Select NXP Wi-Fi part" depends on !NXP_WIFI_CUSTOM help Choose NXP Wi-Fi chip support. config NXP_RW610 bool "NXP RW610-based Chipset" depends on SOC_SERIES_RW6XX select NXP_FW_LOADER select NXP_RF_IMU help Select this option if you have a NXP RW610-based Wireless chip. This option will enable support for NXP RW610-based series boards. config NXP_88W8987 bool "NXP 88W8987 [EXPERIMENTAL]" select EXPERIMENTAL help Enable NXP 88W8987 Wi-Fi connectivity, More information about 88W8987 device you can find on path_to_url config NXP_IW416 bool "NXP IW416 [EXPERIMENTAL]" select EXPERIMENTAL help Enable NXP IW416 Wi-Fi connectivity, More information about IW416 device you can find on path_to_url config NXP_IW61X bool "NXP IW61X [EXPERIMENTAL]" select EXPERIMENTAL help Enable NXP IW61X Wi-Fi connectivity, More information about IW61X device you can find on path_to_url path_to_url config NXP_88W8801 bool "NXP 88W8801 [EXPERIMENTAL]" select EXPERIMENTAL help Enable NXP 88W8801 Wi-Fi connectivity, More information about 88W8801 device you can find on path_to_url endchoice choice NXP_88W8987_MODULE prompt "Select NXP 88W8987 module" depends on NXP_88W8987 && !NXP_WIFI_CUSTOM config NXP_88W8987_AW_CM358_USD bool "NXP AW-CM358-USD" help Azurewave Type CM358 module based on NXP 88W8987 combo LGA chipset which supports which supports Wi-Fi 802.11a/b/g/n/ac + Bluetooth 5.1 BR/EDR/LE up to 433Mbps PHY data rate on Wi-Fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Azurewave Type AW CM358 module you can find on path_to_url config NXP_88W8987_AW_CM358MA_M2 bool "NXP AW-CM358MA-M2" help Azurewave Type CM358MA module based on NXP 88W8987 combo LGA chipset which supports which supports Wi-Fi 802.11a/b/g/n/ac + Bluetooth 5.1 BR/EDR/LE up to 433Mbps PHY data rate on Wi-Fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Murata Type AW CM358MA module you can find on path_to_url config NXP_88W8987_MURATA_1ZM_USD bool "NXP MURATA-1ZM-USD" help Murata Type 1ZM is a small and very high performance module based on NXP 88W8987 combo chipset which supports Wi-Fi 802.11a/b/g/n/ac + Bluetooth 5.1 BR/EDR/LE up to 433Mbps PHY data rate on Wi-Fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Murata Type 1ZM module you can find on path_to_url path_to_url config NXP_88W8987_MURATA_1ZM_M2 bool "NXP MURATA-1ZM-M2" help Murata Type 1ZM is a small and very high performance module based on NXP 88W8987 combo chipset which supports Wi-Fi 802.11a/b/g/n/ac + Bluetooth 5.1 BR/EDR/LE up to 433Mbps PHY data rate on Wi-Fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Murata Type 1ZM module you can find on path_to_url endchoice choice NXP_IW416_MODULE prompt "Select NXP IW416 module" depends on NXP_IW416 && !NXP_WIFI_CUSTOM config NXP_IW416_AW_AM457_USD bool "NXP IW416-AW-AM457-USD" help Azurewave Type AM457 is a small and high performance module based on NXP IW416 combo chipset which supports Wi-Fi 802.11a/b/g/n + Bluetooth 5.2 BR/EDR/LE up to 150 Mbps PHY data rate on Wi-Fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Type AW AM457 module you can find on path_to_url config NXP_IW416_AW_AM457MA_M2 bool "NXP IW416-AW-AM457MA-M2" help Azurewave Type AM457MA is a small and high performance module based on NXP IW416 combo chipset which supports Wi-Fi 802.11a/b/g/n + Bluetooth 5.2 BR/EDR/LE up to 150 Mbps PHY data rate on Wi-Fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Type AW AM457MA module you can find on path_to_url config NXP_IW416_AW_AM510_USD bool "NXP IW416-AW-AM510-USD" help Azurewave Type AM510 is a small and high performance module based on NXP IW416 combo chipset which supports Wi-Fi 802.11a/b/g/n + Bluetooth 5.2 BR/EDR/LE up to 150 Mbps PHY data rate on Wi-Fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Type AW AM510 module you can find on path_to_url config NXP_IW416_AW_AM510MA_M2 bool "NXP IW416-AW-AM510MA-M2" help Azurewave Type AM510MA is a small and high performance module based on NXP IW416 combo chipset which supports Wi-Fi 802.11a/b/g/n + Bluetooth 5.2 BR/EDR/LE up to 150 Mbps PHY data rate on Wi-Fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Type AW AM510MA module you can find on path_to_url config NXP_IW416_MURATA_1XK_USD bool "NXP IW416-MURATA-1XK-USD" help Murata Type 1XK is a small and high performance module based on NXP IW416 combo chipset which supports Wi-Fi 802.11a/b/g/n + Bluetooth 5.2 BR/EDR/LE up to 150 Mbps PHY data rate on Wi-Fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Type 1XK module you can find on path_to_url path_to_url config NXP_IW416_MURATA_1XK_M2 bool "NXP IW416-MURATA-1XK-M2" help Murata Type 1XK is a small and high performance module based on NXP IW416 combo chipset which supports Wi-Fi 802.11a/b/g/n + Bluetooth 5.2 BR/EDR/LE up to 150 Mbps PHY data rate on Wi-Fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Type 1XK module you can find on path_to_url endchoice choice NXP_IW61X_MODULE prompt "Select NXP IW61X module" depends on NXP_IW61X && !NXP_WIFI_CUSTOM config NXP_IW612_MURATA_2EL_USD bool "NXP IW612-MURATA-2EL-USD" help Murata Type 2EL is a small and very high performance module based on NXP IW612 combo chipset which supports Wi-Fi 802.11a/b/g/n/ac/ax + Bluetooth 5.3 BR/EDR/LE + 802.15.4 up to 601Mbps PHY data rate on Wi-fi and 2Mbps PHY data rate on Bluetooth. Detailed information about Type 2EL module you can find on path_to_url path_to_url config NXP_IW612_MURATA_2EL_M2 bool "NXP IW612-MURATA-2EL-M2" help Murata Type 2EL is a small and very high performance module based on NXP IW612 combo chipset which supports Wi-Fi 802.11a/b/g/n/ac/ax + Bluetooth 5.3 BR/EDR/LE + 802.15.4 up to 601Mbps PHY data rate on Wi-fi and 2Mbps PHY data rate on Bluetooth. Detailed information about Type 2EL module you can find on path_to_url config NXP_IW611_MURATA_2DL_USD bool "NXP IW611-MURATA-2DL-USD" help Murata Type 2DL is a small and very high performance module based on NXP IW611 combo chipset which supports Wi-Fi 802.11a/b/g/n/ac/ax + Bluetooth 5.3 BR/EDR/LE up to 601Mbps PHY data rate on Wi-fi and 2Mbps PHY data rate on Bluetooth. Detailed information about Type 2DL module you can find on path_to_url path_to_url config NXP_IW611_MURATA_2DL_M2 bool "NXP IW611-MURATA-2DL-M2" help Murata Type 2DL is a small and very high performance module based on NXP IW611 combo chipset which supports Wi-Fi 802.11a/b/g/n/ac/ax + Bluetooth 5.3 BR/EDR/LE up to 601Mbps PHY data rate on Wi-fi and 2Mbps PHY data rate on Bluetooth. Detailed information about Type 2DL module you can find on path_to_url endchoice choice NXP_88W8801_MODULE prompt "Select NXP 88W8801 module" depends on NXP_88W8801 && !NXP_WIFI_CUSTOM config NXP_88W8801_AW_NM191_USD bool "NXP AW-NM191-USD" help Azurewave Type NM191 is a small high-performance module (integrated PCB antenna) based on NXP 88W8801 chipset which supports Wi-Fi 802.11b/g/n up to 72.2 Mbps PHY data rate. Detailed information about Murata Type AW NM191 module you can find on path_to_url config NXP_88W8801_AW_NM191MA_M2 bool "NXP AW-NM191MA-M2" help Azurewave Type NM191MA is a small high-performance module (integrated PCB antenna) based on NXP 88W8801 chipset which supports Wi-Fi 802.11b/g/n up to 72.2 Mbps PHY data rate. Detailed information about Murata Type AW NM191MA module you can find on path_to_url config NXP_88W8801_MURATA_2DS_USD bool "NXP MURATA-2DS-USD" help Murata Type 2DS is a small high-performance module (integrated PCB antenna) based on NXP 88W8801 chipset which supports Wi-Fi 802.11b/g/n up to 72.2 Mbps PHY data rate. Detailed information about Murata Type 2DS module you can find on path_to_url path_to_url config NXP_88W8801_MURATA_2DS_USD bool "NXP MURATA-2DS-M2" help Murata Type 2DS is a small high-performance module (integrated PCB antenna) based on NXP 88W8801 chipset which supports Wi-Fi 802.11b/g/n up to 72.2 Mbps PHY data rate. Detailed information about Murata Type 2DS module you can find on path_to_url endchoice config NXP_WIFI_SHELL bool "NXP Wi-Fi shell" depends on SHELL help NXP Wi-Fi shell commands support. menu "Wi-Fi driver Stack configurations" config NXP_WIFI_MON_TASK_STACK_SIZE int "Mon thread stack size" default 1152 help This option specifies the size of the stack used by the mon task. config NXP_WIFI_WLCMGR_TASK_STACK_SIZE int "Wlcmgr thread stack size" default 5120 help This option specifies the size of the stack used by the wlcmgr task. config NXP_WIFI_POWERSAVE_TASK_STACK_SIZE int "Wifi powersave task stack size" default 512 help This option specifies the size of the stack used by the wifi powersave task. config NXP_WIFI_TX_TASK_STACK_SIZE int "Wifi driver TX task stack size" default 2048 depends on NXP_WIFI_WMM help This option specifies the size of the stack used by the wifi driver TX task. config NXP_WIFI_DRIVER_TASK_STACK_SIZE int "Wifi driver task stack size" default 2048 help This option specifies the size of the stack used by the wifi driver task. config NXP_WIFI_SCAN_TASK_STACK_SIZE int "Wifi scan task stack size" default 2048 help This option specifies the size of the stack used by the wifi scan task. endmenu menu "Wi-Fi Station Support" config NXP_WIFI_STA_AUTO_CONN bool "Automatically starts STA connection" default n help This option enables Station auto connection support. if NXP_WIFI_STA_AUTO_CONN config NXP_WIFI_STA_AUTO_SSID string "NXP Wi-Fi STA auto connect SSID" depends on NXP_WIFI_STA_AUTO_CONN default "myssid" help This option specifies the SSID of the external Access Point for auto connection. Maximum length is 32 ascii characters. config NXP_WIFI_STA_AUTO_PASSWORD string "NXP Wi-Fi STA auto connect password" depends on NXP_WIFI_STA_AUTO_CONN default "" help This option specifies the Passphrase of the external Access Point for auto connection. Only support PSK security or open security by default. Length range 8 - 64, or 0 for open security. endif config NXP_WIFI_STA_RECONNECT bool "Automatically starts STA Reconnection" default y help This option enables Station auto reconnection support, when disconnected from current associated Access Point. config NXP_WIFI_AUTO_POWER_SAVE bool "Automatically starts Power Save support" default y help WiFi driver will automatically initiate power save when initialized. menu "Wi-Fi Scan Support" config NXP_WIFI_EXT_SCAN_SUPPORT bool "Extended Scan Support" default y depends on !NXP_88W8801 help This option enables the use of extended scan support. config NXP_WIFI_SCAN_WITH_RSSIFILTER bool "Scan with rssi filter" default y help This option enables rssi threshold support in the Wi-Fi driver. config NXP_WIFI_MAX_AP_ENTRIES int "Maximum scan entries" range 1 30 default 10 help This is the maximum number of entries in the list of APs stored by wifi driver. Each entry takes about 400 bytes of RAM. The value should be decided based on number of APs expected to be present in the end user environment. Note that the wifi driver automatically keeps only the highest signal strength APs in the list. config NXP_WIFI_SCAN_CHANNEL_GAP int "Max scan channel gap" default 1 help This option sets the max scan channel gap time between two scan commands. endmenu config NXP_WIFI_WMM_UAPSD bool "UAPSD mode" default y help This option enables WMM UAPSD in the Wi-Fi driver. config NXP_WIFI_ROAMING bool "Wi-Fi Soft Roaming" default y help This option enables Soft Roaming support in the Wi-Fi driver. config NXP_WIFI_CLOUD_KEEP_ALIVE bool "Cloud Keep Alive" help This option enables Cloud Keep Alive support in the Wi-Fi driver. config NXP_WIFI_11K bool "802.11K Support" default y help This option enables the use of 802.11k support. config NXP_WIFI_11V bool "802.11V Support" default y help This option enables the use of 802.11v support. config NXP_WIFI_11R bool "802.11R Support" default y depends on NXP_88W8987 || NXP_IW416 || NXP_RW610 || NXP_WIFI_CUSTOM help This option enables the use of 802.11r support. config NXP_WIFI_INACTIVITY_TIMEOUT_EXT bool "Inactivity Timeout Ext Support" default y help This option enables the use of Inactivity Timeout Ext support. endmenu config NXP_WIFI_MAX_PRIO int default 1 help This option sets Wi-Fi max priority in the Wi-Fi driver. config NXP_WIFI_SOFTAP_SUPPORT bool "Wi-Fi SoftAP Support" select NET_DHCPV4_SERVER select WIFI_NM_WPA_SUPPLICANT_AP if WIFI_NM_WPA_SUPPLICANT default y help Option to enable Wi-Fi SoftAP functions in the Wi-Fi driver. if NXP_WIFI_SOFTAP_SUPPORT config NXP_WIFI_SOFTAP_IP_ADDRESS string "NXP SoftAP mode IP Address" default "192.168.10.1" config NXP_WIFI_SOFTAP_IP_GATEWAY string "Gateway Address" default "192.168.10.1" config NXP_WIFI_SOFTAP_IP_MASK string "Network Mask" default "255.255.255.0" config NXP_WIFI_SOFTAP_IP_BASE string "NXP SoftAP base address" default "192.168.10.2" config NXP_WIFI_CAPA bool "Wi-Fi Soft AP Capability" default y help This option enables uAP Wi-Fi Capability in the Wi-Fi driver. config NXP_WIFI_UAP_STA_MAC_ADDR_FILTER bool "Wi-Fi SoftAP clients white/black list" default y help Allow/Block MAC addresses specified in the allowed list. config NXP_WIFI_UAP_WORKAROUND_STICKY_TIM bool "Sticky Tim" default y help This config enables the workaround of a particular firmware issue which causes packets being sent on air even if STA is in IEEE PS. When enabled this will enable the sticky TIM bit workaround. A downside of this is that the STA client of the uAP will not be able to go in IEEE PS. endif menu "Wi-Fi SDIO Multi Port Aggregation" config NXP_WIFI_SDIO_MULTI_PORT_RX_AGGR bool "SDIO Multiport Rx Aggregation" default y if !SOC_SERIES_RW6XX help This option enables SDIO Multiport Rx Aggregation support in the Wi-Fi driver. config NXP_WIFI_SDIO_MULTI_PORT_TX_AGGR bool "SDIO Multiport Tx Aggregation" default y if !SOC_SERIES_RW6XX depends on NXP_WIFI_WMM help This option enables SDIO Multiport Rx Aggregation support in the Wi-Fi driver. endmenu config NXP_WIFI_11AX bool "802.11AX Support" default y select NXP_WIFI_11AC select NXP_WIFI_WMM depends on NXP_RW610 || NXP_IW61X || NXP_WIFI_CUSTOM help This option enables the use of 802.11ax support. config NXP_WIFI_11AC bool "802.11AC Support" default y select NXP_WIFI_WMM depends on NXP_RW610 || NXP_IW61X || NXP_88W8987 || NXP_WIFI_CUSTOM help This option enables the use of 802.11ac support. config NXP_WIFI_WMM bool "802.11 WMM Support" default y help This option enables the use of 802.11 WMM support. config NXP_WIFI_TURBO_MODE bool "Turbo Mode" default y depends on NXP_WIFI_WMM depends on !NXP_88W8801 help This option enables WMM Turbo Mode support in the Wi-Fi driver. config NXP_WIFI_IPV6 bool "IPv6 Support" default y depends on NET_IPV6 help This option enables the use of IPv6 support. config NXP_WIFI_5GHz_SUPPORT bool "5GHz Support(Band A)" default y depends on !NXP_88W8801 help This option enables the use of 5GHz. config NXP_WIFI_TX_RX_ZERO_COPY bool "Zero memory copy TX/RX data packets" default y if NXP_RW610 imply NET_IPV4_FRAGMENT help This option enables the Zero memory copy of data packets in Wi-Fi driver data path. config NXP_WIFI_GET_LOG bool "Get 802.11 log" default y help This option gets 802.11 log in the Wi-Fi driver. config NXP_WIFI_TX_PER_TRACK bool "TX packet error tracking" help This option is used to track Tx packet error ratio. config NXP_WIFI_CSI bool "CSI support" default y depends on NXP_RW610 || NXP_88W8987 || NXP_WIFI_CUSTOM help This option enable/disable channel state information collection. config NXP_WIFI_RESET bool "Wi-Fi reset" default y help This option is used to enable/disable/reset Wi-Fi. config NXP_WIFI_ECSA bool "ECSA" default y help This option is used to do channel switch according to spec. config NXP_WIFI_UNII4_BAND_SUPPORT bool "UNII4 support" default y depends on NXP_WIFI_5GHz_SUPPORT help This option is used to enable/disable UNII4 channels. config NXP_WIFI_RECOVERY bool "RECOVERY" depends on NXP_RW610 help This option is used to enable wifi recovery support. if NXP_RW610 config FW_VDLLV2 bool "Firmware virtual dynamic link library version 2" help This option is to load some firmware features in run-time. config NXP_WIFI_AUTO_NULL_TX bool "Auto send null frame" default y help This option is to support sending null frame in period for CSI. config NXP_WIFI_NET_MONITOR bool "Networking monitor" default y help This option is used to set/get network monitor configuration. config NXP_WIFI_CAU_TEMPERATURE bool "Cau temperature" default y help This option is used to enable/disable Cau temperature. config NXP_WIFI_TSP bool "Thermal Safeguard Protection" default y help This option is used to set and get Thermal Safeguard Protection configuration. config NXP_WIFI_IPS bool "IPS" default y help This option enable/disable config for IPS in the Wi-Fi driver. config NXP_WIFI_RX_ABORT_CFG bool "RX abort support" default y help This option enables rx abort config with static RSSI threshold in the Wi-Fi driver. config NXP_WIFI_RX_ABORT_CFG_EXT bool "RX abort extension support" default y help This option enables rx abort extension config with dynamic RSSI threshold in the Wi-Fi driver. config NXP_WIFI_CCK_DESENSE_CFG bool "CCK desense mode support" default y help This option enables cck desense mode in the Wi-Fi driver. config NXP_WIFI_COEX_DUTY_CYCLE bool "Set duty cycle" default y help This option sets duty cycle in the Wi-Fi driver. config NXP_WIFI_MMSF bool "11AX density config" default y help This option is used to specify/get 11ax density config in the Wi-Fi driver. config NXP_WIFI_IMD3_CFG bool "Set imd validation parameters" default y help This option is used to set IM3 configuration for Wi-Fi, BLE coex mode and antenna isolation debug. config NXP_WIFI_ANT_DETECT bool "Antenna automatic detection" default y help This option is used to auto detect which two antennas are present and then configure corresponding evaluate Mode-X to firmware and enable antenna diversity. config NXP_WIFI_WLAN_CALDATA_1ANT bool "One antenna" help This option is used to enable one antenna. config NXP_WIFI_WLAN_CALDATA_1ANT_WITH_DIVERSITY bool "One antenna diversity" help This option is used to enable one antenna diversity. config NXP_WIFI_WLAN_CALDATA_3ANT_DIVERSITY bool "Three antenna diversity" help This option is used to enable three antenna diversity. endif # NXP_RW610 config NXP_WIFI_11AX_TWT bool "802.11ax TWT support" default y depends on NXP_WIFI_11AX help This option enables 11ax TWT in the Wi-Fi driver. config NXP_WIFI_DTIM_PERIOD bool "Wi-Fi DTIM period" default y help This option is used to set dtim period in the Wi-Fi driver. config NXP_WIFI_MEM_ACCESS bool default y if NXP_RW610 help This option enables memory access cmd in the Wi-Fi driver. config NXP_WIFI_REG_ACCESS bool default y if NXP_RW610 help This option enables register access cmd in the Wi-Fi driver. config NXP_WIFI_SUBSCRIBE_EVENT_SUPPORT bool "Subscribe event from firmware" default y if NXP_RW610 help This option prints the get subscribe event from firmware for user test. config NXP_WIFI_TX_RX_HISTOGRAM bool "TX/RX statistics" default y if NXP_RW610 help This option enables TX/RX statistics in the Wi-Fi driver. config NXP_WIFI_RF_TEST_MODE bool "WLAN RF Test Mode" default y if NXP_RW610 help This option enables WLAN test mode commands. config NXP_WIFI_EU_VALIDATION bool "EU Validation" default y help This option enables EU Validation Support. if NXP_RW610 || NXP_IW61X config NXP_WIFI_CLOCKSYNC bool "Clock sync using TSF latch" default y help This option enables clock synchronization of TSF latches. config NXP_WIFI_COMPRESS_TX_PWTBL bool "Compress TX Power Table Support" default y help This option enables the use of Compress TX Power Table support. config NXP_WIFI_COMPRESS_RU_TX_PWTBL bool "Compress RU TX Power Table Support" default y help This option enables the use of Compress RU TX Power Table support. endif config NXP_WIFI_EU_CRYPTO bool "Wi-Fi EU Crypto" default y depends on !NXP_88W8801 help This option enables Wi-Fi EU Crypto support in the Wi-Fi driver. config NXP_WIFI_HOST_SLEEP bool "HOST Sleep" default y if PM help This option enables HOST Sleep support for MCU. config NXP_WIFI_MEF_CFG bool "Memory Efficient Filtering" default y if PM help This option enables Memory Efficient Filtering support in the Wi-Fi driver. config NXP_WIFI_FIPS bool "FIPS" help This option enables Wi-Fi FIPS support in the Wi-Fi driver. config NXP_WIFI_OWE bool "Opportunistic Wireless Encryption" default y help This option enables Wi-Fi Opportunistic Wireless Encryption support in the Wi-Fi driver. config NXP_WIFI_TC_RELOCATE bool "Traffic api relocate to RAM" default y help Relocate Wi-Fi transmit and receive api to RAM to increase traffic throughput. config NXP_WIFI_CUSTOM_CALDATA bool "Set caldata by drv" help This option force to use custom calibration data. if NXP_88W8987 || NXP_IW416 config NXP_WIFI_FW_AUTO_RECONNECT bool "Firmware Auto Reconnect" default y help This option enables the use of firmware auto recoonect support. config NXP_WIFI_IND_DNLD bool "Parallel Firmware Download" help This option enables the use of Parallel firmware download support. config NXP_WIFI_IND_RESET bool "Wi-Fi Independent Reset" help This option enables the use of Wi-Fi independent reset support. endif config NXP_WIFI_SMOKE_TESTS bool "Smoke Tests" select NET_SHELL select KERNEL_SHELL select SHELL_BACKEND_TELNET select SHELL_TELNET_SUPPORT_COMMAND help This option is for development smoke tests in the Wi-Fi driver. if NXP_WIFI_SMOKE_TESTS config NXP_WIFI_SIGMA_AGENT bool "Wi-Fi Alliance Sigma Agent Support" select POSIX_API select PTHREAD_IPC select PTHREAD_CREATE_BARRIER select TIMER help This option is to enable Wi-Fi Alliance Sigma Agent support in the Wi-Fi driver. choice prompt "NXP SM IP Address configuration" default NXP_WIFI_SM_IP_DHCP help Choose whether to use an IP assigned by DHCP Server or configure a static IP Address. config NXP_WIFI_SM_IP_DHCP bool "DHCP" help Use DHCP to get an IP Address. config NXP_WIFI_SM_IP_STATIC bool "Static" help Setup Static IP Address. endchoice if NXP_WIFI_SM_IP_STATIC config NXP_WIFI_SM_IP_ADDRESS string "NXP Station mode IP Address" config NXP_WIFI_SM_IP_GATEWAY string "Gateway Address" config NXP_WIFI_SM_IP_MASK string "Network Mask" endif endif # NXP_WIFI_SMOKE_TESTS menu "Development and Debugging" config NXP_WIFI_ENABLE_ERROR_LOGS bool "WiFi driver error logs control" default y if WIFI_LOG_LEVEL_ERR || WIFI_LOG_LEVEL_DBG help If you enable this, error messages will be printed in case of error conditions. This will increase the size of the image. It is strongly recommended to keep it enabled during development, to quickly localize problems. config NXP_WIFI_ENABLE_WARNING_LOGS bool "WiFi driver warning logs control" default y if WIFI_LOG_LEVEL_WRN || WIFI_LOG_LEVEL_DBG help If you enable this, error messages will be printed in case of error conditions. This will increase the size of the image. It is strongly recommended to keep it enabled during development, to quickly localize problems. config NXP_WIFI_DEBUG_BUILD bool "Debug build" depends on WIFI_LOG_LEVEL_DBG help If you enable this the debug options will be enabled. Asserts will be also be enabled. config NXP_WIFI_OS_DEBUG bool "OS debug" depends on NXP_WIFI_DEBUG_BUILD help If you enable this the OS abstraction APIs debugs will be enabled. config NXP_WIFI_NET_DEBUG bool "NET debug" depends on NXP_WIFI_DEBUG_BUILD help If you enable this the network driver abstraction APIs debugs will be enabled. config NXP_WIFI_WLCMGR_DEBUG bool "Wireless Connection Manager" depends on NXP_WIFI_DEBUG_BUILD help If you enable this the WLAN Connection Manager APIs debugs will be enabled. menu "Wifi extra debug options" config NXP_WIFI_EXTRA_DEBUG bool "WiFi driver extra debug control" depends on WIFI_LOG_LEVEL_DBG help This macro helps you to get additional debugging information from the wifi driver. For e.g. more detailed reason will be given if an assoc failure happens. config NXP_WIFI_UAP_DEBUG bool "WiFi driver uAP debug" depends on NXP_WIFI_EXTRA_DEBUG depends on NXP_WIFI_SOFTAP_SUPPORT help Enabling this will print out logs related to the uAP. This is enable to developer to localize issues related to uAP. Apart from other logs, uAP initialization and configuration logs are printed out. config NXP_WIFI_EVENTS_DEBUG bool "Dump event information" depends on NXP_WIFI_EXTRA_DEBUG help Enabling this will dump event codes of events received on from the firmware. This helps the developer to checks the events received from the firmware along with their timestamp. config NXP_WIFI_CMD_RESP_DEBUG bool "Dump command and response codes" depends on NXP_WIFI_EXTRA_DEBUG help Enabling this will dump command and response codes send to and received from firmware respectively. config NXP_WIFI_PS_DEBUG bool "Power save debug" depends on NXP_WIFI_EXTRA_DEBUG help Enabling this will dump command and response codes send to and received from firmware respectively for power save commands. config NXP_WIFI_SCAN_DEBUG bool "Scan debug" depends on NXP_WIFI_EXTRA_DEBUG help Enabling this will enable scan code logs This helps the developer to localize wlan scan related issues like split scan, channel selections, etc config NXP_WIFI_PKT_DEBUG bool "Packet debug" depends on NXP_WIFI_EXTRA_DEBUG help Enabling this will enable packet TX/RX code logs This helps the developer to localize wlan data path related issues like tx/rx failures, etc config NXP_WIFI_IO_INFO_DUMP bool "Input-Output debug (basic)" depends on NXP_WIFI_EXTRA_DEBUG help Enabling this will dump information about input/output data packets. This information has information like packet size and interface for which packet is destined. config NXP_WIFI_IO_DEBUG bool "Input-Output debug (advanced)" depends on NXP_WIFI_EXTRA_DEBUG help Enabling this will enable I/O debugging of wifi driver. This enables you to see how the driver is interacting with the SDIO bus. config NXP_WIFI_IO_DUMP bool "Hex Dump packets" depends on NXP_WIFI_EXTRA_DEBUG help Enabling this will enable I/O debugging of wifi driver. This enables you to see all the packets that are received/sent from/to the SDIO bus. config NXP_WIFI_MEM_DEBUG bool "Allocations debug" depends on NXP_WIFI_EXTRA_DEBUG help Enabling this will enable monitoring memory allocations and frees done by the wifi driver. This enables you to gauge and/or debug heap memory used by the driver. config NXP_WIFI_AMPDU_DEBUG bool "AMPDU debug" depends on NXP_WIFI_EXTRA_DEBUG help Enabling this will help you to monitor what is happening to AMPDU Rx packets. Note that AMPDU Tx is not supported by the driver. Note that you will need to enable timer debug separately to see timer activity going on during out of order packets handling. config NXP_WIFI_TIMER_DEBUG bool "Timers debug" depends on NXP_WIFI_EXTRA_DEBUG help Enable this to monitor timer activity of the driver. Timers are generally used for AMPDU out of order packet handling. It is also used for command timeout related functionality. config NXP_WIFI_SDIO_DEBUG bool "SDIO debug" depends on NXP_WIFI_EXTRA_DEBUG help Enable this to monitor SDIO init deinit errors config NXP_WIFI_SDIO_IO_DEBUG bool "SDIO IO debug" depends on NXP_WIFI_EXTRA_DEBUG help Enable this to monitor SDIO driver read write errors for data and command operations. config NXP_WIFI_FWDNLD_IO_DEBUG bool "FW download debug" depends on NXP_WIFI_EXTRA_DEBUG help Enable this to monitor FW download debug logs config NXP_WIFI_FW_DEBUG bool "FW debug" depends on NXP_WIFI_EXTRA_DEBUG help Enable this to monitor debug logs from FW config NXP_WIFI_FW_VDLL_DEBUG bool "VDLL debug" depends on NXP_WIFI_EXTRA_DEBUG help Enable this to monitor VDLL debug logs endmenu # Wifi extra debug options endmenu # Development and Debugging # Create hidden config options that are used in NXP Wi-Fi driver. # This way we do not need to mark them as allowed for CI checks. # And also someone else cannot use the same name options. config RX_CHAN_INFO bool default y config TXPD_RXPD_V3 bool default y endif # WIFI_NXP ```
/content/code_sandbox/drivers/wifi/nxp/Kconfig.nxp
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
8,195
```objective-c /** * * @file nxp_wifi_drv.h * Shim layer between wifi driver connection manager and zephyr * Wi-Fi L2 layer */ #ifndef ZEPHYR_DRIVERS_WIFI_NNP_WIFI_DRV_H_ #define ZEPHYR_DRIVERS_WIFI_NXP_WIFI_DRV_H_ #include <zephyr/kernel.h> #include <stdio.h> #ifdef CONFIG_SDIO_STACK #include <zephyr/sd/sd.h> #include <zephyr/sd/sdio.h> #endif #include <zephyr/drivers/gpio.h> #include <zephyr/net/wifi_mgmt.h> #include <zephyr/net/dhcpv4_server.h> #include "wlan_bt_fw.h" #include "wlan.h" #include "wm_net.h" #if defined(CONFIG_NXP_WIFI_SHELL) #include "wifi_shell.h" #endif #if defined(CONFIG_WIFI_NM_WPA_SUPPLICANT) #include "wifi_nxp.h" #include "rtos_wpa_supp_if.h" #endif #define MAX_DATA_SIZE 1600 #define NXP_WIFI_SYNC_TIMEOUT_MS K_FOREVER #define NXP_WIFI_UAP_NETWORK_NAME "uap-network" #define NXP_WIFI_STA_NETWORK_NAME "sta-network" #define NXP_WIFI_EVENT_BIT(event) (1 << event) #define NXP_WIFI_SYNC_INIT_GROUP \ NXP_WIFI_EVENT_BIT(WLAN_REASON_INITIALIZED) | \ NXP_WIFI_EVENT_BIT(WLAN_REASON_INITIALIZATION_FAILED) #define NXP_WIFI_SYNC_PS_GROUP \ NXP_WIFI_EVENT_BIT(WLAN_REASON_PS_ENTER) | NXP_WIFI_EVENT_BIT(WLAN_REASON_PS_EXIT) enum nxp_wifi_ret { NXP_WIFI_RET_SUCCESS, NXP_WIFI_RET_FAIL, NXP_WIFI_RET_NOT_FOUND, NXP_WIFI_RET_AUTH_FAILED, NXP_WIFI_RET_ADDR_FAILED, NXP_WIFI_RET_NOT_CONNECTED, NXP_WIFI_RET_NOT_READY, NXP_WIFI_RET_TIMEOUT, NXP_WIFI_RET_BAD_PARAM, }; enum nxp_wifi_state { NXP_WIFI_NOT_INITIALIZED, NXP_WIFI_INITIALIZED, NXP_WIFI_STARTED, }; struct nxp_wifi_dev { struct net_if *iface; scan_result_cb_t scan_cb; struct k_mutex mutex; }; int nxp_wifi_wlan_event_callback(enum wlan_event_reason reason, void *data); #if defined(CONFIG_NXP_WIFI_SHELL) void nxp_wifi_shell_register(struct nxp_wifi_dev *dev); #else #define nxp_wifi_shell_register(dev) #endif #endif ```
/content/code_sandbox/drivers/wifi/nxp/nxp_wifi_drv.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
501
```c /** * * @file nxp_wifi_drv.c * Shim layer between wifi driver connection manager and zephyr * Wi-Fi L2 layer */ #define DT_DRV_COMPAT nxp_wifi #include <zephyr/net/ethernet.h> #include <zephyr/net/dns_resolve.h> #include <zephyr/device.h> #include <soc.h> #include <ethernet/eth_stats.h> #include <zephyr/logging/log.h> #include <zephyr/net/net_if.h> #include <zephyr/net/wifi_mgmt.h> #ifdef CONFIG_PM_DEVICE #include <zephyr/pm/device.h> #endif #ifdef CONFIG_WIFI_NM #include <zephyr/net/wifi_nm.h> #endif LOG_MODULE_REGISTER(nxp_wifi, CONFIG_WIFI_LOG_LEVEL); #include "nxp_wifi_drv.h" /******************************************************************************* * Definitions ******************************************************************************/ #ifdef CONFIG_NXP_WIFI_TC_RELOCATE #define NXP_WIFI_SET_FUNC_ATTR __ramfunc #else #define NXP_WIFI_SET_FUNC_ATTR #endif #ifdef CONFIG_NXP_RW610 #define IMU_IRQ_N DT_INST_IRQ_BY_IDX(0, 0, irq) #define IMU_IRQ_P DT_INST_IRQ_BY_IDX(0, 0, priority) #define IMU_WAKEUP_IRQ_N DT_INST_IRQ_BY_IDX(0, 1, irq) #define IMU_WAKEUP_IRQ_P DT_INST_IRQ_BY_IDX(0, 1, priority) #endif /******************************************************************************* * Variables ******************************************************************************/ static int s_nxp_wifi_State = NXP_WIFI_NOT_INITIALIZED; static bool s_nxp_wifi_StaConnected; static bool s_nxp_wifi_UapActivated; static struct k_event s_nxp_wifi_SyncEvent; static struct nxp_wifi_dev nxp_wifi0; /* static instance */ static struct wlan_network nxp_wlan_network; #ifndef CONFIG_WIFI_NM_WPA_SUPPLICANT static char uap_ssid[IEEEtypes_SSID_SIZE + 1]; #endif extern struct interface g_mlan; #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT extern struct interface g_uap; #endif #ifdef CONFIG_WIFI_NM_WPA_SUPPLICANT extern const rtos_wpa_supp_dev_ops wpa_supp_ops; #endif #if defined(CONFIG_PM_DEVICE) && defined(CONFIG_NXP_RW610) extern int is_hs_handshake_done; extern int wlan_host_sleep_state; #endif static int nxp_wifi_recv(struct net_if *iface, struct net_pkt *pkt); /******************************************************************************* * Prototypes ******************************************************************************/ #ifdef CONFIG_NXP_WIFI_STA_AUTO_CONN static void nxp_wifi_auto_connect(void); #endif /* Callback Function passed to WLAN Connection Manager. The callback function * gets called when there are WLAN Events that need to be handled by the * application. */ int nxp_wifi_wlan_event_callback(enum wlan_event_reason reason, void *data) { int ret; #ifndef CONFIG_WIFI_NM_WPA_SUPPLICANT struct wlan_ip_config addr; char ssid[IEEEtypes_SSID_SIZE + 1]; char ip[16]; #endif static int auth_fail; #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT wlan_uap_client_disassoc_t *disassoc_resp = data; struct in_addr dhcps_addr4; struct in_addr base_addr; struct in_addr netmask_addr; #endif struct wifi_iface_status status = { 0 }; struct wifi_ap_sta_info ap_sta_info = { 0 }; LOG_DBG("WLAN: received event %d", reason); if (s_nxp_wifi_State >= NXP_WIFI_INITIALIZED) { /* Do not replace the current set of events */ k_event_post(&s_nxp_wifi_SyncEvent, NXP_WIFI_EVENT_BIT(reason)); } switch (reason) { case WLAN_REASON_INITIALIZED: LOG_DBG("WLAN initialized"); #ifdef CONFIG_NET_INTERFACE_NAME ret = net_if_set_name(g_mlan.netif, "ml"); if (ret < 0) { LOG_ERR("Failed to set STA nxp_wlan_network interface name"); return 0; } #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT ret = net_if_set_name(g_uap.netif, "ua"); if (ret < 0) { LOG_ERR("Failed to set uAP nxp_wlan_network interface name"); return 0; } #endif #endif #ifdef CONFIG_NXP_WIFI_STA_AUTO_CONN nxp_wifi_auto_connect(); #endif break; case WLAN_REASON_INITIALIZATION_FAILED: LOG_ERR("WLAN: initialization failed"); break; case WLAN_REASON_AUTH_SUCCESS: net_eth_carrier_on(g_mlan.netif); LOG_DBG("WLAN: authenticated to nxp_wlan_network"); break; case WLAN_REASON_SUCCESS: LOG_DBG("WLAN: connected to nxp_wlan_network"); #ifndef CONFIG_WIFI_NM_WPA_SUPPLICANT ret = wlan_get_address(&addr); if (ret != WM_SUCCESS) { LOG_ERR("failed to get IP address"); return 0; } net_inet_ntoa(addr.ipv4.address, ip); ret = wlan_get_current_network_ssid(ssid); if (ret != WM_SUCCESS) { LOG_ERR("Failed to get External AP nxp_wlan_network ssid"); return 0; } LOG_DBG("Connected to following BSS:"); LOG_DBG("SSID = [%s]", ssid); if (addr.ipv4.address != 0U) { LOG_DBG("IPv4 Address: [%s]", ip); } #ifdef CONFIG_NXP_WIFI_IPV6 ARRAY_FOR_EACH(addr.ipv6, i) { if ((addr.ipv6[i].addr_state == NET_ADDR_TENTATIVE) || (addr.ipv6[i].addr_state == NET_ADDR_PREFERRED)) { LOG_DBG("IPv6 Address: %-13s:\t%s (%s)", ipv6_addr_type_to_desc( (struct net_ipv6_config *)&addr.ipv6[i]), ipv6_addr_addr_to_desc( (struct net_ipv6_config *)&addr.ipv6[i]), ipv6_addr_state_to_desc(addr.ipv6[i].addr_state)); } } LOG_DBG(""); #endif #endif auth_fail = 0; s_nxp_wifi_StaConnected = true; wifi_mgmt_raise_connect_result_event(g_mlan.netif, 0); break; case WLAN_REASON_CONNECT_FAILED: net_eth_carrier_off(g_mlan.netif); LOG_WRN("WLAN: connect failed"); break; case WLAN_REASON_NETWORK_NOT_FOUND: net_eth_carrier_off(g_mlan.netif); LOG_WRN("WLAN: nxp_wlan_network not found"); break; case WLAN_REASON_NETWORK_AUTH_FAILED: net_eth_carrier_off(g_mlan.netif); LOG_WRN("WLAN: nxp_wlan_network authentication failed"); auth_fail++; if (auth_fail >= 3) { LOG_WRN("Authentication Failed. Disconnecting ... "); wlan_disconnect(); auth_fail = 0; } break; case WLAN_REASON_ADDRESS_SUCCESS: LOG_DBG("wlan_network mgr: DHCP new lease"); break; case WLAN_REASON_ADDRESS_FAILED: LOG_WRN("failed to obtain an IP address"); break; case WLAN_REASON_USER_DISCONNECT: net_eth_carrier_off(g_mlan.netif); LOG_DBG("disconnected"); auth_fail = 0; s_nxp_wifi_StaConnected = false; wifi_mgmt_raise_disconnect_result_event(g_mlan.netif, 0); break; case WLAN_REASON_LINK_LOST: net_eth_carrier_off(g_mlan.netif); LOG_WRN("WLAN: link lost"); break; case WLAN_REASON_CHAN_SWITCH: LOG_DBG("WLAN: channel switch"); break; #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT case WLAN_REASON_UAP_SUCCESS: net_eth_carrier_on(g_uap.netif); LOG_DBG("WLAN: UAP Started"); #ifndef CONFIG_WIFI_NM_WPA_SUPPLICANT ret = wlan_get_current_uap_network_ssid(uap_ssid); if (ret != WM_SUCCESS) { LOG_ERR("Failed to get Soft AP nxp_wlan_network ssid"); return 0; } LOG_DBG("Soft AP \"%s\" started successfully", uap_ssid); #endif if (net_addr_pton(AF_INET, CONFIG_NXP_WIFI_SOFTAP_IP_ADDRESS, &dhcps_addr4) < 0) { LOG_ERR("Invalid CONFIG_NXP_WIFI_SOFTAP_IP_ADDRESS"); return 0; } net_if_ipv4_addr_add(g_uap.netif, &dhcps_addr4, NET_ADDR_MANUAL, 0); net_if_ipv4_set_gw(g_uap.netif, &dhcps_addr4); if (net_addr_pton(AF_INET, CONFIG_NXP_WIFI_SOFTAP_IP_MASK, &netmask_addr) < 0) { LOG_ERR("Invalid CONFIG_NXP_WIFI_SOFTAP_IP_MASK"); return 0; } net_if_ipv4_set_netmask_by_addr(g_uap.netif, &dhcps_addr4, &netmask_addr); net_if_up(g_uap.netif); if (net_addr_pton(AF_INET, CONFIG_NXP_WIFI_SOFTAP_IP_BASE, &base_addr) < 0) { LOG_ERR("Invalid CONFIG_NXP_WIFI_SOFTAP_IP_BASE"); return 0; } if (net_dhcpv4_server_start(g_uap.netif, &base_addr) < 0) { LOG_ERR("DHCP Server start failed"); return 0; } LOG_DBG("DHCP Server started successfully"); s_nxp_wifi_UapActivated = true; break; case WLAN_REASON_UAP_CLIENT_ASSOC: LOG_DBG("WLAN: UAP a Client Associated"); LOG_DBG("Client => "); print_mac((const char *)data); LOG_DBG("Associated with Soft AP"); break; case WLAN_REASON_UAP_CLIENT_CONN: wlan_get_current_uap_network(&nxp_wlan_network); #ifdef CONFIG_NXP_WIFI_11AX if (nxp_wlan_network.dot11ax) { ap_sta_info.link_mode = WIFI_6; } #endif #ifdef CONFIG_NXP_WIFI_11AC else if (nxp_wlan_network.dot11ac) { ap_sta_info.link_mode = WIFI_5; } #endif else if (nxp_wlan_network.dot11n) { ap_sta_info.link_mode = WIFI_4; } else { ap_sta_info.link_mode = WIFI_3; } memcpy(ap_sta_info.mac, data, WIFI_MAC_ADDR_LEN); ap_sta_info.mac_length = WIFI_MAC_ADDR_LEN; ap_sta_info.twt_capable = status.twt_capable; wifi_mgmt_raise_ap_sta_connected_event(g_uap.netif, &ap_sta_info); LOG_DBG("WLAN: UAP a Client Connected"); LOG_DBG("Client => "); print_mac((const char *)data); LOG_DBG("Connected with Soft AP"); break; case WLAN_REASON_UAP_CLIENT_DISSOC: memcpy(ap_sta_info.mac, disassoc_resp->sta_addr, WIFI_MAC_ADDR_LEN); wifi_mgmt_raise_ap_sta_disconnected_event(g_uap.netif, &ap_sta_info); LOG_DBG("WLAN: UAP a Client Dissociated:"); LOG_DBG(" Client MAC => "); print_mac((const char *)(disassoc_resp->sta_addr)); LOG_DBG(" Reason code => "); LOG_DBG("%d", disassoc_resp->reason_code); break; case WLAN_REASON_UAP_STOPPED: net_eth_carrier_off(g_uap.netif); LOG_DBG("WLAN: UAP Stopped"); net_dhcpv4_server_stop(g_uap.netif); LOG_DBG("DHCP Server stopped successfully"); s_nxp_wifi_UapActivated = false; break; #endif case WLAN_REASON_PS_ENTER: LOG_DBG("WLAN: PS_ENTER"); break; case WLAN_REASON_PS_EXIT: LOG_DBG("WLAN: PS EXIT"); break; #ifdef CONFIG_NXP_WIFI_SUBSCRIBE_EVENT_SUPPORT case WLAN_REASON_RSSI_HIGH: case WLAN_REASON_SNR_LOW: case WLAN_REASON_SNR_HIGH: case WLAN_REASON_MAX_FAIL: case WLAN_REASON_BEACON_MISSED: case WLAN_REASON_DATA_RSSI_LOW: case WLAN_REASON_DATA_RSSI_HIGH: case WLAN_REASON_DATA_SNR_LOW: case WLAN_REASON_DATA_SNR_HIGH: case WLAN_REASON_LINK_QUALITY: case WLAN_REASON_PRE_BEACON_LOST: break; #endif default: LOG_WRN("WLAN: Unknown Event: %d", reason); } return 0; } static int nxp_wifi_wlan_init(void) { int status = NXP_WIFI_RET_SUCCESS; int ret; if (s_nxp_wifi_State != NXP_WIFI_NOT_INITIALIZED) { status = NXP_WIFI_RET_FAIL; } if (status == NXP_WIFI_RET_SUCCESS) { k_event_init(&s_nxp_wifi_SyncEvent); } if (status == NXP_WIFI_RET_SUCCESS) { ret = wlan_init(wlan_fw_bin, wlan_fw_bin_len); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } } if (status != NXP_WIFI_RET_SUCCESS) { return -1; } s_nxp_wifi_State = NXP_WIFI_INITIALIZED; nxp_wifi_internal_register_rx_cb(nxp_wifi_recv); return 0; } static int nxp_wifi_wlan_start(void) { int status = NXP_WIFI_RET_SUCCESS; int ret; uint32_t syncBit; if (s_nxp_wifi_State != NXP_WIFI_INITIALIZED) { status = NXP_WIFI_RET_NOT_READY; } if (status == NXP_WIFI_RET_SUCCESS) { k_event_clear(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_INIT_GROUP); ret = wlan_start(nxp_wifi_wlan_event_callback); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } } if (status == NXP_WIFI_RET_SUCCESS) { syncBit = k_event_wait(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_INIT_GROUP, false, NXP_WIFI_SYNC_TIMEOUT_MS); k_event_clear(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_INIT_GROUP); if (syncBit & NXP_WIFI_EVENT_BIT(WLAN_REASON_INITIALIZED)) { status = NXP_WIFI_RET_SUCCESS; } else if (syncBit & NXP_WIFI_EVENT_BIT(WLAN_REASON_INITIALIZATION_FAILED)) { status = NXP_WIFI_RET_FAIL; } else { status = NXP_WIFI_RET_TIMEOUT; } } if (status != NXP_WIFI_RET_SUCCESS) { return -1; } s_nxp_wifi_State = NXP_WIFI_STARTED; return 0; } #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT static int nxp_wifi_start_ap(const struct device *dev, struct wifi_connect_req_params *params) { int status = NXP_WIFI_RET_SUCCESS; int ret; struct interface *if_handle = (struct interface *)&g_uap; if (if_handle->state.interface != WLAN_BSS_TYPE_UAP) { LOG_ERR("Wi-Fi not in uAP mode"); return -EIO; } if ((s_nxp_wifi_State != NXP_WIFI_STARTED) || (s_nxp_wifi_UapActivated != false)) { status = NXP_WIFI_RET_NOT_READY; } if (status == NXP_WIFI_RET_SUCCESS) { if ((params->ssid_length == 0) || (params->ssid_length > IEEEtypes_SSID_SIZE)) { status = NXP_WIFI_RET_BAD_PARAM; } } if (status == NXP_WIFI_RET_SUCCESS) { wlan_remove_network(nxp_wlan_network.name); wlan_initialize_uap_network(&nxp_wlan_network); memcpy(nxp_wlan_network.name, NXP_WIFI_UAP_NETWORK_NAME, strlen(NXP_WIFI_UAP_NETWORK_NAME)); memcpy(nxp_wlan_network.ssid, params->ssid, params->ssid_length); if (params->channel == WIFI_CHANNEL_ANY) { nxp_wlan_network.channel = 0; } else { nxp_wlan_network.channel = params->channel; } if (params->mfp == WIFI_MFP_REQUIRED) { nxp_wlan_network.security.mfpc = true; nxp_wlan_network.security.mfpr = true; } else if (params->mfp == WIFI_MFP_OPTIONAL) { nxp_wlan_network.security.mfpc = true; nxp_wlan_network.security.mfpr = false; } if (params->security == WIFI_SECURITY_TYPE_NONE) { nxp_wlan_network.security.type = WLAN_SECURITY_NONE; } else if (params->security == WIFI_SECURITY_TYPE_PSK) { nxp_wlan_network.security.type = WLAN_SECURITY_WPA2; nxp_wlan_network.security.psk_len = params->psk_length; strncpy(nxp_wlan_network.security.psk, params->psk, params->psk_length); } #ifdef CONFIG_WIFI_NM_WPA_SUPPLICANT else if (params->security == WIFI_SECURITY_TYPE_PSK_SHA256) { nxp_wlan_network.security.type = WLAN_SECURITY_WPA2; nxp_wlan_network.security.key_mgmt |= WLAN_KEY_MGMT_PSK_SHA256; nxp_wlan_network.security.psk_len = params->psk_length; strncpy(nxp_wlan_network.security.psk, params->psk, params->psk_length); } #endif else if (params->security == WIFI_SECURITY_TYPE_SAE) { nxp_wlan_network.security.type = WLAN_SECURITY_WPA3_SAE; nxp_wlan_network.security.password_len = params->psk_length; strncpy(nxp_wlan_network.security.password, params->psk, params->psk_length); } else { status = NXP_WIFI_RET_BAD_PARAM; } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_ERR("Failed to enable Wi-Fi AP mode"); return -EAGAIN; } ret = wlan_add_network(&nxp_wlan_network); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } ret = wlan_start_network(nxp_wlan_network.name); if (ret != WM_SUCCESS) { wlan_remove_network(nxp_wlan_network.name); status = NXP_WIFI_RET_FAIL; } return 0; } static int nxp_wifi_stop_ap(const struct device *dev) { int status = NXP_WIFI_RET_SUCCESS; int ret; struct interface *if_handle = (struct interface *)&g_uap; if (if_handle->state.interface != WLAN_BSS_TYPE_UAP) { LOG_ERR("Wi-Fi not in uAP mode"); return -EIO; } if ((s_nxp_wifi_State != NXP_WIFI_STARTED) || (s_nxp_wifi_UapActivated != true)) { status = NXP_WIFI_RET_NOT_READY; } if (status == NXP_WIFI_RET_SUCCESS) { ret = wlan_stop_network(NXP_WIFI_UAP_NETWORK_NAME); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_ERR("Failed to disable Wi-Fi AP mode"); return -EAGAIN; } return 0; } #endif static int nxp_wifi_process_results(unsigned int count) { struct wlan_scan_result scan_result = {0}; struct wifi_scan_result res = {0}; if (!count) { LOG_DBG("No Wi-Fi AP found"); goto out; } if (g_mlan.max_bss_cnt) { count = g_mlan.max_bss_cnt > count ? count : g_mlan.max_bss_cnt; } for (int i = 0; i < count; i++) { wlan_get_scan_result(i, &scan_result); memset(&res, 0, sizeof(struct wifi_scan_result)); memcpy(res.mac, scan_result.bssid, WIFI_MAC_ADDR_LEN); res.mac_length = WIFI_MAC_ADDR_LEN; res.ssid_length = scan_result.ssid_len; strncpy(res.ssid, scan_result.ssid, scan_result.ssid_len); res.rssi = -scan_result.rssi; res.channel = scan_result.channel; res.band = scan_result.channel > 14 ? WIFI_FREQ_BAND_5_GHZ : WIFI_FREQ_BAND_2_4_GHZ; res.security = WIFI_SECURITY_TYPE_NONE; if (scan_result.wpa2_entp) { res.security = WIFI_SECURITY_TYPE_EAP_TLS; } if (scan_result.wpa2) { res.security = WIFI_SECURITY_TYPE_PSK; } #ifdef CONFIG_WIFI_NM_WPA_SUPPLICANT if (scan_result.wpa2_sha256) { res.security = WIFI_SECURITY_TYPE_PSK_SHA256; } #endif if (scan_result.wpa3_sae) { res.security = WIFI_SECURITY_TYPE_SAE; } if (scan_result.ap_mfpr) { res.mfp = WIFI_MFP_REQUIRED; } else if (scan_result.ap_mfpc) { res.mfp = WIFI_MFP_OPTIONAL; } if (g_mlan.scan_cb) { g_mlan.scan_cb(g_mlan.netif, 0, &res); /* ensure notifications get delivered */ k_yield(); } } out: /* report end of scan event */ if (g_mlan.scan_cb) { g_mlan.scan_cb(g_mlan.netif, 0, NULL); } g_mlan.scan_cb = NULL; return WM_SUCCESS; } static int nxp_wifi_scan(const struct device *dev, struct wifi_scan_params *params, scan_result_cb_t cb) { int ret; struct interface *if_handle = (struct interface *)dev->data; wlan_scan_params_v2_t wlan_scan_params_v2 = {0}; uint8_t i = 0; if (if_handle->state.interface != WLAN_BSS_TYPE_STA) { LOG_ERR("Wi-Fi not in station mode"); return -EIO; } if (s_nxp_wifi_State != NXP_WIFI_STARTED) { LOG_ERR("Wi-Fi not started status %d", s_nxp_wifi_State); return -EBUSY; } if (g_mlan.scan_cb != NULL) { LOG_WRN("Scan callback in progress"); return -EINPROGRESS; } g_mlan.scan_cb = cb; if (params == NULL) { goto do_scan; } g_mlan.max_bss_cnt = params->max_bss_cnt; if (params->bands & (1 << WIFI_FREQ_BAND_6_GHZ)) { LOG_ERR("Wi-Fi band 6 GHz not supported"); g_mlan.scan_cb = NULL; return -EIO; } #if (CONFIG_WIFI_MGMT_SCAN_SSID_FILT_MAX > 0) if (params->ssids[0]) { strncpy(wlan_scan_params_v2.ssid[0], params->ssids[0], WIFI_SSID_MAX_LEN); wlan_scan_params_v2.ssid[0][WIFI_SSID_MAX_LEN - 1] = 0; } #if (CONFIG_WIFI_MGMT_SCAN_SSID_FILT_MAX > 1) if (params->ssids[1]) { strncpy(wlan_scan_params_v2.ssid[1], params->ssids[1], WIFI_SSID_MAX_LEN); wlan_scan_params_v2.ssid[1][WIFI_SSID_MAX_LEN - 1] = 0; } #endif #endif #ifdef CONFIG_WIFI_MGMT_SCAN_CHAN_MAX_MANUAL for (i = 0; i < WIFI_MGMT_SCAN_CHAN_MAX_MANUAL && params->band_chan[i].channel; i++) { if (params->scan_type == WIFI_SCAN_TYPE_ACTIVE) { wlan_scan_params_v2.chan_list[i].scan_type = MLAN_SCAN_TYPE_ACTIVE; wlan_scan_params_v2.chan_list[i].scan_time = params->dwell_time_active; } else { wlan_scan_params_v2.chan_list[i].scan_type = MLAN_SCAN_TYPE_PASSIVE; wlan_scan_params_v2.chan_list[i].scan_time = params->dwell_time_passive; } wlan_scan_params_v2.chan_list[i].chan_number = (uint8_t)(params->band_chan[i].channel); } #endif wlan_scan_params_v2.num_channels = i; if (params->bands & (1 << WIFI_FREQ_BAND_2_4_GHZ)) { wlan_scan_params_v2.chan_list[0].radio_type = 0 | BAND_SPECIFIED; } #ifdef CONFIG_5GHz_SUPPORT if (params->bands & (1 << WIFI_FREQ_BAND_5_GHZ)) { if (wlan_scan_params_v2.chan_list[0].radio_type & BAND_SPECIFIED) { wlan_scan_params_v2.chan_list[0].radio_type = 0; } else { wlan_scan_params_v2.chan_list[0].radio_type = 1 | BAND_SPECIFIED; } } #else if (params->bands & (1 << WIFI_FREQ_BAND_5_GHZ)) { LOG_ERR("Wi-Fi band 5Hz not supported"); g_mlan.scan_cb = NULL; return -EIO; } #endif do_scan: wlan_scan_params_v2.cb = nxp_wifi_process_results; ret = wlan_scan_with_opt(wlan_scan_params_v2); if (ret != WM_SUCCESS) { LOG_ERR("Failed to start Wi-Fi scanning"); g_mlan.scan_cb = NULL; return -EAGAIN; } return 0; } static int nxp_wifi_version(const struct device *dev, struct wifi_version *params) { int status = NXP_WIFI_RET_SUCCESS; if (s_nxp_wifi_State != NXP_WIFI_STARTED) { status = NXP_WIFI_RET_NOT_READY; } if (status != NXP_WIFI_RET_SUCCESS) { LOG_ERR("Failed to get Wi-Fi driver/firmware version"); return -EAGAIN; } params->drv_version = WLAN_DRV_VERSION; params->fw_version = wlan_get_firmware_version_ext(); return 0; } static int nxp_wifi_ap_bandwidth(const struct device *dev, struct wifi_ap_params *params) { int status = NXP_WIFI_RET_SUCCESS; int ret = WM_SUCCESS; struct interface *if_handle = (struct interface *)dev->data; if (if_handle->state.interface != WLAN_BSS_TYPE_UAP) { LOG_ERR("Wi-Fi not in uAP mode"); return -EIO; } if (s_nxp_wifi_State != NXP_WIFI_STARTED) { status = NXP_WIFI_RET_NOT_READY; } if (status == NXP_WIFI_RET_SUCCESS) { if (params->oper == WIFI_MGMT_SET) { ret = wlan_uap_set_bandwidth(params->bandwidth); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } } else { ret = wlan_uap_get_bandwidth(&params->bandwidth); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_ERR("Failed to get/set Wi-Fi AP bandwidth"); return -EAGAIN; } return 0; } static int nxp_wifi_connect(const struct device *dev, struct wifi_connect_req_params *params) { int status = NXP_WIFI_RET_SUCCESS; int ret; struct interface *if_handle = (struct interface *)dev->data; if (s_nxp_wifi_State != NXP_WIFI_STARTED) { LOG_ERR("Wi-Fi not started"); wifi_mgmt_raise_connect_result_event(g_mlan.netif, -1); return -EALREADY; } if (if_handle->state.interface != WLAN_BSS_TYPE_STA) { LOG_ERR("Wi-Fi not in station mode"); wifi_mgmt_raise_connect_result_event(g_mlan.netif, -1); return -EIO; } if ((params->ssid_length == 0) || (params->ssid_length > IEEEtypes_SSID_SIZE)) { status = NXP_WIFI_RET_BAD_PARAM; } if (status == NXP_WIFI_RET_SUCCESS) { wlan_disconnect(); wlan_remove_network(nxp_wlan_network.name); wlan_initialize_sta_network(&nxp_wlan_network); memcpy(nxp_wlan_network.name, NXP_WIFI_STA_NETWORK_NAME, strlen(NXP_WIFI_STA_NETWORK_NAME)); memcpy(nxp_wlan_network.ssid, params->ssid, params->ssid_length); nxp_wlan_network.ssid_specific = 1; if (params->channel == WIFI_CHANNEL_ANY) { nxp_wlan_network.channel = 0; } else { nxp_wlan_network.channel = params->channel; } if (params->mfp == WIFI_MFP_REQUIRED) { nxp_wlan_network.security.mfpc = true; nxp_wlan_network.security.mfpr = true; } else if (params->mfp == WIFI_MFP_OPTIONAL) { nxp_wlan_network.security.mfpc = true; nxp_wlan_network.security.mfpr = false; } if (params->security == WIFI_SECURITY_TYPE_NONE) { nxp_wlan_network.security.type = WLAN_SECURITY_NONE; } else if (params->security == WIFI_SECURITY_TYPE_PSK) { nxp_wlan_network.security.type = WLAN_SECURITY_WPA2; nxp_wlan_network.security.psk_len = params->psk_length; strncpy(nxp_wlan_network.security.psk, params->psk, params->psk_length); } #ifdef CONFIG_WIFI_NM_WPA_SUPPLICANT else if (params->security == WIFI_SECURITY_TYPE_PSK_SHA256) { nxp_wlan_network.security.type = WLAN_SECURITY_WPA2; nxp_wlan_network.security.key_mgmt |= WLAN_KEY_MGMT_PSK_SHA256; nxp_wlan_network.security.psk_len = params->psk_length; strncpy(nxp_wlan_network.security.psk, params->psk, params->psk_length); } #endif else if (params->security == WIFI_SECURITY_TYPE_SAE) { nxp_wlan_network.security.type = WLAN_SECURITY_WPA3_SAE; nxp_wlan_network.security.password_len = params->psk_length; strncpy(nxp_wlan_network.security.password, params->psk, params->psk_length); } else { status = NXP_WIFI_RET_BAD_PARAM; } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_ERR("Failed to connect to Wi-Fi access point"); return -EAGAIN; } ret = wlan_add_network(&nxp_wlan_network); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } ret = wlan_connect(nxp_wlan_network.name); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } return 0; } static int nxp_wifi_disconnect(const struct device *dev) { int status = NXP_WIFI_RET_SUCCESS; int ret; struct interface *if_handle = (struct interface *)dev->data; enum wlan_connection_state connection_state = WLAN_DISCONNECTED; if (s_nxp_wifi_State != NXP_WIFI_STARTED) { status = NXP_WIFI_RET_NOT_READY; } if (if_handle->state.interface != WLAN_BSS_TYPE_STA) { LOG_ERR("Wi-Fi not in station mode"); return -EIO; } wlan_get_connection_state(&connection_state); if (connection_state == WLAN_DISCONNECTED) { s_nxp_wifi_StaConnected = false; wifi_mgmt_raise_disconnect_result_event(g_mlan.netif, -1); return NXP_WIFI_RET_SUCCESS; } if (status == NXP_WIFI_RET_SUCCESS) { ret = wlan_disconnect(); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_ERR("Failed to disconnect from AP"); wifi_mgmt_raise_disconnect_result_event(g_mlan.netif, -1); return -EAGAIN; } wifi_mgmt_raise_disconnect_result_event(g_mlan.netif, 0); return 0; } static inline enum wifi_security_type nxp_wifi_security_type(enum wlan_security_type type) { switch (type) { case WLAN_SECURITY_NONE: return WIFI_SECURITY_TYPE_NONE; case WLAN_SECURITY_WPA2: return WIFI_SECURITY_TYPE_PSK; case WLAN_SECURITY_WPA3_SAE: return WIFI_SECURITY_TYPE_SAE; default: return WIFI_SECURITY_TYPE_UNKNOWN; } } #ifndef CONFIG_WIFI_NM_WPA_SUPPLICANT static int nxp_wifi_uap_status(const struct device *dev, struct wifi_iface_status *status) { enum wlan_connection_state connection_state = WLAN_DISCONNECTED; struct interface *if_handle = (struct interface *)&g_uap; wlan_get_uap_connection_state(&connection_state); if (connection_state == WLAN_UAP_STARTED) { if (!wlan_get_current_uap_network(&nxp_wlan_network)) { strncpy(status->ssid, nxp_wlan_network.ssid, WIFI_SSID_MAX_LEN); status->ssid[WIFI_SSID_MAX_LEN - 1] = 0; status->ssid_len = strlen(status->ssid); memcpy(status->bssid, nxp_wlan_network.bssid, WIFI_MAC_ADDR_LEN); status->rssi = nxp_wlan_network.rssi; status->channel = nxp_wlan_network.channel; status->beacon_interval = nxp_wlan_network.beacon_period; status->dtim_period = nxp_wlan_network.dtim_period; if (if_handle->state.interface == WLAN_BSS_TYPE_STA) { status->iface_mode = WIFI_MODE_INFRA; } #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT else if (if_handle->state.interface == WLAN_BSS_TYPE_UAP) { status->iface_mode = WIFI_MODE_AP; } #endif #ifdef CONFIG_NXP_WIFI_11AX if (nxp_wlan_network.dot11ax) { status->link_mode = WIFI_6; } #endif #ifdef CONFIG_NXP_WIFI_11AC else if (nxp_wlan_network.dot11ac) { status->link_mode = WIFI_5; } #endif else if (nxp_wlan_network.dot11n) { status->link_mode = WIFI_4; } else { status->link_mode = WIFI_3; } status->band = nxp_wlan_network.channel > 14 ? WIFI_FREQ_BAND_5_GHZ : WIFI_FREQ_BAND_2_4_GHZ; status->security = nxp_wifi_security_type(nxp_wlan_network.security.type); status->mfp = nxp_wlan_network.security.mfpr ? WIFI_MFP_REQUIRED : (nxp_wlan_network.security.mfpc ? WIFI_MFP_OPTIONAL : 0); } } return 0; } #endif static int nxp_wifi_status(const struct device *dev, struct wifi_iface_status *status) { enum wlan_connection_state connection_state = WLAN_DISCONNECTED; struct interface *if_handle = (struct interface *)dev->data; wlan_get_connection_state(&connection_state); if (s_nxp_wifi_State != NXP_WIFI_STARTED) { status->state = WIFI_STATE_INTERFACE_DISABLED; return 0; } if (connection_state == WLAN_DISCONNECTED) { status->state = WIFI_STATE_DISCONNECTED; } else if (connection_state == WLAN_SCANNING) { status->state = WIFI_STATE_SCANNING; } else if (connection_state == WLAN_ASSOCIATING) { status->state = WIFI_STATE_ASSOCIATING; } else if (connection_state == WLAN_ASSOCIATED) { status->state = WIFI_STATE_ASSOCIATED; } else if (connection_state == WLAN_CONNECTED) { status->state = WIFI_STATE_COMPLETED; if (!wlan_get_current_network(&nxp_wlan_network)) { strncpy(status->ssid, nxp_wlan_network.ssid, WIFI_SSID_MAX_LEN - 1); status->ssid[WIFI_SSID_MAX_LEN - 1] = '\0'; status->ssid_len = strlen(nxp_wlan_network.ssid); memcpy(status->bssid, nxp_wlan_network.bssid, WIFI_MAC_ADDR_LEN); status->rssi = nxp_wlan_network.rssi; status->channel = nxp_wlan_network.channel; status->beacon_interval = nxp_wlan_network.beacon_period; status->dtim_period = nxp_wlan_network.dtim_period; if (if_handle->state.interface == WLAN_BSS_TYPE_STA) { status->iface_mode = WIFI_MODE_INFRA; } #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT else if (if_handle->state.interface == WLAN_BSS_TYPE_UAP) { status->iface_mode = WIFI_MODE_AP; } #endif #ifdef CONFIG_NXP_WIFI_11AX if (nxp_wlan_network.dot11ax) { status->link_mode = WIFI_6; } #endif #ifdef CONFIG_NXP_WIFI_11AC else if (nxp_wlan_network.dot11ac) { status->link_mode = WIFI_5; } #endif else if (nxp_wlan_network.dot11n) { status->link_mode = WIFI_4; } else { status->link_mode = WIFI_3; } status->band = nxp_wlan_network.channel > 14 ? WIFI_FREQ_BAND_5_GHZ : WIFI_FREQ_BAND_2_4_GHZ; status->security = nxp_wifi_security_type(nxp_wlan_network.security.type); status->mfp = nxp_wlan_network.security.mfpr ? WIFI_MFP_REQUIRED : (nxp_wlan_network.security.mfpc ? WIFI_MFP_OPTIONAL : 0); } } return 0; } #if defined(CONFIG_NET_STATISTICS_WIFI) static int nxp_wifi_stats(const struct device *dev, struct net_stats_wifi *stats) { struct interface *if_handle = (struct interface *)dev->data; stats->bytes.received = if_handle->stats.bytes.received; stats->bytes.sent = if_handle->stats.bytes.sent; stats->pkts.rx = if_handle->stats.pkts.rx; stats->pkts.tx = if_handle->stats.pkts.tx; stats->errors.rx = if_handle->stats.errors.rx; stats->errors.tx = if_handle->stats.errors.tx; stats->broadcast.rx = if_handle->stats.broadcast.rx; stats->broadcast.tx = if_handle->stats.broadcast.tx; stats->multicast.rx = if_handle->stats.multicast.rx; stats->multicast.tx = if_handle->stats.multicast.tx; stats->sta_mgmt.beacons_rx = if_handle->stats.sta_mgmt.beacons_rx; stats->sta_mgmt.beacons_miss = if_handle->stats.sta_mgmt.beacons_miss; return 0; } #endif #ifdef CONFIG_NXP_WIFI_STA_AUTO_CONN static void nxp_wifi_auto_connect(void) { int ssid_len = strlen(CONFIG_NXP_WIFI_STA_AUTO_SSID); int psk_len = strlen(CONFIG_NXP_WIFI_STA_AUTO_PASSWORD); struct wifi_connect_req_params params = {0}; char ssid[IEEEtypes_SSID_SIZE] = {0}; char psk[WLAN_PSK_MAX_LENGTH] = {0}; if (ssid_len >= IEEEtypes_SSID_SIZE) { LOG_ERR("AutoConnect SSID too long"); return; } if (ssid_len == 0) { LOG_ERR("AutoConnect SSID NULL"); return; } strcpy(ssid, CONFIG_NXP_WIFI_STA_AUTO_SSID); if (psk_len == 0) { params.security = WIFI_SECURITY_TYPE_NONE; } else if (psk_len >= WLAN_PSK_MIN_LENGTH && psk_len < WLAN_PSK_MAX_LENGTH) { strcpy(psk, CONFIG_NXP_WIFI_STA_AUTO_PASSWORD); params.security = WIFI_SECURITY_TYPE_PSK; } else { LOG_ERR("AutoConnect invalid password length %d", psk_len); return; } params.channel = WIFI_CHANNEL_ANY; params.ssid = &ssid[0]; params.ssid_length = ssid_len; params.psk = &psk[0]; params.psk_length = psk_len; LOG_DBG("AutoConnect SSID[%s]", ssid); nxp_wifi_connect(g_mlan.netif->if_dev->dev, &params); } #endif static int nxp_wifi_power_save(const struct device *dev, struct wifi_ps_params *params) { int status = NXP_WIFI_RET_SUCCESS; int ret = WM_SUCCESS; uint32_t syncBit; struct interface *if_handle = (struct interface *)dev->data; if (if_handle->state.interface != WLAN_BSS_TYPE_STA) { LOG_ERR("Wi-Fi not in station mode"); return -EIO; } if (s_nxp_wifi_State != NXP_WIFI_STARTED) { status = NXP_WIFI_RET_NOT_READY; } if (status == NXP_WIFI_RET_SUCCESS) { switch (params->type) { case WIFI_PS_PARAM_STATE: if (params->enabled == WIFI_PS_DISABLED) { k_event_clear(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP); ret = wlan_deepsleepps_off(); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } if (status == NXP_WIFI_RET_SUCCESS) { syncBit = k_event_wait(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP, false, NXP_WIFI_SYNC_TIMEOUT_MS); k_event_clear(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP); if (syncBit & NXP_WIFI_EVENT_BIT(WLAN_REASON_PS_EXIT)) { status = NXP_WIFI_RET_SUCCESS; } else { status = NXP_WIFI_RET_TIMEOUT; } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_DBG("Wi-Fi power save is already disabled"); return -EAGAIN; } k_event_clear(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP); ret = wlan_ieeeps_off(); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } if (status == NXP_WIFI_RET_SUCCESS) { syncBit = k_event_wait(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP, false, NXP_WIFI_SYNC_TIMEOUT_MS); k_event_clear(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP); if (syncBit & NXP_WIFI_EVENT_BIT(WLAN_REASON_PS_EXIT)) { status = NXP_WIFI_RET_SUCCESS; } else { status = NXP_WIFI_RET_TIMEOUT; } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_DBG("Wi-Fi power save is already disabled"); return -EAGAIN; } } else if (params->enabled == WIFI_PS_ENABLED) { k_event_clear(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP); ret = wlan_deepsleepps_on(); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } if (status == NXP_WIFI_RET_SUCCESS) { syncBit = k_event_wait(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP, false, NXP_WIFI_SYNC_TIMEOUT_MS); k_event_clear(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP); if (syncBit & NXP_WIFI_EVENT_BIT(WLAN_REASON_PS_ENTER)) { status = NXP_WIFI_RET_SUCCESS; } else { status = NXP_WIFI_RET_TIMEOUT; } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_DBG("Wi-Fi power save is already enabled"); return -EAGAIN; } k_event_clear(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP); ret = wlan_ieeeps_on((unsigned int)WAKE_ON_UNICAST | (unsigned int)WAKE_ON_MAC_EVENT | (unsigned int)WAKE_ON_MULTICAST | (unsigned int)WAKE_ON_ARP_BROADCAST); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } if (status == NXP_WIFI_RET_SUCCESS) { syncBit = k_event_wait(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP, false, NXP_WIFI_SYNC_TIMEOUT_MS); k_event_clear(&s_nxp_wifi_SyncEvent, NXP_WIFI_SYNC_PS_GROUP); if (syncBit & NXP_WIFI_EVENT_BIT(WLAN_REASON_PS_ENTER)) { status = NXP_WIFI_RET_SUCCESS; } else { status = NXP_WIFI_RET_TIMEOUT; } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_DBG("Wi-Fi power save is already enabled"); return -EAGAIN; } } break; case WIFI_PS_PARAM_LISTEN_INTERVAL: wlan_configure_listen_interval((int)params->listen_interval); break; case WIFI_PS_PARAM_WAKEUP_MODE: if (params->wakeup_mode == WIFI_PS_WAKEUP_MODE_DTIM) { wlan_configure_listen_interval(0); } break; case WIFI_PS_PARAM_MODE: if (params->mode == WIFI_PS_MODE_WMM) { ret = wlan_set_wmm_uapsd(1); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } } else if (params->mode == WIFI_PS_MODE_LEGACY) { ret = wlan_set_wmm_uapsd(0); if (ret != WM_SUCCESS) { status = NXP_WIFI_RET_FAIL; } } break; case WIFI_PS_PARAM_TIMEOUT: wlan_configure_delay_to_ps((int)params->timeout_ms); break; default: status = NXP_WIFI_RET_FAIL; break; } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_ERR("Failed to set Wi-Fi power save"); return -EAGAIN; } return 0; } int nxp_wifi_get_power_save(const struct device *dev, struct wifi_ps_config *config) { int status = NXP_WIFI_RET_SUCCESS; struct interface *if_handle = (struct interface *)dev->data; if (if_handle->state.interface != WLAN_BSS_TYPE_STA) { LOG_ERR("Wi-Fi not in station mode"); return -EIO; } if (s_nxp_wifi_State != NXP_WIFI_STARTED) { status = NXP_WIFI_RET_NOT_READY; } if (status == NXP_WIFI_RET_SUCCESS) { if (config) { if (wlan_is_power_save_enabled()) { config->ps_params.enabled = WIFI_PS_ENABLED; } else { config->ps_params.enabled = WIFI_PS_DISABLED; } config->ps_params.listen_interval = wlan_get_listen_interval(); config->ps_params.timeout_ms = wlan_get_delay_to_ps(); if (config->ps_params.listen_interval) { config->ps_params.wakeup_mode = WIFI_PS_WAKEUP_MODE_LISTEN_INTERVAL; } else { config->ps_params.wakeup_mode = WIFI_PS_WAKEUP_MODE_DTIM; } if (wlan_is_wmm_uapsd_enabled()) { config->ps_params.mode = WIFI_PS_MODE_WMM; } else { config->ps_params.mode = WIFI_PS_MODE_LEGACY; } } else { status = NXP_WIFI_RET_FAIL; } } if (status != NXP_WIFI_RET_SUCCESS) { LOG_ERR("Failed to get Wi-Fi power save config"); return -EAGAIN; } return 0; } static int nxp_wifi_reg_domain(const struct device *dev, struct wifi_reg_domain *reg_domain) { int ret; uint8_t index = 0; chan_freq_power_t *nxp_wifi_chan_freq_power = NULL; int nxp_wifi_cfp_no = 0; if (reg_domain->oper == WIFI_MGMT_GET) { nxp_wifi_chan_freq_power = (chan_freq_power_t *)wlan_get_regulatory_domain(0, &nxp_wifi_cfp_no); if (nxp_wifi_chan_freq_power != NULL) { for (int i = 0; i < nxp_wifi_cfp_no; i++) { reg_domain->chan_info[i].center_frequency = nxp_wifi_chan_freq_power[i].freq; reg_domain->chan_info[i].max_power = nxp_wifi_chan_freq_power[i].max_tx_power; reg_domain->chan_info[i].supported = 1; reg_domain->chan_info[i].passive_only = nxp_wifi_chan_freq_power[i].passive_scan_or_radar_detect; reg_domain->chan_info[i].dfs = nxp_wifi_chan_freq_power[i].passive_scan_or_radar_detect; } index = nxp_wifi_cfp_no; } nxp_wifi_chan_freq_power = (chan_freq_power_t *)wlan_get_regulatory_domain(1, &nxp_wifi_cfp_no); if (nxp_wifi_chan_freq_power != NULL) { for (int i = 0; i < nxp_wifi_cfp_no; i++) { reg_domain->chan_info[index + i].center_frequency = nxp_wifi_chan_freq_power[i].freq; reg_domain->chan_info[index + i].max_power = nxp_wifi_chan_freq_power[i].max_tx_power; reg_domain->chan_info[index + i].supported = 1; reg_domain->chan_info[index + i].passive_only = nxp_wifi_chan_freq_power[i].passive_scan_or_radar_detect; reg_domain->chan_info[index + i].dfs = nxp_wifi_chan_freq_power[i].passive_scan_or_radar_detect; } index += nxp_wifi_cfp_no; } reg_domain->num_channels = index; wifi_get_country_code(reg_domain->country_code); } else { if (is_uap_started()) { LOG_ERR("region code can not be set after uAP start!"); return -EAGAIN; } ret = wlan_set_country_code(reg_domain->country_code); if (ret != WM_SUCCESS) { LOG_ERR("Unable to set country code: %s", reg_domain->country_code); return -EAGAIN; } } return 0; } static int nxp_wifi_set_twt(const struct device *dev, struct wifi_twt_params *params) { wlan_twt_setup_config_t twt_setup_conf; wlan_twt_teardown_config_t teardown_conf; int ret = -1; if (params->negotiation_type == WIFI_TWT_INDIVIDUAL) { params->negotiation_type = 0; } else if (params->negotiation_type == WIFI_TWT_BROADCAST) { params->negotiation_type = 3; } if (params->operation == WIFI_TWT_SETUP) { twt_setup_conf.implicit = params->setup.implicit; twt_setup_conf.announced = params->setup.announce; twt_setup_conf.trigger_enabled = params->setup.trigger; twt_setup_conf.twt_info_disabled = params->setup.twt_info_disable; twt_setup_conf.negotiation_type = params->negotiation_type; twt_setup_conf.twt_wakeup_duration = params->setup.twt_wake_interval; twt_setup_conf.flow_identifier = params->flow_id; twt_setup_conf.hard_constraint = 1; twt_setup_conf.twt_exponent = params->setup.exponent; twt_setup_conf.twt_mantissa = params->setup.twt_interval; twt_setup_conf.twt_request = params->setup.responder; ret = wlan_set_twt_setup_cfg(&twt_setup_conf); } else if (params->operation == WIFI_TWT_TEARDOWN) { teardown_conf.flow_identifier = params->flow_id; teardown_conf.negotiation_type = params->negotiation_type; teardown_conf.teardown_all_twt = params->teardown.teardown_all; ret = wlan_set_twt_teardown_cfg(&teardown_conf); } return ret; } static int nxp_wifi_set_btwt(const struct device *dev, struct wifi_twt_params *params) { wlan_btwt_config_t btwt_config; int ret = -1; btwt_config.action = 1; btwt_config.sub_id = params->btwt.sub_id; btwt_config.nominal_wake = params->btwt.nominal_wake; btwt_config.max_sta_support = params->btwt.max_sta_support; btwt_config.twt_mantissa = params->btwt.twt_interval; btwt_config.twt_offset = params->btwt.twt_offset; btwt_config.twt_exponent = params->btwt.twt_exponent; btwt_config.sp_gap = params->btwt.sp_gap; ret = wlan_set_btwt_cfg(&btwt_config); return ret; } static void nxp_wifi_sta_init(struct net_if *iface) { const struct device *dev = net_if_get_device(iface); struct ethernet_context *eth_ctx = net_if_l2_data(iface); struct interface *intf = dev->data; eth_ctx->eth_if_type = L2_ETH_IF_TYPE_WIFI; intf->netif = iface; #ifdef CONFIG_WIFI_NM wifi_nm_register_mgd_type_iface(wifi_nm_get_instance("wifi_supplicant"), WIFI_TYPE_STA, iface); #endif g_mlan.state.interface = WLAN_BSS_TYPE_STA; #ifndef CONFIG_NXP_WIFI_SOFTAP_SUPPORT int ret; if (s_nxp_wifi_State == NXP_WIFI_NOT_INITIALIZED) { /* Initialize the wifi subsystem */ ret = nxp_wifi_wlan_init(); if (ret) { LOG_ERR("wlan initialization failed"); return; } ret = nxp_wifi_wlan_start(); if (ret) { LOG_ERR("wlan start failed"); return; } } #endif } #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT static void nxp_wifi_uap_init(struct net_if *iface) { const struct device *dev = net_if_get_device(iface); struct ethernet_context *eth_ctx = net_if_l2_data(iface); struct interface *intf = dev->data; int ret; eth_ctx->eth_if_type = L2_ETH_IF_TYPE_WIFI; intf->netif = iface; #ifdef CONFIG_WIFI_NM wifi_nm_register_mgd_type_iface(wifi_nm_get_instance("hostapd"), WIFI_TYPE_SAP, iface); #endif g_uap.state.interface = WLAN_BSS_TYPE_UAP; if (s_nxp_wifi_State == NXP_WIFI_NOT_INITIALIZED) { /* Initialize the wifi subsystem */ ret = nxp_wifi_wlan_init(); if (ret) { LOG_ERR("wlan initialization failed"); return; } ret = nxp_wifi_wlan_start(); if (ret) { LOG_ERR("wlan start failed"); return; } } } #endif static NXP_WIFI_SET_FUNC_ATTR int nxp_wifi_send(const struct device *dev, struct net_pkt *pkt) { #if defined(CONFIG_NET_STATISTICS_WIFI) struct interface *if_handle = (struct interface *)dev->data; const int pkt_len = net_pkt_get_len(pkt); struct net_eth_hdr *hdr = NET_ETH_HDR(pkt); #endif /* Enqueue packet for transmission */ if (nxp_wifi_internal_tx(dev, pkt) != WM_SUCCESS) { goto out; } #if defined(CONFIG_NET_STATISTICS_WIFI) if_handle->stats.bytes.sent += pkt_len; if_handle->stats.pkts.tx++; if (net_eth_is_addr_multicast(&hdr->dst)) { if_handle->stats.multicast.tx++; } else if (net_eth_is_addr_broadcast(&hdr->dst)) { if_handle->stats.broadcast.tx++; } #endif return 0; out: #if defined(CONFIG_NET_STATISTICS_WIFI) if_handle->stats.errors.tx++; #endif return -EIO; } static NXP_WIFI_SET_FUNC_ATTR int nxp_wifi_recv(struct net_if *iface, struct net_pkt *pkt) { #if defined(CONFIG_NET_STATISTICS_WIFI) struct interface *if_handle = (struct interface *)(net_if_get_device(iface)->data); const int pkt_len = net_pkt_get_len(pkt); struct net_eth_hdr *hdr = NET_ETH_HDR(pkt); #endif if (net_recv_data(iface, pkt) < 0) { goto out; } #if defined(CONFIG_NET_STATISTICS_WIFI) if (net_eth_is_addr_broadcast(&hdr->dst)) { if_handle->stats.broadcast.rx++; } else if (net_eth_is_addr_multicast(&hdr->dst)) { if_handle->stats.multicast.rx++; } if_handle->stats.bytes.received += pkt_len; if_handle->stats.pkts.rx++; #endif return 0; out: #if defined(CONFIG_NET_STATISTICS_WIFI) if_handle->stats.errors.rx++; #endif return -EIO; } #ifdef CONFIG_NXP_RW610 extern void WL_MCI_WAKEUP0_DriverIRQHandler(void); extern void WL_MCI_WAKEUP_DONE0_DriverIRQHandler(void); #endif static int nxp_wifi_dev_init(const struct device *dev) { struct nxp_wifi_dev *nxp_wifi = &nxp_wifi0; k_mutex_init(&nxp_wifi->mutex); nxp_wifi_shell_register(nxp_wifi); #ifdef CONFIG_NXP_RW610 IRQ_CONNECT(IMU_IRQ_N, IMU_IRQ_P, WL_MCI_WAKEUP0_DriverIRQHandler, 0, 0); irq_enable(IMU_IRQ_N); IRQ_CONNECT(IMU_WAKEUP_IRQ_N, IMU_WAKEUP_IRQ_P, WL_MCI_WAKEUP_DONE0_DriverIRQHandler, 0, 0); irq_enable(IMU_WAKEUP_IRQ_N); #if (DT_INST_PROP(0, wakeup_source)) EnableDeepSleepIRQ(IMU_IRQ_N); #endif #endif return 0; } static int nxp_wifi_set_config(const struct device *dev, enum ethernet_config_type type, const struct ethernet_config *config) { struct interface *if_handle = (struct interface *)dev->data; switch (type) { case ETHERNET_CONFIG_TYPE_MAC_ADDRESS: memcpy(if_handle->mac_address, config->mac_address.addr, 6); net_if_set_link_addr(if_handle->netif, if_handle->mac_address, sizeof(if_handle->mac_address), NET_LINK_ETHERNET); if (if_handle->state.interface == WLAN_BSS_TYPE_STA) { if (wlan_set_sta_mac_addr(if_handle->mac_address)) { LOG_ERR("Failed to set Wi-Fi MAC Address"); return -ENOEXEC; } #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT } else if (if_handle->state.interface == WLAN_BSS_TYPE_UAP) { if (wlan_set_uap_mac_addr(if_handle->mac_address)) { LOG_ERR("Failed to set Wi-Fi MAC Address"); return -ENOEXEC; } #endif } else { LOG_ERR("Invalid Interface index"); return -ENOEXEC; } break; default: return -ENOTSUP; } return 0; } #if defined(CONFIG_PM_DEVICE) && defined(CONFIG_NXP_RW610) void device_pm_dump_wakeup_source(void) { if (POWER_GetWakeupStatus(IMU_IRQ_N)) { LOG_INF("Wakeup by WLAN"); POWER_ClearWakeupStatus(IMU_IRQ_N); } else if (POWER_GetWakeupStatus(41)) { LOG_INF("Wakeup by OSTIMER"); POWER_ClearWakeupStatus(41); } else if (POWER_GetWakeupStatus(32)) { LOG_INF("Wakeup by RTC"); POWER_ClearWakeupStatus(32); } } static int device_wlan_pm_action(const struct device *dev, enum pm_device_action pm_action) { int ret = 0; switch (pm_action) { case PM_DEVICE_ACTION_SUSPEND: if (!wlan_host_sleep_state || !wlan_is_started() || wakelock_isheld() #ifdef CONFIG_NXP_WIFI_WMM_UAPSD || wlan_is_wmm_uapsd_enabled() #endif ) return -EBUSY; /* * Trigger host sleep handshake here. Before handshake is done, host is not allowed * to enter low power mode */ if (!is_hs_handshake_done) { is_hs_handshake_done = WLAN_HOSTSLEEP_IN_PROCESS; ret = wlan_hs_send_event(HOST_SLEEP_HANDSHAKE, NULL); if (ret != 0) { return -EFAULT; } return -EBUSY; } if (is_hs_handshake_done == WLAN_HOSTSLEEP_IN_PROCESS) { return -EBUSY; } if (is_hs_handshake_done == WLAN_HOSTSLEEP_FAIL) { is_hs_handshake_done = 0; return -EFAULT; } break; case PM_DEVICE_ACTION_RESUME: /* * Cancel host sleep in firmware and dump wakekup source. * If sleep state is periodic, start timer to keep host in full power state for 5s. * User can use this time to issue other commands. */ if (is_hs_handshake_done == WLAN_HOSTSLEEP_SUCCESS) { ret = wlan_hs_send_event(HOST_SLEEP_EXIT, NULL); if (ret != 0) { return -EFAULT; } device_pm_dump_wakeup_source(); /* reset hs hanshake flag after waking up */ is_hs_handshake_done = 0; if (wlan_host_sleep_state == HOST_SLEEP_ONESHOT) { wlan_host_sleep_state = HOST_SLEEP_DISABLE; } } break; default: break; } return ret; } PM_DEVICE_DT_INST_DEFINE(0, device_wlan_pm_action); #endif static const struct wifi_mgmt_ops nxp_wifi_sta_mgmt = { .get_version = nxp_wifi_version, .scan = nxp_wifi_scan, .connect = nxp_wifi_connect, .disconnect = nxp_wifi_disconnect, .reg_domain = nxp_wifi_reg_domain, #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT .ap_enable = nxp_wifi_start_ap, .ap_bandwidth = nxp_wifi_ap_bandwidth, .ap_disable = nxp_wifi_stop_ap, #endif .iface_status = nxp_wifi_status, #if defined(CONFIG_NET_STATISTICS_WIFI) .get_stats = nxp_wifi_stats, #endif .set_power_save = nxp_wifi_power_save, .get_power_save_config = nxp_wifi_get_power_save, .set_twt = nxp_wifi_set_twt, }; #if defined(CONFIG_WIFI_NM_WPA_SUPPLICANT) static const struct zep_wpa_supp_dev_ops nxp_wifi_drv_ops = { .init = wifi_nxp_wpa_supp_dev_init, .deinit = wifi_nxp_wpa_supp_dev_deinit, .scan2 = wifi_nxp_wpa_supp_scan2, .scan_abort = wifi_nxp_wpa_supp_scan_abort, .get_scan_results2 = wifi_nxp_wpa_supp_scan_results_get, .deauthenticate = wifi_nxp_wpa_supp_deauthenticate, .authenticate = wifi_nxp_wpa_supp_authenticate, .associate = wifi_nxp_wpa_supp_associate, .set_key = wifi_nxp_wpa_supp_set_key, .set_supp_port = wifi_nxp_wpa_supp_set_supp_port, .signal_poll = wifi_nxp_wpa_supp_signal_poll, .send_mlme = wifi_nxp_wpa_supp_send_mlme, .get_wiphy = wifi_nxp_wpa_supp_get_wiphy, .get_capa = wifi_nxp_wpa_supp_get_capa, .get_conn_info = wifi_nxp_wpa_supp_get_conn_info, .set_country = wifi_nxp_wpa_supp_set_country, .get_country = wifi_nxp_wpa_supp_get_country, #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT #ifdef CONFIG_WIFI_NM_WPA_SUPPLICANT .hapd_init = wifi_nxp_hostapd_dev_init, .hapd_deinit = wifi_nxp_hostapd_dev_deinit, #endif .init_ap = wifi_nxp_wpa_supp_init_ap, .set_ap = wifi_nxp_hostapd_set_ap, .stop_ap = wifi_nxp_hostapd_stop_ap, .sta_remove = wifi_nxp_hostapd_sta_remove, .sta_add = wifi_nxp_hostapd_sta_add, .do_acs = wifi_nxp_hostapd_do_acs, #endif .dpp_listen = wifi_nxp_wpa_dpp_listen, .remain_on_channel = wifi_nxp_wpa_supp_remain_on_channel, .cancel_remain_on_channel = wifi_nxp_wpa_supp_cancel_remain_on_channel, }; #endif static const struct net_wifi_mgmt_offload nxp_wifi_sta_apis = { .wifi_iface.iface_api.init = nxp_wifi_sta_init, .wifi_iface.set_config = nxp_wifi_set_config, .wifi_iface.send = nxp_wifi_send, .wifi_mgmt_api = &nxp_wifi_sta_mgmt, #if defined(CONFIG_WIFI_NM_WPA_SUPPLICANT) .wifi_drv_ops = &nxp_wifi_drv_ops, #endif }; NET_DEVICE_INIT_INSTANCE(wifi_nxp_sta, "ml", 0, nxp_wifi_dev_init, PM_DEVICE_DT_INST_GET(0), &g_mlan, #ifdef CONFIG_WIFI_NM_WPA_SUPPLICANT &wpa_supp_ops, #else NULL, #endif CONFIG_WIFI_INIT_PRIORITY, &nxp_wifi_sta_apis, ETHERNET_L2, NET_L2_GET_CTX_TYPE(ETHERNET_L2), NET_ETH_MTU); #ifdef CONFIG_NXP_WIFI_SOFTAP_SUPPORT static const struct wifi_mgmt_ops nxp_wifi_uap_mgmt = { .ap_enable = nxp_wifi_start_ap, .ap_disable = nxp_wifi_stop_ap, .iface_status = nxp_wifi_status, #if defined(CONFIG_NET_STATISTICS_WIFI) .get_stats = nxp_wifi_stats, #endif .set_power_save = nxp_wifi_power_save, .get_power_save_config = nxp_wifi_get_power_save, .set_btwt = nxp_wifi_set_btwt, .ap_bandwidth = nxp_wifi_ap_bandwidth, }; static const struct net_wifi_mgmt_offload nxp_wifi_uap_apis = { .wifi_iface.iface_api.init = nxp_wifi_uap_init, .wifi_iface.set_config = nxp_wifi_set_config, .wifi_iface.send = nxp_wifi_send, .wifi_mgmt_api = &nxp_wifi_uap_mgmt, #if defined(CONFIG_WIFI_NM_WPA_SUPPLICANT) .wifi_drv_ops = &nxp_wifi_drv_ops, #endif }; NET_DEVICE_INIT_INSTANCE(wifi_nxp_uap, "ua", 1, NULL, NULL, &g_uap, #ifdef CONFIG_WIFI_NM_WPA_SUPPLICANT &wpa_supp_ops, #else NULL, #endif CONFIG_WIFI_INIT_PRIORITY, &nxp_wifi_uap_apis, ETHERNET_L2, NET_L2_GET_CTX_TYPE(ETHERNET_L2), NET_ETH_MTU); #endif ```
/content/code_sandbox/drivers/wifi/nxp/nxp_wifi_drv.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
14,638
```c /** * */ #define LOG_MODULE_NAME wifi_winc1500 #define LOG_LEVEL CONFIG_WIFI_LOG_LEVEL #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(LOG_MODULE_NAME); #include <zephyr/kernel.h> #include <zephyr/debug/stack.h> #include <zephyr/device.h> #include <string.h> #include <errno.h> #include <zephyr/net/net_pkt.h> #include <zephyr/net/net_if.h> #include <zephyr/net/net_l2.h> #include <zephyr/net/net_context.h> #include <zephyr/net/net_offload.h> #include <zephyr/net/wifi_mgmt.h> #include <zephyr/net/conn_mgr/connectivity_wifi_mgmt.h> #include <zephyr/sys/printk.h> /* We do not need <socket/include/socket.h> * It seems there is a bug in ASF side: if OS is already defining sockaddr * and all, ASF will not need to define it. Unfortunately its socket.h does * but also defines some NM API functions there (??), so we need to redefine * those here. */ #define __SOCKET_H__ #define HOSTNAME_MAX_SIZE (64) #include <driver/include/m2m_wifi.h> #include <socket/include/m2m_socket_host_if.h> NMI_API void socketInit(void); typedef void (*tpfAppSocketCb) (SOCKET sock, uint8 u8Msg, void *pvMsg); typedef void (*tpfAppResolveCb) (uint8 *pu8DomainName, uint32 u32ServerIP); NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); NMI_API sint8 listen(SOCKET sock, uint8 backlog); NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); NMI_API sint8 winc1500_close(SOCKET sock); enum socket_errors { SOCK_ERR_NO_ERROR = 0, SOCK_ERR_INVALID_ADDRESS = -1, SOCK_ERR_ADDR_ALREADY_IN_USE = -2, SOCK_ERR_MAX_TCP_SOCK = -3, SOCK_ERR_MAX_UDP_SOCK = -4, SOCK_ERR_INVALID_ARG = -6, SOCK_ERR_MAX_LISTEN_SOCK = -7, SOCK_ERR_INVALID = -9, SOCK_ERR_ADDR_IS_REQUIRED = -11, SOCK_ERR_CONN_ABORTED = -12, SOCK_ERR_TIMEOUT = -13, SOCK_ERR_BUFFER_FULL = -14, }; enum socket_messages { SOCKET_MSG_BIND = 1, SOCKET_MSG_LISTEN, SOCKET_MSG_DNS_RESOLVE, SOCKET_MSG_ACCEPT, SOCKET_MSG_CONNECT, SOCKET_MSG_RECV, SOCKET_MSG_SEND, SOCKET_MSG_SENDTO, SOCKET_MSG_RECVFROM, }; typedef struct { sint8 status; } tstrSocketBindMsg; typedef struct { sint8 status; } tstrSocketListenMsg; typedef struct { SOCKET sock; struct sockaddr_in strAddr; } tstrSocketAcceptMsg; typedef struct { SOCKET sock; sint8 s8Error; } tstrSocketConnectMsg; typedef struct { uint8 *pu8Buffer; sint16 s16BufferSize; uint16 u16RemainingSize; struct sockaddr_in strRemoteAddr; } tstrSocketRecvMsg; #include <driver/include/m2m_wifi.h> #include <socket/include/m2m_socket_host_if.h> #if defined(CONFIG_WIFI_WINC1500_REGION_NORTH_AMERICA) #define WINC1500_REGION NORTH_AMERICA #elif defined(CONFIG_WIFI_WINC1500_REGION_EUROPE) #define WINC1500_REGION EUROPE #elif defined(CONFIG_WIFI_WINC1500_REGION_ASIA) #define WINC1500_REGION ASIA #endif #define WINC1500_BIND_TIMEOUT K_MSEC(500) #define WINC1500_LISTEN_TIMEOUT K_MSEC(500) #define WINC1500_BUF_TIMEOUT K_MSEC(100) NET_BUF_POOL_DEFINE(winc1500_tx_pool, CONFIG_WIFI_WINC1500_BUF_CTR, CONFIG_WIFI_WINC1500_MAX_PACKET_SIZE, 0, NULL); NET_BUF_POOL_DEFINE(winc1500_rx_pool, CONFIG_WIFI_WINC1500_BUF_CTR, CONFIG_WIFI_WINC1500_MAX_PACKET_SIZE, 0, NULL); K_KERNEL_STACK_MEMBER(winc1500_stack, CONFIG_WIFI_WINC1500_THREAD_STACK_SIZE); struct k_thread winc1500_thread_data; struct socket_data { struct net_context *context; net_context_connect_cb_t connect_cb; net_tcp_accept_cb_t accept_cb; net_context_recv_cb_t recv_cb; void *connect_user_data; void *recv_user_data; void *accept_user_data; struct net_pkt *rx_pkt; struct net_buf *pkt_buf; int ret_code; struct k_sem wait_sem; }; struct winc1500_data { struct socket_data socket_data[ CONFIG_WIFI_WINC1500_OFFLOAD_MAX_SOCKETS]; struct net_if *iface; unsigned char mac[6]; scan_result_cb_t scan_cb; uint8_t scan_result; bool connecting; bool connected; }; static struct winc1500_data w1500_data; #if LOG_LEVEL > LOG_LEVEL_OFF static void stack_stats(void) { log_stack_usage(&winc1500_thread_data); } #endif /* LOG_LEVEL > LOG_LEVEL_OFF */ static char *socket_error_string(int8_t err) { switch (err) { case SOCK_ERR_NO_ERROR: return "Successful socket operation"; case SOCK_ERR_INVALID_ADDRESS: return "Socket address is invalid." "The socket operation cannot be completed successfully" " without specifying a specific address. " "For example: bind is called without specifying" " a port number"; case SOCK_ERR_ADDR_ALREADY_IN_USE: return "Socket operation cannot bind on the given address." " With socket operations, only one IP address per " "socket is permitted. Any attempt for a new socket " "to bind with an IP address already bound to another " "open socket, will return the following error code. " "States that bind operation failed."; case SOCK_ERR_MAX_TCP_SOCK: return "Exceeded the maximum number of TCP sockets." "A maximum number of TCP sockets opened simultaneously" " is defined through TCP_SOCK_MAX. It is not permitted" " to exceed that number at socket creation." " Identifies that @ref socket operation failed."; case SOCK_ERR_MAX_UDP_SOCK: return "Exceeded the maximum number of UDP sockets." "A maximum number of UDP sockets opened simultaneously" " is defined through UDP_SOCK_MAX. It is not permitted" " to exceed that number at socket creation." " Identifies that socket operation failed"; case SOCK_ERR_INVALID_ARG: return "An invalid argument is passed to a function."; case SOCK_ERR_MAX_LISTEN_SOCK: return "Exceeded the maximum number of TCP passive listening " "sockets. Identifies Identifies that listen operation" " failed."; case SOCK_ERR_INVALID: return "The requested socket operation is not valid in the " "current socket state. For example: @ref accept is " "called on a TCP socket before bind or listen."; case SOCK_ERR_ADDR_IS_REQUIRED: return "Destination address is required. Failure to provide " "the socket address required for the socket operation " "to be completed. It is generated as an error to the " "sendto function when the address required to send the" " data to is not known."; case SOCK_ERR_CONN_ABORTED: return "The socket is closed by the peer. The local socket is " "also closed."; case SOCK_ERR_TIMEOUT: return "The socket pending operation has timedout."; case SOCK_ERR_BUFFER_FULL: return "No buffer space available to be used for the requested" " socket operation."; default: return "Unknown"; } } static char *wifi_cb_msg_2_str(uint8_t message_type) { switch (message_type) { case M2M_WIFI_RESP_CURRENT_RSSI: return "M2M_WIFI_RESP_CURRENT_RSSI"; case M2M_WIFI_REQ_WPS: return "M2M_WIFI_REQ_WPS"; case M2M_WIFI_RESP_IP_CONFIGURED: return "M2M_WIFI_RESP_IP_CONFIGURED"; case M2M_WIFI_RESP_IP_CONFLICT: return "M2M_WIFI_RESP_IP_CONFLICT"; case M2M_WIFI_RESP_CLIENT_INFO: return "M2M_WIFI_RESP_CLIENT_INFO"; case M2M_WIFI_RESP_GET_SYS_TIME: return "M2M_WIFI_RESP_GET_SYS_TIME"; case M2M_WIFI_REQ_SEND_ETHERNET_PACKET: return "M2M_WIFI_REQ_SEND_ETHERNET_PACKET"; case M2M_WIFI_RESP_ETHERNET_RX_PACKET: return "M2M_WIFI_RESP_ETHERNET_RX_PACKET"; case M2M_WIFI_RESP_CON_STATE_CHANGED: return "M2M_WIFI_RESP_CON_STATE_CHANGED"; case M2M_WIFI_REQ_DHCP_CONF: return "Response indicating that IP address was obtained."; case M2M_WIFI_RESP_SCAN_DONE: return "M2M_WIFI_RESP_SCAN_DONE"; case M2M_WIFI_RESP_SCAN_RESULT: return "M2M_WIFI_RESP_SCAN_RESULT"; case M2M_WIFI_RESP_PROVISION_INFO: return "M2M_WIFI_RESP_PROVISION_INFO"; default: return "UNKNOWN"; } } static char *socket_message_to_string(uint8_t message) { switch (message) { case SOCKET_MSG_BIND: return "Bind socket event."; case SOCKET_MSG_LISTEN: return "Listen socket event."; case SOCKET_MSG_DNS_RESOLVE: return "DNS Resolution event."; case SOCKET_MSG_ACCEPT: return "Accept socket event."; case SOCKET_MSG_CONNECT: return "Connect socket event."; case SOCKET_MSG_RECV: return "Receive socket event."; case SOCKET_MSG_SEND: return "Send socket event."; case SOCKET_MSG_SENDTO: return "Sendto socket event."; case SOCKET_MSG_RECVFROM: return "Recvfrom socket event."; default: return "UNKNOWN."; } } /** * This function is called when the socket is to be opened. */ static int winc1500_get(sa_family_t family, enum net_sock_type type, enum net_ip_protocol ip_proto, struct net_context **context) { struct socket_data *sd; SOCKET sock; if (family != AF_INET) { LOG_ERR("Only AF_INET is supported!"); return -1; } /* winc1500 atmel uses AF_INET 2 instead of zephyrs AF_INET 1 * we have checked if family is AF_INET so we can hardcode this * for now. */ sock = socket(2, type, 0); if (sock < 0) { LOG_ERR("socket error!"); return -1; } (*context)->offload_context = (void *)(intptr_t)sock; sd = &w1500_data.socket_data[sock]; k_sem_init(&sd->wait_sem, 0, 1); sd->context = *context; return 0; } /** * This function is called when user wants to bind to local IP address. */ static int winc1500_bind(struct net_context *context, const struct sockaddr *addr, socklen_t addrlen) { SOCKET socket = (int)context->offload_context; int ret; /* FIXME atmel winc1500 don't support bind on null port */ if (net_sin(addr)->sin_port == 0U) { return 0; } ret = bind((int)context->offload_context, (struct sockaddr *)addr, addrlen); if (ret) { LOG_ERR("bind error %d %s!", ret, socket_message_to_string(ret)); return ret; } if (k_sem_take(&w1500_data.socket_data[socket].wait_sem, WINC1500_BIND_TIMEOUT)) { LOG_ERR("bind error timeout expired"); return -ETIMEDOUT; } return w1500_data.socket_data[socket].ret_code; } /** * This function is called when user wants to mark the socket * to be a listening one. */ static int winc1500_listen(struct net_context *context, int backlog) { SOCKET socket = (int)context->offload_context; int ret; ret = listen((int)context->offload_context, backlog); if (ret) { LOG_ERR("listen error %d %s!", ret, socket_error_string(ret)); return ret; } if (k_sem_take(&w1500_data.socket_data[socket].wait_sem, WINC1500_LISTEN_TIMEOUT)) { return -ETIMEDOUT; } return w1500_data.socket_data[socket].ret_code; } /** * This function is called when user wants to create a connection * to a peer host. */ static int winc1500_connect(struct net_context *context, const struct sockaddr *addr, socklen_t addrlen, net_context_connect_cb_t cb, int32_t timeout, void *user_data) { SOCKET socket = (int)context->offload_context; int ret; w1500_data.socket_data[socket].connect_cb = cb; w1500_data.socket_data[socket].connect_user_data = user_data; w1500_data.socket_data[socket].ret_code = 0; ret = connect(socket, (struct sockaddr *)addr, addrlen); if (ret) { LOG_ERR("connect error %d %s!", ret, socket_error_string(ret)); return ret; } if (timeout != 0 && k_sem_take(&w1500_data.socket_data[socket].wait_sem, K_MSEC(timeout))) { return -ETIMEDOUT; } return w1500_data.socket_data[socket].ret_code; } /** * This function is called when user wants to accept a connection * being established. */ static int winc1500_accept(struct net_context *context, net_tcp_accept_cb_t cb, int32_t timeout, void *user_data) { SOCKET socket = (int)context->offload_context; int ret; w1500_data.socket_data[socket].accept_cb = cb; w1500_data.socket_data[socket].accept_user_data = user_data; ret = accept(socket, NULL, 0); if (ret) { LOG_ERR("accept error %d %s!", ret, socket_error_string(ret)); return ret; } if (timeout) { if (k_sem_take(&w1500_data.socket_data[socket].wait_sem, K_MSEC(timeout))) { return -ETIMEDOUT; } } return w1500_data.socket_data[socket].ret_code; } /** * This function is called when user wants to send data to peer host. */ static int winc1500_send(struct net_pkt *pkt, net_context_send_cb_t cb, int32_t timeout, void *user_data) { struct net_context *context = pkt->context; SOCKET socket = (int)context->offload_context; int ret = 0; struct net_buf *buf; buf = net_buf_alloc(&winc1500_tx_pool, WINC1500_BUF_TIMEOUT); if (!buf) { return -ENOBUFS; } if (net_pkt_read(pkt, buf->data, net_pkt_get_len(pkt))) { ret = -ENOBUFS; goto out; } net_buf_add(buf, net_pkt_get_len(pkt)); ret = send(socket, buf->data, buf->len, 0); if (ret) { LOG_ERR("send error %d %s!", ret, socket_error_string(ret)); goto out; } net_pkt_unref(pkt); out: net_buf_unref(buf); return ret; } /** * This function is called when user wants to send data to peer host. */ static int winc1500_sendto(struct net_pkt *pkt, const struct sockaddr *dst_addr, socklen_t addrlen, net_context_send_cb_t cb, int32_t timeout, void *user_data) { struct net_context *context = pkt->context; SOCKET socket = (int)context->offload_context; int ret = 0; struct net_buf *buf; buf = net_buf_alloc(&winc1500_tx_pool, WINC1500_BUF_TIMEOUT); if (!buf) { return -ENOBUFS; } if (net_pkt_read(pkt, buf->data, net_pkt_get_len(pkt))) { ret = -ENOBUFS; goto out; } net_buf_add(buf, net_pkt_get_len(pkt)); ret = sendto(socket, buf->data, buf->len, 0, (struct sockaddr *)dst_addr, addrlen); if (ret) { LOG_ERR("sendto error %d %s!", ret, socket_error_string(ret)); goto out; } net_pkt_unref(pkt); out: net_buf_unref(buf); return ret; } /** */ static int prepare_pkt(struct socket_data *sock_data) { /* Get the frame from the buffer */ sock_data->rx_pkt = net_pkt_rx_alloc_on_iface(w1500_data.iface, K_NO_WAIT); if (!sock_data->rx_pkt) { LOG_ERR("Could not allocate rx packet"); return -1; } /* Reserve a data buffer to receive the frame */ sock_data->pkt_buf = net_buf_alloc(&winc1500_rx_pool, K_NO_WAIT); if (!sock_data->pkt_buf) { LOG_ERR("Could not allocate data buffer"); net_pkt_unref(sock_data->rx_pkt); return -1; } net_pkt_append_buffer(sock_data->rx_pkt, sock_data->pkt_buf); return 0; } /** * This function is called when user wants to receive data from peer * host. */ static int winc1500_recv(struct net_context *context, net_context_recv_cb_t cb, int32_t timeout, void *user_data) { SOCKET socket = (int) context->offload_context; int ret; w1500_data.socket_data[socket].recv_cb = cb; w1500_data.socket_data[socket].recv_user_data = user_data; if (!cb) { return 0; } ret = prepare_pkt(&w1500_data.socket_data[socket]); if (ret) { LOG_ERR("Could not reserve packet buffer"); return -ENOMEM; } ret = recv(socket, w1500_data.socket_data[socket].pkt_buf->data, CONFIG_WIFI_WINC1500_MAX_PACKET_SIZE, timeout); if (ret) { LOG_ERR("recv error %d %s!", ret, socket_error_string(ret)); return ret; } return 0; } /** * This function is called when user wants to close the socket. */ static int winc1500_put(struct net_context *context) { SOCKET sock = (int) context->offload_context; struct socket_data *sd = &w1500_data.socket_data[sock]; int ret; memset(&(context->remote), 0, sizeof(struct sockaddr_in)); context->flags &= ~NET_CONTEXT_REMOTE_ADDR_SET; ret = winc1500_close(sock); net_pkt_unref(sd->rx_pkt); memset(sd, 0, sizeof(struct socket_data)); return ret; } static struct net_offload winc1500_offload = { .get = winc1500_get, .bind = winc1500_bind, .listen = winc1500_listen, .connect = winc1500_connect, .accept = winc1500_accept, .send = winc1500_send, .sendto = winc1500_sendto, .recv = winc1500_recv, .put = winc1500_put, }; static void handle_wifi_con_state_changed(void *pvMsg) { tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged *)pvMsg; switch (pstrWifiState->u8CurrState) { case M2M_WIFI_DISCONNECTED: LOG_DBG("Disconnected (%u)", pstrWifiState->u8ErrCode); if (w1500_data.connecting) { wifi_mgmt_raise_connect_result_event(w1500_data.iface, pstrWifiState->u8ErrCode ? -EIO : 0); w1500_data.connecting = false; break; } w1500_data.connected = false; wifi_mgmt_raise_disconnect_result_event(w1500_data.iface, 0); break; case M2M_WIFI_CONNECTED: LOG_DBG("Connected (%u)", pstrWifiState->u8ErrCode); w1500_data.connected = true; w1500_data.connecting = false; wifi_mgmt_raise_connect_result_event(w1500_data.iface, 0); break; case M2M_WIFI_UNDEF: /* TODO status undefined*/ LOG_DBG("Undefined?"); break; } } static void handle_wifi_dhcp_conf(void *pvMsg) { uint8_t *pu8IPAddress = (uint8_t *)pvMsg; struct in_addr addr; uint8_t i; /* Connected and got IP address*/ LOG_DBG("Wi-Fi connected, IP is %u.%u.%u.%u", pu8IPAddress[0], pu8IPAddress[1], pu8IPAddress[2], pu8IPAddress[3]); /* TODO at this point the standby mode should be enable * status = WiFi connected IP assigned */ for (i = 0U; i < 4; i++) { addr.s4_addr[i] = pu8IPAddress[i]; } /* TODO fill in net mask, gateway and lease time */ net_if_ipv4_addr_add(w1500_data.iface, &addr, NET_ADDR_DHCP, 0); } static void reset_scan_data(void) { w1500_data.scan_cb = NULL; w1500_data.scan_result = 0U; } static void handle_scan_result(void *pvMsg) { tstrM2mWifiscanResult *pstrScanResult = (tstrM2mWifiscanResult *)pvMsg; struct wifi_scan_result result; if (!w1500_data.scan_cb) { return; } if (pstrScanResult->u8AuthType == M2M_WIFI_SEC_OPEN) { result.security = WIFI_SECURITY_TYPE_NONE; } else if (pstrScanResult->u8AuthType == M2M_WIFI_SEC_WPA_PSK) { result.security = WIFI_SECURITY_TYPE_PSK; } else { LOG_DBG("Security %u not supported", pstrScanResult->u8AuthType); goto out; } memcpy(result.ssid, pstrScanResult->au8SSID, WIFI_SSID_MAX_LEN); result.ssid_length = strlen(result.ssid); result.channel = pstrScanResult->u8ch; result.rssi = pstrScanResult->s8rssi; w1500_data.scan_cb(w1500_data.iface, 0, &result); k_yield(); out: if (w1500_data.scan_result < m2m_wifi_get_num_ap_found()) { m2m_wifi_req_scan_result(w1500_data.scan_result); w1500_data.scan_result++; } else { w1500_data.scan_cb(w1500_data.iface, 0, NULL); reset_scan_data(); } } static void handle_scan_done(void *pvMsg) { tstrM2mScanDone *pstrInfo = (tstrM2mScanDone *)pvMsg; if (!w1500_data.scan_cb) { return; } if (pstrInfo->s8ScanState != M2M_SUCCESS) { w1500_data.scan_cb(w1500_data.iface, -EIO, NULL); reset_scan_data(); LOG_ERR("Scan failed."); return; } w1500_data.scan_result = 0U; if (pstrInfo->u8NumofCh >= 1) { LOG_DBG("Requesting results (%u)", m2m_wifi_get_num_ap_found()); m2m_wifi_req_scan_result(w1500_data.scan_result); w1500_data.scan_result++; } else { LOG_DBG("No AP found"); w1500_data.scan_cb(w1500_data.iface, 0, NULL); reset_scan_data(); } } static void winc1500_wifi_cb(uint8_t message_type, void *pvMsg) { LOG_DBG("Msg Type %d %s", message_type, wifi_cb_msg_2_str(message_type)); switch (message_type) { case M2M_WIFI_RESP_CON_STATE_CHANGED: handle_wifi_con_state_changed(pvMsg); break; case M2M_WIFI_REQ_DHCP_CONF: handle_wifi_dhcp_conf(pvMsg); break; case M2M_WIFI_RESP_SCAN_RESULT: handle_scan_result(pvMsg); break; case M2M_WIFI_RESP_SCAN_DONE: handle_scan_done(pvMsg); break; default: break; } #if LOG_LEVEL > LOG_LEVEL_OFF stack_stats(); #endif /* LOG_LEVEL > LOG_LEVEL_OFF */ } static void handle_socket_msg_connect(struct socket_data *sd, void *pvMsg) { tstrSocketConnectMsg *strConnMsg = (tstrSocketConnectMsg *)pvMsg; LOG_ERR("CONNECT: socket %d error %d", strConnMsg->sock, strConnMsg->s8Error); if (!strConnMsg->s8Error) { net_context_set_state(sd->context, NET_CONTEXT_CONNECTED); } if (sd->connect_cb) { sd->connect_cb(sd->context, strConnMsg->s8Error, sd->connect_user_data); } sd->ret_code = strConnMsg->s8Error; } static bool handle_socket_msg_recv(SOCKET sock, struct socket_data *sd, void *pvMsg) { tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg *)pvMsg; if ((pstrRx->pu8Buffer != NULL) && (pstrRx->s16BufferSize > 0)) { net_buf_add(sd->pkt_buf, pstrRx->s16BufferSize); net_pkt_cursor_init(sd->rx_pkt); if (sd->recv_cb) { sd->recv_cb(sd->context, sd->rx_pkt, NULL, NULL, 0, sd->recv_user_data); } } else if (pstrRx->pu8Buffer == NULL) { if (pstrRx->s16BufferSize == SOCK_ERR_CONN_ABORTED) { net_pkt_unref(sd->rx_pkt); return false; } } return true; } static void handle_socket_msg_bind(struct socket_data *sd, void *pvMsg) { tstrSocketBindMsg *bind_msg = (tstrSocketBindMsg *)pvMsg; /* Holding a value of ZERO for a successful bind or otherwise * a negative error code corresponding to the type of error. */ if (bind_msg->status) { LOG_ERR("BIND: error %d %s", bind_msg->status, socket_message_to_string(bind_msg->status)); sd->ret_code = bind_msg->status; } } static void handle_socket_msg_listen(struct socket_data *sd, void *pvMsg) { tstrSocketListenMsg *listen_msg = (tstrSocketListenMsg *)pvMsg; /* Holding a value of ZERO for a successful listen or otherwise * a negative error code corresponding to the type of error. */ if (listen_msg->status) { LOG_ERR("winc1500_socket_cb:LISTEN: error %d %s", listen_msg->status, socket_message_to_string(listen_msg->status)); sd->ret_code = listen_msg->status; } } static void handle_socket_msg_accept(struct socket_data *sd, void *pvMsg) { tstrSocketAcceptMsg *accept_msg = (tstrSocketAcceptMsg *)pvMsg; /* On a successful accept operation, the return information is * the socket ID for the accepted connection with the remote peer. * Otherwise a negative error code is returned to indicate failure * of the accept operation. */ LOG_DBG("ACCEPT: from %d.%d.%d.%d:%d, new socket is %d", accept_msg->strAddr.sin_addr.s4_addr[0], accept_msg->strAddr.sin_addr.s4_addr[1], accept_msg->strAddr.sin_addr.s4_addr[2], accept_msg->strAddr.sin_addr.s4_addr[3], ntohs(accept_msg->strAddr.sin_port), accept_msg->sock); if (accept_msg->sock < 0) { LOG_ERR("ACCEPT: error %d %s", accept_msg->sock, socket_message_to_string(accept_msg->sock)); sd->ret_code = accept_msg->sock; } if (sd->accept_cb) { struct socket_data *a_sd; int ret; a_sd = &w1500_data.socket_data[accept_msg->sock]; memcpy(a_sd, sd, sizeof(struct socket_data)); ret = net_context_get(AF_INET, SOCK_STREAM, IPPROTO_TCP, &a_sd->context); if (ret < 0) { LOG_ERR("Cannot get new net context for ACCEPT"); return; } /* We get a new socket from accept_msg but we need a new * context as well. The new context gives us another socket * so we have to close that one first. */ winc1500_close((int)a_sd->context->offload_context); a_sd->context->offload_context = (void *)((int)accept_msg->sock); /** The iface is reset when getting a new context. */ a_sd->context->iface = sd->context->iface; /** Setup remote */ a_sd->context->remote.sa_family = AF_INET; net_sin(&a_sd->context->remote)->sin_port = accept_msg->strAddr.sin_port; net_sin(&a_sd->context->remote)->sin_addr.s_addr = accept_msg->strAddr.sin_addr.s_addr; a_sd->context->flags |= NET_CONTEXT_REMOTE_ADDR_SET; sd->accept_cb(a_sd->context, (struct sockaddr *)&accept_msg->strAddr, sizeof(struct sockaddr_in), (accept_msg->sock > 0) ? 0 : accept_msg->sock, sd->accept_user_data); } } static void winc1500_socket_cb(SOCKET sock, uint8 message, void *pvMsg) { struct socket_data *sd = &w1500_data.socket_data[sock]; if (message != 6) { LOG_DBG("sock %d Msg %d %s", sock, message, socket_message_to_string(message)); } sd->ret_code = 0; switch (message) { case SOCKET_MSG_CONNECT: handle_socket_msg_connect(sd, pvMsg); k_sem_give(&sd->wait_sem); break; case SOCKET_MSG_SEND: break; case SOCKET_MSG_RECV: if (!handle_socket_msg_recv(sock, sd, pvMsg)) { return; } break; case SOCKET_MSG_BIND: handle_socket_msg_bind(sd, pvMsg); k_sem_give(&sd->wait_sem); break; case SOCKET_MSG_LISTEN: handle_socket_msg_listen(sd, pvMsg); k_sem_give(&sd->wait_sem); break; case SOCKET_MSG_ACCEPT: handle_socket_msg_accept(sd, pvMsg); break; } #if LOG_LEVEL > LOG_LEVEL_OFF stack_stats(); #endif /* LOG_LEVEL > LOG_LEVEL_OFF */ } static void winc1500_thread(void *p1, void *p2, void *p3) { ARG_UNUSED(p1); ARG_UNUSED(p2); ARG_UNUSED(p3); while (1) { while (m2m_wifi_handle_events(NULL) != 0) { } k_sleep(K_MSEC(1)); } } static int winc1500_mgmt_scan(const struct device *dev, struct wifi_scan_params *params, scan_result_cb_t cb) { ARG_UNUSED(params); if (w1500_data.scan_cb) { return -EALREADY; } w1500_data.scan_cb = cb; if (m2m_wifi_request_scan(M2M_WIFI_CH_ALL)) { w1500_data.scan_cb = NULL; LOG_ERR("Failed to request scan"); return -EIO; } return 0; } static int winc1500_mgmt_connect(const struct device *dev, struct wifi_connect_req_params *params) { uint8_t ssid[M2M_MAX_SSID_LEN]; tuniM2MWifiAuth psk; uint8_t security; uint16_t channel; void *auth; memcpy(ssid, params->ssid, params->ssid_length); ssid[params->ssid_length] = '\0'; if (params->security == WIFI_SECURITY_TYPE_PSK) { memcpy(psk.au8PSK, params->psk, params->psk_length); psk.au8PSK[params->psk_length] = '\0'; auth = &psk; security = M2M_WIFI_SEC_WPA_PSK; } else { auth = NULL; security = M2M_WIFI_SEC_OPEN; } if (params->channel == WIFI_CHANNEL_ANY) { channel = M2M_WIFI_CH_ALL; } else { channel = params->channel; } LOG_DBG("Connecting to %s (%u) on %s %u %s security (%s)", ssid, params->ssid_length, channel == M2M_WIFI_CH_ALL ? "channel unknown" : "channel", channel, security == M2M_WIFI_SEC_OPEN ? "without" : "with", params->psk ? (char *)psk.au8PSK : ""); if (m2m_wifi_connect((char *)ssid, params->ssid_length, security, auth, channel)) { return -EIO; } w1500_data.connecting = true; return 0; } static int winc1500_mgmt_disconnect(const struct device *dev) { if (!w1500_data.connected) { return -EALREADY; } if (m2m_wifi_disconnect()) { return -EIO; } return 0; } static int winc1500_mgmt_ap_enable(const struct device *dev, struct wifi_connect_req_params *params) { tstrM2MAPConfig strM2MAPConfig; memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); strcpy((char *)&strM2MAPConfig.au8SSID, params->ssid); strM2MAPConfig.u8ListenChannel = params->channel; /** security is hardcoded as open for now */ strM2MAPConfig.u8SecType = M2M_WIFI_SEC_OPEN; /** DHCP: 192.168.1.1 */ strM2MAPConfig.au8DHCPServerIP[0] = 0xC0; strM2MAPConfig.au8DHCPServerIP[1] = 0xA8; strM2MAPConfig.au8DHCPServerIP[2] = 0x01; strM2MAPConfig.au8DHCPServerIP[3] = 0x01; if (m2m_wifi_enable_ap(&strM2MAPConfig) != M2M_SUCCESS) { return -EIO; } return 0; } static int winc1500_mgmt_ap_disable(const struct device *dev) { if (m2m_wifi_disable_ap() != M2M_SUCCESS) { return -EIO; } return 0; } static void winc1500_iface_init(struct net_if *iface) { LOG_DBG("eth_init:net_if_set_link_addr:" "MAC Address %02X:%02X:%02X:%02X:%02X:%02X", w1500_data.mac[0], w1500_data.mac[1], w1500_data.mac[2], w1500_data.mac[3], w1500_data.mac[4], w1500_data.mac[5]); net_if_set_link_addr(iface, w1500_data.mac, sizeof(w1500_data.mac), NET_LINK_ETHERNET); iface->if_dev->offload = &winc1500_offload; w1500_data.iface = iface; } static enum offloaded_net_if_types winc1500_get_wifi_type(void) { return L2_OFFLOADED_NET_IF_TYPE_WIFI; } static const struct wifi_mgmt_ops winc1500_mgmt_ops = { .scan = winc1500_mgmt_scan, .connect = winc1500_mgmt_connect, .disconnect = winc1500_mgmt_disconnect, .ap_enable = winc1500_mgmt_ap_enable, .ap_disable = winc1500_mgmt_ap_disable, }; static const struct net_wifi_mgmt_offload winc1500_api = { .wifi_iface.iface_api.init = winc1500_iface_init, .wifi_iface.get_type = winc1500_get_wifi_type, .wifi_mgmt_api = &winc1500_mgmt_ops, }; static int winc1500_init(const struct device *dev) { tstrWifiInitParam param = { .pfAppWifiCb = winc1500_wifi_cb, }; unsigned char is_valid; int ret; ARG_UNUSED(dev); w1500_data.connecting = false; w1500_data.connected = false; ret = m2m_wifi_init(&param); if (ret != M2M_SUCCESS) { LOG_ERR("m2m_wifi_init return error!(%d)", ret); return -EIO; } socketInit(); registerSocketCallback(winc1500_socket_cb, NULL); if (m2m_wifi_get_otp_mac_address(w1500_data.mac, &is_valid) != M2M_SUCCESS) { LOG_ERR("Failed to get MAC address"); } LOG_DBG("WINC1500 MAC Address from OTP (%d) " "%02X:%02X:%02X:%02X:%02X:%02X", is_valid, w1500_data.mac[0], w1500_data.mac[1], w1500_data.mac[2], w1500_data.mac[3], w1500_data.mac[4], w1500_data.mac[5]); if (m2m_wifi_set_scan_region(WINC1500_REGION) != M2M_SUCCESS) { LOG_ERR("Failed set scan region"); } if (m2m_wifi_set_power_profile(PWR_LOW1) != M2M_SUCCESS) { LOG_ERR("Failed set power profile"); } if (m2m_wifi_set_tx_power(TX_PWR_LOW) != M2M_SUCCESS) { LOG_ERR("Failed set tx power"); } /* monitoring thread for winc wifi callbacks */ k_thread_create(&winc1500_thread_data, winc1500_stack, CONFIG_WIFI_WINC1500_THREAD_STACK_SIZE, winc1500_thread, NULL, NULL, NULL, K_PRIO_COOP(CONFIG_WIFI_WINC1500_THREAD_PRIO), 0, K_NO_WAIT); k_thread_name_set(&winc1500_thread_data, "WINC1500"); LOG_DBG("WINC1500 driver Initialized"); return 0; } NET_DEVICE_OFFLOAD_INIT(winc1500, CONFIG_WIFI_WINC1500_NAME, winc1500_init, NULL, &w1500_data, NULL, CONFIG_WIFI_INIT_PRIORITY, &winc1500_api, CONFIG_WIFI_WINC1500_MAX_PACKET_SIZE); CONNECTIVITY_WIFI_MGMT_BIND(winc1500); ```
/content/code_sandbox/drivers/wifi/winc1500/wifi_winc1500.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
8,760
```c /** * */ #define DT_DRV_COMPAT atmel_winc1500 #define LOG_LEVEL CONFIG_WIFI_LOG_LEVEL #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(winc1500); #include <stdio.h> #include <stdint.h> #include <zephyr/device.h> #include <zephyr/drivers/spi.h> #include "wifi_winc1500_nm_bsp_internal.h" #include <bsp/include/nm_bsp.h> #include <common/include/nm_common.h> #include <bus_wrapper/include/nm_bus_wrapper.h> #include "wifi_winc1500_config.h" #define NM_BUS_MAX_TRX_SZ 256 tstrNmBusCapabilities egstrNmBusCapabilities = { NM_BUS_MAX_TRX_SZ }; #ifdef CONF_WINC_USE_I2C #define SLAVE_ADDRESS 0x60 /** Number of times to try to send packet if failed. */ #define I2C_TIMEOUT 100 static int8_t nm_i2c_write(uint8_t *b, uint16_t sz) { /* Not implemented */ } static int8_t nm_i2c_read(uint8_t *rb, uint16_t sz) { /* Not implemented */ } static int8_t nm_i2c_write_special(uint8_t *wb1, uint16_t sz1, uint8_t *wb2, uint16_t sz2) { /* Not implemented */ } #endif #ifdef CONF_WINC_USE_SPI static int8_t spi_rw(uint8_t *mosi, uint8_t *miso, uint16_t size) { const struct spi_buf buf_tx = { .buf = mosi, .len = size }; const struct spi_buf_set tx = { .buffers = &buf_tx, .count = 1 }; const struct spi_buf buf_rx = { .buf = miso, .len = miso ? size : 0 }; const struct spi_buf_set rx = { .buffers = &buf_rx, .count = 1 }; if (spi_transceive_dt(&winc1500_config.spi, &tx, &rx)) { LOG_ERR("spi_transceive fail"); return M2M_ERR_BUS_FAIL; } return M2M_SUCCESS; } #endif int8_t nm_bus_init(void *pvinit) { /* configure GPIOs */ if (!gpio_is_ready_dt(&winc1500_config.chip_en_gpio)) { return -ENODEV; } gpio_pin_configure_dt(&winc1500_config.chip_en_gpio, GPIO_OUTPUT_LOW); if (!gpio_is_ready_dt(&winc1500_config.irq_gpio)) { return -ENODEV; } gpio_pin_configure_dt(&winc1500_config.irq_gpio, GPIO_INPUT); if (!gpio_is_ready_dt(&winc1500_config.reset_gpio)) { return -ENODEV; } gpio_pin_configure_dt(&winc1500_config.reset_gpio, GPIO_OUTPUT_LOW); #ifdef CONF_WINC_USE_I2C /* Not implemented */ #elif defined CONF_WINC_USE_SPI /* setup SPI device */ if (!spi_is_ready_dt(&winc1500_config.spi)) { LOG_ERR("spi device binding"); return -ENODEV; } nm_bsp_reset(); nm_bsp_sleep(1); nm_bsp_interrupt_ctrl(1); LOG_DBG("NOTICE:DONE"); #endif return 0; } int8_t nm_bus_ioctl(uint8_t cmd, void *parameter) { sint8 ret = 0; switch (cmd) { #ifdef CONF_WINC_USE_I2C case NM_BUS_IOCTL_R: { struct nm_i2c_default *param = (struct nm_i2c_default *)parameter; ret = nm_i2c_read(param->buffer, param->size); } break; case NM_BUS_IOCTL_W: { struct nm_i2c_default *param = (struct nm_i2c_default *)parameter; ret = nm_i2c_write(param->buffer, param->size); } break; case NM_BUS_IOCTL_W_SPECIAL: { struct nm_i2c_special *param = (struct nm_i2c_special *)parameter; ret = nm_i2c_write_special(param->buffer1, param->size1, param->buffer2, param->size2); } break; #elif defined CONF_WINC_USE_SPI case NM_BUS_IOCTL_RW: { tstrNmSpiRw *param = (tstrNmSpiRw *)parameter; ret = spi_rw(param->pu8InBuf, param->pu8OutBuf, param->u16Sz); } break; #endif default: ret = -1; M2M_ERR("ERROR:invalid ioclt cmd\n"); break; } return ret; } int8_t nm_bus_deinit(void) { return M2M_SUCCESS; } int8_t nm_bus_reinit(void *config) { return 0; } ```
/content/code_sandbox/drivers/wifi/winc1500/wifi_winc1500_nm_bus_wrapper.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,051
```c /** * */ #define DT_DRV_COMPAT atmel_winc1500 #include "wifi_winc1500_nm_bsp_internal.h" #include <bsp/include/nm_bsp.h> #include <common/include/nm_common.h> #include "wifi_winc1500_config.h" const struct winc1500_cfg winc1500_config = { .spi = SPI_DT_SPEC_INST_GET(0, SPI_WORD_SET(8) | SPI_TRANSFER_MSB, 0), .chip_en_gpio = GPIO_DT_SPEC_INST_GET(0, enable_gpios), .irq_gpio = GPIO_DT_SPEC_INST_GET(0, irq_gpios), .reset_gpio = GPIO_DT_SPEC_INST_GET(0, reset_gpios), }; struct winc1500_device winc1500; void (*isr_function)(void); static inline void chip_isr(const struct device *port, struct gpio_callback *cb, gpio_port_pins_t pins) { if (isr_function) { isr_function(); } } int8_t nm_bsp_init(void) { isr_function = NULL; /* Perform chip reset. */ nm_bsp_reset(); return 0; } int8_t nm_bsp_deinit(void) { /* TODO */ return 0; } void nm_bsp_reset(void) { gpio_pin_set_dt(&winc1500_config.chip_en_gpio, 0); gpio_pin_set_dt(&winc1500_config.reset_gpio, 0); nm_bsp_sleep(100); gpio_pin_set_dt(&winc1500_config.chip_en_gpio, 1); nm_bsp_sleep(10); gpio_pin_set_dt(&winc1500_config.reset_gpio, 1); nm_bsp_sleep(10); } void nm_bsp_sleep(uint32 u32TimeMsec) { k_busy_wait(u32TimeMsec * MSEC_PER_SEC); } void nm_bsp_register_isr(void (*isr_fun)(void)) { isr_function = isr_fun; gpio_init_callback(&winc1500.gpio_cb, chip_isr, BIT(winc1500_config.irq_gpio.pin)); gpio_add_callback(winc1500_config.irq_gpio.port, &winc1500.gpio_cb); } void nm_bsp_interrupt_ctrl(uint8_t enable) { gpio_pin_interrupt_configure_dt(&winc1500_config.irq_gpio, enable ? GPIO_INT_EDGE_TO_ACTIVE : GPIO_INT_DISABLE); } ```
/content/code_sandbox/drivers/wifi/winc1500/wifi_winc1500_nm_bsp.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
506
```unknown # Atmel WINC1500 WiFi driver options menuconfig WIFI_WINC1500 bool "WINC1500 driver support" default y depends on DT_HAS_ATMEL_WINC1500_ENABLED select SPI select ATMEL_WINC1500 select WIFI_OFFLOAD select NET_L2_WIFI_MGMT if WIFI_WINC1500 config WIFI_WINC1500_NAME string "Driver name" default "WINC1500" config WINC1500_DRV_USE_OLD_SPI_SW bool "Use old SPI access method in the vendor HAL" help This option, when enabled, causes USE_OLD_SPI_SW setting to be passed to vendor HAL. config WIFI_WINC1500_THREAD_STACK_SIZE int "HAL callback handler thread stack size" default 2048 help This option sets the size of the stack used by the thread handling WINC1500 HAL callbacks. Do not touch it unless you know what you are doing. config WIFI_WINC1500_THREAD_PRIO int "HAL callback handler thread priority" default 2 help This option sets the priority of the thread handling WINC1500 HAL callbacks. Do not touch it unless you know what you are doing. config WIFI_WINC1500_BUF_CTR int "Number of buffer per-buffer pool" default 1 help Set the number of buffer the driver will have access to in each of its buffer pools. config WIFI_WINC1500_MAX_PACKET_SIZE int "Maximum size of a packet, in bytes" default 1500 help Set the maximum size of a network packet going through the chip. This sets the size of each buffer, in each buffer pools. Do not modify it unless you know what you are doing. config WIFI_WINC1500_OFFLOAD_MAX_SOCKETS int "Maximum number of sockets that can be managed" default 2 help Set the number of sockets that can be managed through the driver and the chip. choice bool "In which region is the chip running?" default WIFI_WINC1500_REGION_NORTH_AMERICA config WIFI_WINC1500_REGION_NORTH_AMERICA bool "Region North America" config WIFI_WINC1500_REGION_EUROPE bool "Region Europe" config WIFI_WINC1500_REGION_ASIA bool "Region Asia" endchoice endif # WIFI_WINC1500 ```
/content/code_sandbox/drivers/wifi/winc1500/Kconfig.winc1500
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
510
```objective-c /** * */ #ifndef ZEPHYR_DRIVERS_WIFI_WINC1500_WIFI_WINC1500_NM_BSP_INTERNAL_H_ #define ZEPHYR_DRIVERS_WIFI_WINC1500_WIFI_WINC1500_NM_BSP_INTERNAL_H_ #include <zephyr/device.h> #include <zephyr/drivers/gpio.h> #include <zephyr/drivers/spi.h> #include "wifi_winc1500_config.h" #include <bus_wrapper/include/nm_bus_wrapper.h> extern tstrNmBusCapabilities egstrNmBusCapabilities; #if defined(CONFIG_WINC1500_DRV_USE_OLD_SPI_SW) #define USE_OLD_SPI_SW #endif /*CONFIG_WINC1500_DRV_USE_OLD_SPI_SW*/ #define NM_EDGE_INTERRUPT (1) #define NM_DEBUG CONF_WINC_DEBUG #define NM_BSP_PRINTF CONF_WINC_PRINTF enum winc1500_gpio_index { WINC1500_GPIO_IDX_CHIP_EN = 0, WINC1500_GPIO_IDX_IRQN, WINC1500_GPIO_IDX_RESET_N, WINC1500_GPIO_IDX_MAX }; struct winc1500_cfg { struct spi_dt_spec spi; struct gpio_dt_spec chip_en_gpio; struct gpio_dt_spec irq_gpio; struct gpio_dt_spec reset_gpio; }; struct winc1500_device { struct gpio_callback gpio_cb; }; extern struct winc1500_device winc1500; extern const struct winc1500_cfg winc1500_config; #endif /* ZEPHYR_DRIVERS_WIFI_WINC1500_WIFI_WINC1500_NM_BSP_INTERNAL_H_ */ ```
/content/code_sandbox/drivers/wifi/winc1500/wifi_winc1500_nm_bsp_internal.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
321
```objective-c /** * */ #ifndef ZEPHYR_DRIVERS_WIFI_WINC1500_WIFI_WINC1500_CONFIG_H_ #define ZEPHYR_DRIVERS_WIFI_WINC1500_WIFI_WINC1500_CONFIG_H_ /* --------------------------------- ---------- PIN settings --------- --------------------------------- */ #define CONF_WINC_PIN_RESET IOPORT_CREATE_PIN(PIOA, 24) #define CONF_WINC_PIN_CHIP_ENABLE IOPORT_CREATE_PIN(PIOA, 6) #define CONF_WINC_PIN_WAKE IOPORT_CREATE_PIN(PIOA, 25) /* --------------------------------- ---------- SPI settings --------- --------------------------------- */ #define CONF_WINC_USE_SPI (1) /** SPI pin and instance settings. */ #define CONF_WINC_SPI SPI #define CONF_WINC_SPI_ID ID_SPI #define CONF_WINC_SPI_MISO_GPIO SPI_MISO_GPIO #define CONF_WINC_SPI_MISO_FLAGS SPI_MISO_FLAGS #define CONF_WINC_SPI_MOSI_GPIO SPI_MOSI_GPIO #define CONF_WINC_SPI_MOSI_FLAGS SPI_MOSI_FLAGS #define CONF_WINC_SPI_CLK_GPIO SPI_SPCK_GPIO #define CONF_WINC_SPI_CLK_FLAGS SPI_SPCK_FLAGS #define CONF_WINC_SPI_CS_GPIO SPI_NPCS0_GPIO #define CONF_WINC_SPI_CS_FLAGS PIO_OUTPUT_1 #define CONF_WINC_SPI_NPCS (0) /** SPI delay before SPCK and between consecutive transfer. */ #define CONF_WINC_SPI_DLYBS (0) #define CONF_WINC_SPI_DLYBCT (0) /** SPI interrupt pin. */ #define CONF_WINC_SPI_INT_PIN IOPORT_CREATE_PIN(PIOA, 1) #define CONF_WINC_SPI_INT_PIO PIOA #define CONF_WINC_SPI_INT_PIO_ID ID_PIOA #define CONF_WINC_SPI_INT_MASK (1 << 1) #define CONF_WINC_SPI_INT_PRIORITY (0) /** Clock polarity & phase. */ #define CONF_WINC_SPI_POL (0) #define CONF_WINC_SPI_PHA (1) /** SPI clock. */ #define CONF_WINC_SPI_CLOCK (48000000) /* --------------------------------- --------- Debug Options --------- --------------------------------- */ #include <stdio.h> #define CONF_WINC_DEBUG (0) #define CONF_WINC_PRINTF printf #endif /* ZEPHYR_DRIVERS_WIFI_WINC1500_WIFI_WINC1500_CONFIG_H_ */ ```
/content/code_sandbox/drivers/wifi/winc1500/wifi_winc1500_config.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
528
```unknown menuconfig WIFI_ESP32 bool "ESP32 SoC WiFi support" default y depends on DT_HAS_ESPRESSIF_ESP32_WIFI_ENABLED depends on !SMP select THREAD_CUSTOM_DATA select NET_L2_WIFI_MGMT select WIFI_USE_NATIVE_NETWORKING select MBEDTLS select THREAD_STACK_INFO select DYNAMIC_THREAD select DYNAMIC_THREAD_ALLOC help Enable ESP32 SoC WiFi support. Only supported in single core mode because the network stack is not aware of SMP stuff. if WIFI_ESP32 config NET_TCP_WORKQ_STACK_SIZE default 2048 config NET_RX_STACK_SIZE default 2048 config NET_MGMT_EVENT_STACK_SIZE default 2048 config ESP32_WIFI_STA_AUTO_DHCPV4 bool "Automatically starts DHCP4 negotiation" depends on NET_DHCPV4 depends on NET_IPV4 help WiFi driver will automatically initiate DHCPV4 negotiation when connected. config ESP32_WIFI_STA_RECONNECT bool "WiFi connection retry" help Set auto WiFI reconnection when disconnected. config ESP32_WIFI_SW_COEXIST_ENABLE bool help Software controls WiFi/Bluetooth coexistence. Not supported yet. config ESP32_WIFI_NET_ALLOC_SPIRAM bool "Allocate memory of WiFi and NET in SPIRAM" depends on ESP_SPIRAM help Allocate memory of WiFi and NET stack in SPIRAM, increasing available RAM memory space for application stack. config ESP32_WIFI_STATIC_RX_BUFFER_NUM int "Max number of WiFi static RX buffers" range 2 25 default 10 help Set the number of WiFi static RX buffers. Each buffer takes approximately 1.6KB of RAM. The static rx buffers are allocated when esp_wifi_init is called, they are not freed until esp_wifi_deinit is called. WiFi hardware use these buffers to receive all 802.11 frames. A higher number may allow higher throughput but increases memory use. If ESP32_WIFI_AMPDU_RX_ENABLED is enabled, this value is recommended to set equal or bigger than ESP32_WIFI_RX_BA_WIN in order to achieve better throughput and compatibility with both stations and APs. config ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM int "Max number of WiFi dynamic RX buffers" range 0 128 default 32 help Set the number of WiFi dynamic RX buffers, 0 means unlimited RX buffers will be allocated (provided sufficient free RAM). The size of each dynamic RX buffer depends on the size of the received data frame. For each received data frame, the WiFi driver makes a copy to an RX buffer and then delivers it to the high layer TCP/IP stack. The dynamic RX buffer is freed after the higher layer has successfully received the data frame. For some applications, WiFi data frames may be received faster than the application can process them. In these cases we may run out of memory if RX buffer number is unlimited (0). If a dynamic RX buffer limit is set, it should be at least the number of static RX buffers. choice ESP32_WIFI_TX_BUFFER prompt "Type of WiFi TX buffers" default ESP32_WIFI_DYNAMIC_TX_BUFFER help Select type of WiFi TX buffers: If "Static" is selected, WiFi TX buffers are allocated when WiFi is initialized and released when WiFi is de-initialized. The size of each static TX buffer is fixed to about 1.6KB. If "Dynamic" is selected, each WiFi TX buffer is allocated as needed when a data frame is delivered to the Wifi driver from the TCP/IP stack. The buffer is freed after the data frame has been sent by the WiFi driver. The size of each dynamic TX buffer depends on the length of each data frame sent by the TCP/IP layer. If PSRAM is enabled, "Static" should be selected to guarantee enough WiFi TX buffers. If PSRAM is disabled, "Dynamic" should be selected to improve the utilization of RAM. config ESP32_WIFI_STATIC_TX_BUFFER bool "Static" config ESP32_WIFI_DYNAMIC_TX_BUFFER bool "Dynamic" endchoice config ESP32_WIFI_TX_BUFFER_TYPE int default 0 if ESP32_WIFI_STATIC_TX_BUFFER default 1 if ESP32_WIFI_DYNAMIC_TX_BUFFER config ESP32_WIFI_STATIC_TX_BUFFER_NUM int "Max number of WiFi static TX buffers" depends on ESP32_WIFI_STATIC_TX_BUFFER range 1 64 default 16 help Set the number of WiFi static TX buffers. Each buffer takes approximately 1.6KB of RAM. The static RX buffers are allocated when esp_wifi_init() is called, they are not released until esp_wifi_deinit() is called. For each transmitted data frame from the higher layer TCP/IP stack, the WiFi driver makes a copy of it in a TX buffer. For some applications especially UDP applications, the upper layer can deliver frames faster than WiFi layer can transmit. In these cases, we may run out of TX buffers. config ESP32_WIFI_CACHE_TX_BUFFER_NUM int "Max number of WiFi cache TX buffers" depends on ESP_SPIRAM range 16 128 default 32 help Set the number of WiFi cache TX buffer number. For each TX packet from uplayer, such as LWIP etc, WiFi driver needs to allocate a static TX buffer and makes a copy of uplayer packet. If WiFi driver fails to allocate the static TX buffer, it caches the uplayer packets to a dedicated buffer queue, this option is used to configure the size of the cached TX queue. config ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM int "Max number of WiFi dynamic TX buffers" depends on ESP32_WIFI_DYNAMIC_TX_BUFFER range 1 128 default 32 help Set the number of WiFi dynamic TX buffers. The size of each dynamic TXbuffer is not fixed, it depends on the size of each transmitted data frame. For each transmitted frame from the higher layer TCP/IP stack, the WiFi driver makes a copy of it in a TX buffer. For some applications, especially UDP applications, the upper layer can deliver frames faster than WiFi layer can transmit. In these cases, we may run out of TX buffers. config ESP32_WIFI_CSI_ENABLED bool "WiFi CSI(Channel State Information)" default n help Select this option to enable CSI(Channel State Information) feature. CSI takes about CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM KB of RAM. If CSI is not used, it is better to disable this feature in order to save memory. config ESP32_WIFI_AMPDU_TX_ENABLED bool "WiFi AMPDU TX" default y help Select this option to enable AMPDU TX feature. It improves transmission error checking and overall network performance with the cost of processing speed. Helpful when the device is operating in crowded wireless area. config ESP32_WIFI_TX_BA_WIN int "WiFi AMPDU TX BA window size" depends on ESP32_WIFI_AMPDU_TX_ENABLED range 2 32 default 6 help Set the size of WiFi Block Ack TX window. Generally a bigger value means higher throughput but more memory. Most of time we should NOT change the default value unless special reason, e.g. test the maximum UDP TX throughput with iperf etc. For iperf test in shieldbox, the recommended value is 9~12. config ESP32_WIFI_AMPDU_RX_ENABLED bool "WiFi AMPDU RX" default y help Select this option to enable AMPDU RX feature. It improves transmission error checking and overall network performance with the cost of processing speed. Helpful when the device is operating in crowded wireless area. config ESP32_WIFI_RX_BA_WIN int "WiFi AMPDU RX BA window size" depends on ESP32_WIFI_AMPDU_RX_ENABLED range 2 32 default 6 help Set the size of WiFi Block Ack RX window. Generally a bigger value means higher throughput and better compatibility but more memory. Most of time we should NOT change the default value unless special reason, e.g. test the maximum UDP RX throughput with iperf etc. For iperf test in shieldbox, the recommended value is 9~12. If PSRAM is used and WiFi memory is preferred to be allocated in PSRAM first, the default and minimum value should be 16 to achieve better throughput and compatibility with both stations and APs. config ESP32_WIFI_AMSDU_TX_ENABLED bool "WiFi AMSDU TX" depends on ESP_SPIRAM default n help Select this option to enable AMSDU TX feature config ESP32_WIFI_IRAM_OPT bool "WiFi IRAM speed optimization" default n if (BT && ESP_SPIRAM && SOC_SERIES_ESP32) default y help Select this option to place frequently called Wi-Fi library functions in IRAM. When this option is disabled, more than 10Kbytes of IRAM memory will be saved but Wi-Fi throughput will be reduced. config ESP32_WIFI_RX_IRAM_OPT bool "WiFi RX IRAM speed optimization" default n if (BT && ESP_SPIRAM && SOC_SERIES_ESP32) help Select this option to place frequently called Wi-Fi library RX functions in IRAM. When this option is disabled, more than 17Kbytes of IRAM memory will be saved but Wi-Fi performance will be reduced. config ESP32_WIFI_FTM_ENABLE bool "WiFi FTM" default n depends on SOC_SERIES_ESP32C3 help Enable feature Fine Timing Measurement for calculating WiFi Round-Trip-Time (RTT). config ESP32_WIFI_FTM_INITIATOR_SUPPORT bool "FTM Initiator support" default y depends on ESP32_WIFI_FTM_ENABLE config ESP32_WIFI_FTM_RESPONDER_SUPPORT bool "FTM Responder support" default y depends on ESP32_WIFI_FTM_ENABLE config ESP32_WIFI_SOFTAP_SUPPORT bool default y help Hidden option to enable Wi-Fi SoftAP functions in WPA supplicant and RF libraries. config ESP32_WIFI_MBEDTLS_CRYPTO bool "Use MbedTLS crypto APIs" default n select MBEDTLS_ECP_C select MBEDTLS_ECDH_C select MBEDTLS_ECDSA_C select MBEDTLS_PKCS5_C select MBEDTLS_PK_WRITE_C select MBEDTLS_CIPHER_MODE_CTR_ENABLED select MBEDTLS_CMAC select MBEDTLS_ZEPHYR_ENTROPY help Select this option to use MbedTLS crypto APIs which utilize hardware acceleration. config ESP32_WIFI_ENABLE_WPA3_SAE bool "WPA3-Personal" default n select ESP32_WIFI_MBEDTLS_CRYPTO help Select this option to allow the device to establish a WPA3-Personal connection. config ESP32_WIFI_ENABLE_WPA3_OWE_STA bool "OWE STA" default y depends on ESP32_WIFI_ENABLE_WPA3_SAE help Select this option to allow the device to establish OWE connection with eligible AP's. config ESP32_WIFI_ENABLE_SAE_PK bool "SAE-PK" default y depends on ESP32_WIFI_ENABLE_WPA3_SAE help Select this option to enable SAE-PK config ESP32_WIFI_DEBUG_PRINT bool "Print debug messages from WPA Supplicant" default n help Select this option to print logging information from WPA supplicant, this includes handshake information and key hex dumps depending on the project logging level. Enabling this could increase the build size ~60kb depending on the project logging level. endif # WIFI_ESP32 ```
/content/code_sandbox/drivers/wifi/esp32/Kconfig.esp32
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,536
```objective-c /* * an affiliate of Cypress Semiconductor Corporation * */ /* This is enpty/stub file used in WHD */ ```
/content/code_sandbox/drivers/wifi/infineon/cybsp.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
25
```c /* * */ #define DT_DRV_COMPAT espressif_esp32_wifi #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(esp32_wifi, CONFIG_WIFI_LOG_LEVEL); #include <zephyr/net/ethernet.h> #include <zephyr/net/net_pkt.h> #include <zephyr/net/net_if.h> #include <zephyr/net/wifi_mgmt.h> #include <zephyr/net/conn_mgr/connectivity_wifi_mgmt.h> #include <zephyr/device.h> #include <soc.h> #include "esp_private/wifi.h" #include "esp_event.h" #include "esp_timer.h" #include "esp_system.h" #include "esp_wpa.h" #include <esp_mac.h> #include "wifi/wifi_event.h" #define DHCPV4_MASK (NET_EVENT_IPV4_DHCP_BOUND | NET_EVENT_IPV4_DHCP_STOP) /* use global iface pointer to support any ethernet driver */ /* necessary for wifi callback functions */ static struct net_if *esp32_wifi_iface; static struct esp32_wifi_runtime esp32_data; enum esp32_state_flag { ESP32_STA_STOPPED, ESP32_STA_STARTED, ESP32_STA_CONNECTING, ESP32_STA_CONNECTED, ESP32_AP_CONNECTED, ESP32_AP_DISCONNECTED, ESP32_AP_STOPPED, }; struct esp32_wifi_status { char ssid[WIFI_SSID_MAX_LEN + 1]; char pass[WIFI_PSK_MAX_LEN + 1]; wifi_auth_mode_t security; bool connected; uint8_t channel; int rssi; }; struct esp32_wifi_runtime { uint8_t mac_addr[6]; uint8_t frame_buf[NET_ETH_MAX_FRAME_SIZE]; #if defined(CONFIG_NET_STATISTICS_WIFI) struct net_stats_wifi stats; #endif struct esp32_wifi_status status; scan_result_cb_t scan_cb; uint8_t state; uint8_t ap_connection_cnt; }; static struct net_mgmt_event_callback esp32_dhcp_cb; static void wifi_event_handler(struct net_mgmt_event_callback *cb, uint32_t mgmt_event, struct net_if *iface) { const struct wifi_status *status = (const struct wifi_status *)cb->info; switch (mgmt_event) { case NET_EVENT_IPV4_DHCP_BOUND: wifi_mgmt_raise_connect_result_event(esp32_wifi_iface, 0); break; default: break; } } static int esp32_wifi_send(const struct device *dev, struct net_pkt *pkt) { struct esp32_wifi_runtime *data = dev->data; const int pkt_len = net_pkt_get_len(pkt); esp_interface_t ifx = esp32_data.state == ESP32_AP_CONNECTED ? ESP_IF_WIFI_AP : ESP_IF_WIFI_STA; /* Read the packet payload */ if (net_pkt_read(pkt, data->frame_buf, pkt_len) < 0) { goto out; } /* Enqueue packet for transmission */ if (esp_wifi_internal_tx(ifx, (void *)data->frame_buf, pkt_len) != ESP_OK) { goto out; } #if defined(CONFIG_NET_STATISTICS_WIFI) data->stats.bytes.sent += pkt_len; data->stats.pkts.tx++; #endif LOG_DBG("pkt sent %p len %d", pkt, pkt_len); return 0; out: LOG_ERR("Failed to send packet"); #if defined(CONFIG_NET_STATISTICS_WIFI) data->stats.errors.tx++; #endif return -EIO; } static esp_err_t eth_esp32_rx(void *buffer, uint16_t len, void *eb) { struct net_pkt *pkt; if (esp32_wifi_iface == NULL) { esp_wifi_internal_free_rx_buffer(eb); LOG_ERR("network interface unavailable"); return -EIO; } pkt = net_pkt_rx_alloc_with_buffer(esp32_wifi_iface, len, AF_UNSPEC, 0, K_MSEC(100)); if (!pkt) { LOG_ERR("Failed to allocate net buffer"); esp_wifi_internal_free_rx_buffer(eb); return -EIO; } if (net_pkt_write(pkt, buffer, len) < 0) { LOG_ERR("Failed to write to net buffer"); goto pkt_unref; } if (net_recv_data(esp32_wifi_iface, pkt) < 0) { LOG_ERR("Failed to push received data"); goto pkt_unref; } #if defined(CONFIG_NET_STATISTICS_WIFI) esp32_data.stats.bytes.received += len; esp32_data.stats.pkts.rx++; #endif esp_wifi_internal_free_rx_buffer(eb); return 0; pkt_unref: esp_wifi_internal_free_rx_buffer(eb); net_pkt_unref(pkt); #if defined(CONFIG_NET_STATISTICS_WIFI) esp32_data.stats.errors.rx++; #endif return -EIO; } static void scan_done_handler(void) { uint16_t aps = 0; wifi_ap_record_t *ap_list_buffer; struct wifi_scan_result res = { 0 }; esp_wifi_scan_get_ap_num(&aps); if (!aps) { LOG_INF("No Wi-Fi AP found"); goto out; } ap_list_buffer = k_malloc(aps * sizeof(wifi_ap_record_t)); if (ap_list_buffer == NULL) { LOG_INF("Failed to malloc buffer to print scan results"); goto out; } if (esp_wifi_scan_get_ap_records(&aps, (wifi_ap_record_t *)ap_list_buffer) == ESP_OK) { for (int k = 0; k < aps; k++) { memset(&res, 0, sizeof(struct wifi_scan_result)); int ssid_len = strnlen(ap_list_buffer[k].ssid, WIFI_SSID_MAX_LEN); res.ssid_length = ssid_len; strncpy(res.ssid, ap_list_buffer[k].ssid, ssid_len); res.rssi = ap_list_buffer[k].rssi; res.channel = ap_list_buffer[k].primary; memcpy(res.mac, ap_list_buffer[k].bssid, WIFI_MAC_ADDR_LEN); res.mac_length = WIFI_MAC_ADDR_LEN; switch (ap_list_buffer[k].authmode) { case WIFI_AUTH_OPEN: res.security = WIFI_SECURITY_TYPE_NONE; break; case WIFI_AUTH_WPA2_PSK: res.security = WIFI_SECURITY_TYPE_PSK; break; case WIFI_AUTH_WPA3_PSK: res.security = WIFI_SECURITY_TYPE_SAE; break; case WIFI_AUTH_WAPI_PSK: res.security = WIFI_SECURITY_TYPE_WAPI; break; case WIFI_AUTH_WPA2_ENTERPRISE: res.security = WIFI_SECURITY_TYPE_EAP; break; case WIFI_AUTH_WEP: res.security = WIFI_SECURITY_TYPE_WEP; break; case WIFI_AUTH_WPA_PSK: res.security = WIFI_SECURITY_TYPE_WPA_PSK; break; default: res.security = WIFI_SECURITY_TYPE_UNKNOWN; break; } if (esp32_data.scan_cb) { esp32_data.scan_cb(esp32_wifi_iface, 0, &res); /* ensure notifications get delivered */ k_yield(); } } } else { LOG_INF("Unable to retrieve AP records"); } k_free(ap_list_buffer); out: /* report end of scan event */ esp32_data.scan_cb(esp32_wifi_iface, 0, NULL); esp32_data.scan_cb = NULL; } static void esp_wifi_handle_sta_connect_event(void *event_data) { ARG_UNUSED(event_data); esp32_data.state = ESP32_STA_CONNECTED; #if defined(CONFIG_ESP32_WIFI_STA_AUTO_DHCPV4) net_dhcpv4_start(esp32_wifi_iface); #else wifi_mgmt_raise_connect_result_event(esp32_wifi_iface, 0); #endif } static void esp_wifi_handle_sta_disconnect_event(void *event_data) { wifi_event_sta_disconnected_t *event = (wifi_event_sta_disconnected_t *)event_data; if (esp32_data.state == ESP32_STA_CONNECTED) { #if defined(CONFIG_ESP32_WIFI_STA_AUTO_DHCPV4) net_dhcpv4_stop(esp32_wifi_iface); #endif wifi_mgmt_raise_disconnect_result_event(esp32_wifi_iface, 0); } else { wifi_mgmt_raise_disconnect_result_event(esp32_wifi_iface, -1); } LOG_DBG("Disconnect reason: %d", event->reason); switch (event->reason) { case WIFI_REASON_AUTH_EXPIRE: case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT: case WIFI_REASON_AUTH_FAIL: case WIFI_REASON_HANDSHAKE_TIMEOUT: case WIFI_REASON_MIC_FAILURE: LOG_DBG("STA Auth Error"); break; case WIFI_REASON_NO_AP_FOUND: LOG_DBG("AP Not found"); break; default: break; } if (IS_ENABLED(CONFIG_ESP32_WIFI_STA_RECONNECT) && (event->reason != WIFI_REASON_ASSOC_LEAVE)) { esp32_data.state = ESP32_STA_CONNECTING; esp_wifi_connect(); } else { esp32_data.state = ESP32_STA_STARTED; } } static void esp_wifi_handle_ap_connect_event(void *event_data) { wifi_event_ap_staconnected_t *event = (wifi_event_ap_staconnected_t *) event_data; LOG_DBG("Station " MACSTR " join, AID=%d", MAC2STR(event->mac), event->aid); wifi_mgmt_raise_connect_result_event(esp32_wifi_iface, 0); if (!(esp32_data.ap_connection_cnt++)) { esp_wifi_internal_reg_rxcb(WIFI_IF_AP, eth_esp32_rx); } } static void esp_wifi_handle_ap_disconnect_event(void *event_data) { wifi_event_ap_stadisconnected_t *event = (wifi_event_ap_stadisconnected_t *)event_data; LOG_DBG("station "MACSTR" leave, AID=%d", MAC2STR(event->mac), event->aid); wifi_mgmt_raise_disconnect_result_event(esp32_wifi_iface, 0); if (!(--esp32_data.ap_connection_cnt)) { esp_wifi_internal_reg_rxcb(WIFI_IF_AP, NULL); } } void esp_wifi_event_handler(const char *event_base, int32_t event_id, void *event_data, size_t event_data_size, uint32_t ticks_to_wait) { LOG_DBG("Wi-Fi event: %d", event_id); switch (event_id) { case WIFI_EVENT_STA_START: esp32_data.state = ESP32_STA_STARTED; net_eth_carrier_on(esp32_wifi_iface); break; case WIFI_EVENT_STA_STOP: esp32_data.state = ESP32_STA_STOPPED; net_eth_carrier_off(esp32_wifi_iface); break; case WIFI_EVENT_STA_CONNECTED: esp_wifi_handle_sta_connect_event(event_data); break; case WIFI_EVENT_STA_DISCONNECTED: esp_wifi_handle_sta_disconnect_event(event_data); break; case WIFI_EVENT_SCAN_DONE: scan_done_handler(); break; case WIFI_EVENT_AP_STOP: esp32_data.state = ESP32_AP_STOPPED; net_eth_carrier_off(esp32_wifi_iface); break; case WIFI_EVENT_AP_STACONNECTED: esp32_data.state = ESP32_AP_CONNECTED; esp_wifi_handle_ap_connect_event(event_data); break; case WIFI_EVENT_AP_STADISCONNECTED: esp32_data.state = ESP32_AP_DISCONNECTED; esp_wifi_handle_ap_disconnect_event(event_data); break; default: break; } } static int esp32_wifi_disconnect(const struct device *dev) { struct esp32_wifi_runtime *data = dev->data; int ret = esp_wifi_disconnect(); if (ret != ESP_OK) { LOG_INF("Failed to disconnect from hotspot"); return -EAGAIN; } return 0; } static int esp32_wifi_connect(const struct device *dev, struct wifi_connect_req_params *params) { struct esp32_wifi_runtime *data = dev->data; wifi_mode_t mode; int ret; if (data->state == ESP32_STA_CONNECTING || data->state == ESP32_STA_CONNECTED) { wifi_mgmt_raise_connect_result_event(esp32_wifi_iface, -1); return -EALREADY; } ret = esp_wifi_get_mode(&mode); if (ret) { LOG_ERR("Failed to get Wi-Fi mode (%d)", ret); return -EAGAIN; } if (mode != ESP32_WIFI_MODE_STA) { ret = esp_wifi_set_mode(ESP32_WIFI_MODE_STA); if (ret) { LOG_ERR("Failed to set Wi-Fi mode (%d)", ret); return -EAGAIN; } ret = esp_wifi_start(); if (ret) { LOG_ERR("Failed to start Wi-Fi driver (%d)", ret); return -EAGAIN; } } if (data->state != ESP32_STA_STARTED) { LOG_ERR("Wi-Fi not in station mode"); wifi_mgmt_raise_connect_result_event(esp32_wifi_iface, -1); return -EIO; } data->state = ESP32_STA_CONNECTING; memcpy(data->status.ssid, params->ssid, params->ssid_length); data->status.ssid[params->ssid_length] = '\0'; wifi_config_t wifi_config; memset(&wifi_config, 0, sizeof(wifi_config_t)); memcpy(wifi_config.sta.ssid, params->ssid, params->ssid_length); wifi_config.sta.ssid[params->ssid_length] = '\0'; switch (params->security) { case WIFI_SECURITY_TYPE_NONE: wifi_config.sta.threshold.authmode = WIFI_AUTH_OPEN; data->status.security = WIFI_AUTH_OPEN; wifi_config.sta.pmf_cfg.required = false; break; case WIFI_SECURITY_TYPE_PSK: memcpy(wifi_config.sta.password, params->psk, params->psk_length); wifi_config.sta.password[params->psk_length] = '\0'; wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK; wifi_config.sta.pmf_cfg.required = false; data->status.security = WIFI_AUTH_WPA2_PSK; break; case WIFI_SECURITY_TYPE_SAE: #if defined(CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE) if (params->sae_password) { memcpy(wifi_config.sta.password, params->sae_password, params->sae_password_length); wifi_config.sta.password[params->sae_password_length] = '\0'; } else { memcpy(wifi_config.sta.password, params->psk, params->psk_length); wifi_config.sta.password[params->psk_length] = '\0'; } data->status.security = WIFI_AUTH_WPA3_PSK; wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA3_PSK; wifi_config.sta.sae_pwe_h2e = WPA3_SAE_PWE_BOTH; break; #else LOG_ERR("WPA3 not supported for STA mode. Enable " "CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE"); return -EINVAL; #endif /* CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE */ default: LOG_ERR("Authentication method not supported"); return -EIO; } if (params->channel == WIFI_CHANNEL_ANY) { wifi_config.sta.channel = 0U; data->status.channel = 0U; } else { wifi_config.sta.channel = params->channel; data->status.channel = params->channel; } ret = esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config); if (ret) { LOG_ERR("Failed to set Wi-Fi configuration (%d)", ret); return -EINVAL; } ret = esp_wifi_connect(); if (ret) { LOG_ERR("Failed to connect to Wi-Fi access point (%d)", ret); return -EAGAIN; } return 0; } static int esp32_wifi_scan(const struct device *dev, struct wifi_scan_params *params, scan_result_cb_t cb) { struct esp32_wifi_runtime *data = dev->data; int ret = 0; if (data->scan_cb != NULL) { LOG_INF("Scan callback in progress"); return -EINPROGRESS; } data->scan_cb = cb; wifi_scan_config_t scan_config = { 0 }; if (params) { /* The enum values are same, so, no conversion needed */ scan_config.scan_type = params->scan_type; } ret = esp_wifi_set_mode(ESP32_WIFI_MODE_STA); ret |= esp_wifi_scan_start(&scan_config, false); if (ret != ESP_OK) { LOG_ERR("Failed to start Wi-Fi scanning"); return -EAGAIN; } return 0; }; static int esp32_wifi_ap_enable(const struct device *dev, struct wifi_connect_req_params *params) { struct esp32_wifi_runtime *data = dev->data; esp_err_t err = 0; /* Build Wi-Fi configuration for AP mode */ wifi_config_t wifi_config = { .ap = { .max_connection = 5, .channel = params->channel == WIFI_CHANNEL_ANY ? 0 : params->channel, }, }; memcpy(data->status.ssid, params->ssid, params->ssid_length); data->status.ssid[params->ssid_length] = '\0'; strncpy((char *) wifi_config.ap.ssid, params->ssid, params->ssid_length); wifi_config.ap.ssid_len = params->ssid_length; switch (params->security) { case WIFI_SECURITY_TYPE_NONE: memset(wifi_config.ap.password, 0, sizeof(wifi_config.ap.password)); wifi_config.ap.authmode = WIFI_AUTH_OPEN; data->status.security = WIFI_AUTH_OPEN; wifi_config.ap.pmf_cfg.required = false; break; case WIFI_SECURITY_TYPE_PSK: strncpy((char *) wifi_config.ap.password, params->psk, params->psk_length); wifi_config.ap.authmode = WIFI_AUTH_WPA2_PSK; data->status.security = WIFI_AUTH_WPA2_PSK; wifi_config.ap.pmf_cfg.required = false; break; default: LOG_ERR("Authentication method not supported"); return -EINVAL; } /* Start Wi-Fi in AP mode with configuration built above */ err = esp_wifi_set_mode(ESP32_WIFI_MODE_AP); if (err) { LOG_ERR("Failed to set Wi-Fi mode (%d)", err); return -EINVAL; } err = esp_wifi_set_config(WIFI_IF_AP, &wifi_config); if (err) { LOG_ERR("Failed to set Wi-Fi configuration (%d)", err); return -EINVAL; } err = esp_wifi_start(); if (err) { LOG_ERR("Failed to enable Wi-Fi AP mode"); return -EAGAIN; } net_eth_carrier_on(esp32_wifi_iface); return 0; }; static int esp32_wifi_ap_disable(const struct device *dev) { int err = 0; err = esp_wifi_stop(); if (err) { LOG_ERR("Failed to disable Wi-Fi AP mode: (%d)", err); return -EAGAIN; } return 0; }; static int esp32_wifi_status(const struct device *dev, struct wifi_iface_status *status) { struct esp32_wifi_runtime *data = dev->data; wifi_mode_t mode; wifi_config_t conf; wifi_ap_record_t ap_info; switch (data->state) { case ESP32_STA_STOPPED: case ESP32_AP_STOPPED: status->state = WIFI_STATE_INACTIVE; break; case ESP32_STA_STARTED: case ESP32_AP_DISCONNECTED: status->state = WIFI_STATE_DISCONNECTED; break; case ESP32_STA_CONNECTING: status->state = WIFI_STATE_SCANNING; break; case ESP32_STA_CONNECTED: case ESP32_AP_CONNECTED: status->state = WIFI_STATE_COMPLETED; break; default: break; } strncpy(status->ssid, data->status.ssid, WIFI_SSID_MAX_LEN); status->ssid_len = strnlen(data->status.ssid, WIFI_SSID_MAX_LEN); status->band = WIFI_FREQ_BAND_2_4_GHZ; status->link_mode = WIFI_LINK_MODE_UNKNOWN; status->mfp = WIFI_MFP_DISABLE; if (esp_wifi_get_mode(&mode) == ESP_OK) { if (mode == ESP32_WIFI_MODE_STA) { wifi_phy_mode_t phy_mode; esp_err_t err; esp_wifi_get_config(ESP_IF_WIFI_STA, &conf); esp_wifi_sta_get_ap_info(&ap_info); status->iface_mode = WIFI_MODE_INFRA; status->channel = ap_info.primary; status->rssi = ap_info.rssi; memcpy(status->bssid, ap_info.bssid, WIFI_MAC_ADDR_LEN); err = esp_wifi_sta_get_negotiated_phymode(&phy_mode); if (err == ESP_OK) { if (phy_mode == WIFI_PHY_MODE_11B) { status->link_mode = WIFI_1; } else if (phy_mode == WIFI_PHY_MODE_11G) { status->link_mode = WIFI_3; } else if ((phy_mode == WIFI_PHY_MODE_HT20) || (phy_mode == WIFI_PHY_MODE_HT40)) { status->link_mode = WIFI_4; } else if (phy_mode == WIFI_PHY_MODE_HE20) { status->link_mode = WIFI_6; } } status->beacon_interval = conf.sta.listen_interval; } else if (mode == ESP32_WIFI_MODE_AP) { esp_wifi_get_config(ESP_IF_WIFI_AP, &conf); status->iface_mode = WIFI_MODE_AP; status->link_mode = WIFI_LINK_MODE_UNKNOWN; status->channel = conf.ap.channel; status->beacon_interval = conf.ap.beacon_interval; } else { status->iface_mode = WIFI_MODE_UNKNOWN; status->link_mode = WIFI_LINK_MODE_UNKNOWN; status->channel = 0; } } switch (data->status.security) { case WIFI_AUTH_OPEN: status->security = WIFI_SECURITY_TYPE_NONE; break; case WIFI_AUTH_WPA2_PSK: status->security = WIFI_SECURITY_TYPE_PSK; break; case WIFI_AUTH_WPA3_PSK: status->security = WIFI_SECURITY_TYPE_SAE; break; default: status->security = WIFI_SECURITY_TYPE_UNKNOWN; } return 0; } static void esp32_wifi_init(struct net_if *iface) { const struct device *dev = net_if_get_device(iface); struct esp32_wifi_runtime *dev_data = dev->data; struct ethernet_context *eth_ctx = net_if_l2_data(iface); eth_ctx->eth_if_type = L2_ETH_IF_TYPE_WIFI; esp32_wifi_iface = iface; dev_data->state = ESP32_STA_STOPPED; /* Start interface when we are actually connected with Wi-Fi network */ esp_read_mac(dev_data->mac_addr, ESP_MAC_WIFI_STA); /* Assign link local address. */ net_if_set_link_addr(iface, dev_data->mac_addr, 6, NET_LINK_ETHERNET); ethernet_init(iface); net_if_carrier_off(iface); wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT(); esp_err_t ret = esp_wifi_init(&config); esp_wifi_internal_reg_rxcb(ESP_IF_WIFI_STA, eth_esp32_rx); ret |= esp_wifi_set_mode(ESP32_WIFI_MODE_STA); ret |= esp_wifi_start(); if (ret != ESP_OK) { LOG_ERR("Failed to start Wi-Fi driver"); } } #if defined(CONFIG_NET_STATISTICS_WIFI) static int esp32_wifi_stats(const struct device *dev, struct net_stats_wifi *stats) { struct esp32_wifi_runtime *data = dev->data; stats->bytes.received = data->stats.bytes.received; stats->bytes.sent = data->stats.bytes.sent; stats->pkts.rx = data->stats.pkts.rx; stats->pkts.tx = data->stats.pkts.tx; stats->errors.rx = data->stats.errors.rx; stats->errors.tx = data->stats.errors.tx; stats->broadcast.rx = data->stats.broadcast.rx; stats->broadcast.tx = data->stats.broadcast.tx; stats->multicast.rx = data->stats.multicast.rx; stats->multicast.tx = data->stats.multicast.tx; stats->sta_mgmt.beacons_rx = data->stats.sta_mgmt.beacons_rx; stats->sta_mgmt.beacons_miss = data->stats.sta_mgmt.beacons_miss; return 0; } #endif static int esp32_wifi_dev_init(const struct device *dev) { esp_timer_init(); if (IS_ENABLED(CONFIG_ESP32_WIFI_STA_AUTO_DHCPV4)) { net_mgmt_init_event_callback(&esp32_dhcp_cb, wifi_event_handler, DHCPV4_MASK); net_mgmt_add_event_callback(&esp32_dhcp_cb); } return 0; } static const struct wifi_mgmt_ops esp32_wifi_mgmt = { .scan = esp32_wifi_scan, .connect = esp32_wifi_connect, .disconnect = esp32_wifi_disconnect, .ap_enable = esp32_wifi_ap_enable, .ap_disable = esp32_wifi_ap_disable, .iface_status = esp32_wifi_status, #if defined(CONFIG_NET_STATISTICS_WIFI) .get_stats = esp32_wifi_stats, #endif }; static const struct net_wifi_mgmt_offload esp32_api = { .wifi_iface.iface_api.init = esp32_wifi_init, .wifi_iface.send = esp32_wifi_send, .wifi_mgmt_api = &esp32_wifi_mgmt, }; NET_DEVICE_DT_INST_DEFINE(0, esp32_wifi_dev_init, NULL, &esp32_data, NULL, CONFIG_WIFI_INIT_PRIORITY, &esp32_api, ETHERNET_L2, NET_L2_GET_CTX_TYPE(ETHERNET_L2), NET_ETH_MTU); CONNECTIVITY_WIFI_MGMT_BIND(Z_DEVICE_DT_DEV_ID(DT_DRV_INST(0))); ```
/content/code_sandbox/drivers/wifi/esp32/src/esp_wifi_drv.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
5,567
```objective-c /* * an affiliate of Cypress Semiconductor Corporation * */ #include <whd_buffer_api.h> #include <zephyr/sd/sd.h> #include <zephyr/sd/sdio.h> #include <zephyr/drivers/gpio.h> #include <zephyr/net/wifi_mgmt.h> #include <cy_utils.h> struct airoc_wifi_data { struct sd_card card; struct sdio_func sdio_func1; struct sdio_func sdio_func2; struct net_if *iface; bool second_interface_init; bool is_ap_up; bool is_sta_connected; uint8_t mac_addr[6]; scan_result_cb_t scan_rslt_cb; whd_ssid_t ssid; whd_scan_result_t scan_result; struct k_sem sema_common; struct k_sem sema_scan; #if defined(CONFIG_NET_STATISTICS_WIFI) struct net_stats_wifi stats; #endif whd_driver_t whd_drv; struct gpio_callback host_oob_pin_cb; uint8_t frame_buf[NET_ETH_MAX_FRAME_SIZE]; }; struct airoc_wifi_config { const struct device *sdhc_dev; struct gpio_dt_spec wifi_reg_on_gpio; struct gpio_dt_spec wifi_host_wake_gpio; struct gpio_dt_spec wifi_dev_wake_gpio; }; /** * \brief This function returns pointer type to handle instance * of whd interface (whd_interface_t) which allocated in * Zephyr AIROC driver (drivers/wifi/infineon/airoc_wifi.c) */ whd_interface_t airoc_wifi_get_whd_interface(void); ```
/content/code_sandbox/drivers/wifi/infineon/airoc_wifi.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
326
```c /* * an affiliate of Cypress Semiconductor Corporation * */ #include <airoc_wifi.h> #include <bus_protocols/whd_bus_sdio_protocol.h> #include <bus_protocols/whd_bus.h> #include <bus_protocols/whd_sdio.h> #include <zephyr/sd/sd.h> #include <cy_utils.h> #define DT_DRV_COMPAT infineon_airoc_wifi LOG_MODULE_REGISTER(infineon_airoc, CONFIG_WIFI_LOG_LEVEL); #ifdef __cplusplus extern "C" { #endif /** Defines the amount of stack memory available for the wifi thread. */ #if !defined(CY_WIFI_THREAD_STACK_SIZE) #define CY_WIFI_THREAD_STACK_SIZE (5120) #endif /** Defines the priority of the thread that services wifi packets. Legal values are defined by the * RTOS being used. */ #if !defined(CY_WIFI_THREAD_PRIORITY) #define CY_WIFI_THREAD_PRIORITY (CY_RTOS_PRIORITY_HIGH) #endif /** Defines the country this will operate in for wifi initialization parameters. See the * wifi-host-driver's whd_country_code_t for legal options. */ #if !defined(CY_WIFI_COUNTRY) #define CY_WIFI_COUNTRY (WHD_COUNTRY_AUSTRALIA) #endif /** Defines the priority of the interrupt that handles out-of-band notifications from the wifi * chip. Legal values are defined by the MCU running this code. */ #if !defined(CY_WIFI_OOB_INTR_PRIORITY) #define CY_WIFI_OOB_INTR_PRIORITY (2) #endif /** Defines whether to use the out-of-band pin to allow the WIFI chip to wake up the MCU. */ #if defined(CY_WIFI_HOST_WAKE_SW_FORCE) #define CY_USE_OOB_INTR (CY_WIFI_HOST_WAKE_SW_FORCE) #else #define CY_USE_OOB_INTR (1u) #endif /* defined(CY_WIFI_HOST_WAKE_SW_FORCE) */ #define CY_WIFI_HOST_WAKE_IRQ_EVENT GPIO_INT_TRIG_LOW #define DEFAULT_OOB_PIN (0) #define WLAN_POWER_UP_DELAY_MS (250) #define WLAN_CBUCK_DISCHARGE_MS (10) extern whd_resource_source_t resource_ops; struct whd_bus_priv { whd_sdio_config_t sdio_config; whd_bus_stats_t whd_bus_stats; whd_sdio_t sdio_obj; }; static whd_init_config_t init_config_default = { .thread_stack_size = CY_WIFI_THREAD_STACK_SIZE, .thread_stack_start = NULL, .thread_priority = (uint32_t)CY_WIFI_THREAD_PRIORITY, .country = CY_WIFI_COUNTRY }; /****************************************************** * Function ******************************************************/ int airoc_wifi_power_on(const struct device *dev) { #if DT_INST_NODE_HAS_PROP(0, wifi_reg_on_gpios) int ret; const struct airoc_wifi_config *config = dev->config; /* Check WIFI REG_ON gpio instance */ if (!device_is_ready(config->wifi_reg_on_gpio.port)) { LOG_ERR("Error: failed to configure wifi_reg_on %s pin %d", config->wifi_reg_on_gpio.port->name, config->wifi_reg_on_gpio.pin); return -EIO; } /* Configure wifi_reg_on as output */ ret = gpio_pin_configure_dt(&config->wifi_reg_on_gpio, GPIO_OUTPUT); if (ret) { LOG_ERR("Error %d: failed to configure wifi_reg_on %s pin %d", ret, config->wifi_reg_on_gpio.port->name, config->wifi_reg_on_gpio.pin); return ret; } ret = gpio_pin_set_dt(&config->wifi_reg_on_gpio, 0); if (ret) { return ret; } /* Allow CBUCK regulator to discharge */ (void)k_msleep(WLAN_CBUCK_DISCHARGE_MS); /* WIFI power on */ ret = gpio_pin_set_dt(&config->wifi_reg_on_gpio, 1); if (ret) { return ret; } (void)k_msleep(WLAN_POWER_UP_DELAY_MS); #endif /* DT_INST_NODE_HAS_PROP(0, reg_on_gpios) */ return 0; } int airoc_wifi_init_primary(const struct device *dev, whd_interface_t *interface, whd_netif_funcs_t *netif_funcs, whd_buffer_funcs_t *buffer_if) { int ret; struct airoc_wifi_data *data = dev->data; const struct airoc_wifi_config *config = dev->config; whd_sdio_config_t whd_sdio_config = { .sdio_1bit_mode = WHD_FALSE, .high_speed_sdio_clock = WHD_FALSE, }; #if DT_INST_NODE_HAS_PROP(0, wifi_host_wake_gpios) whd_oob_config_t oob_config = { .host_oob_pin = (void *)&config->wifi_host_wake_gpio, .dev_gpio_sel = DEFAULT_OOB_PIN, .is_falling_edge = (CY_WIFI_HOST_WAKE_IRQ_EVENT == GPIO_INT_TRIG_LOW) ? WHD_TRUE : WHD_FALSE, .intr_priority = CY_WIFI_OOB_INTR_PRIORITY}; whd_sdio_config.oob_config = oob_config; #endif if (airoc_wifi_power_on(dev)) { LOG_ERR("airoc_wifi_power_on retuens fail"); return -ENODEV; } if (!device_is_ready(config->sdhc_dev)) { LOG_ERR("SDHC device is not ready"); return -ENODEV; } ret = sd_init(config->sdhc_dev, &data->card); if (ret) { return ret; } /* Init SDIO functions */ ret = sdio_init_func(&data->card, &data->sdio_func1, BACKPLANE_FUNCTION); if (ret) { LOG_ERR("sdio_enable_func BACKPLANE_FUNCTION, error: %x", ret); return ret; } ret = sdio_init_func(&data->card, &data->sdio_func2, WLAN_FUNCTION); if (ret) { LOG_ERR("sdio_enable_func WLAN_FUNCTION, error: %x", ret); return ret; } ret = sdio_set_block_size(&data->sdio_func1, SDIO_64B_BLOCK); if (ret) { LOG_ERR("Can't set block size for BACKPLANE_FUNCTION, error: %x", ret); return ret; } ret = sdio_set_block_size(&data->sdio_func2, SDIO_64B_BLOCK); if (ret) { LOG_ERR("Can't set block size for WLAN_FUNCTION, error: %x", ret); return ret; } /* Init wifi host driver (whd) */ cy_rslt_t whd_ret = whd_init(&data->whd_drv, &init_config_default, &resource_ops, buffer_if, netif_funcs); if (whd_ret == CY_RSLT_SUCCESS) { whd_ret = whd_bus_sdio_attach(data->whd_drv, &whd_sdio_config, (whd_sdio_t)&data->card); if (whd_ret == CY_RSLT_SUCCESS) { whd_ret = whd_wifi_on(data->whd_drv, interface); } if (whd_ret != CY_RSLT_SUCCESS) { whd_deinit(*interface); return -ENODEV; } } return 0; } /* * Implement SDIO CMD52/53 wrappers */ static struct sdio_func *airoc_wifi_get_sdio_func(struct sd_card *sd, whd_bus_function_t function) { struct airoc_wifi_data *data = CONTAINER_OF(sd, struct airoc_wifi_data, card); struct sdio_func *func[] = {&sd->func0, &data->sdio_func1, &data->sdio_func2}; if (function > WLAN_FUNCTION) { return NULL; } return func[function]; } whd_result_t whd_bus_sdio_cmd52(whd_driver_t whd_driver, whd_bus_transfer_direction_t direction, whd_bus_function_t function, uint32_t address, uint8_t value, sdio_response_needed_t response_expected, uint8_t *response) { int ret; struct sd_card *sd = whd_driver->bus_priv->sdio_obj; struct sdio_func *func = airoc_wifi_get_sdio_func(sd, function); WHD_BUS_STATS_INCREMENT_VARIABLE(whd_driver->bus_priv, cmd52); if (direction == BUS_WRITE) { ret = sdio_rw_byte(func, address, value, response); } else { ret = sdio_read_byte(func, address, response); } WHD_BUS_STATS_CONDITIONAL_INCREMENT_VARIABLE(whd_driver->bus_priv, (ret != WHD_SUCCESS), cmd52_fail); /* Possibly device might not respond to this cmd. So, don't check return value here */ if ((ret != WHD_SUCCESS) && (address == SDIO_SLEEP_CSR)) { return ret; } CHECK_RETURN(ret); return WHD_SUCCESS; } whd_result_t whd_bus_sdio_cmd53(whd_driver_t whd_driver, whd_bus_transfer_direction_t direction, whd_bus_function_t function, sdio_transfer_mode_t mode, uint32_t address, uint16_t data_size, uint8_t *data, sdio_response_needed_t response_expected, uint32_t *response) { whd_result_t ret; struct sd_card *sd = whd_driver->bus_priv->sdio_obj; struct sdio_func *func = airoc_wifi_get_sdio_func(sd, function); if (direction == BUS_WRITE) { WHD_BUS_STATS_INCREMENT_VARIABLE(whd_driver->bus_priv, cmd53_write); ret = sdio_write_addr(func, address, data, data_size); } else { WHD_BUS_STATS_INCREMENT_VARIABLE(whd_driver->bus_priv, cmd53_read); ret = sdio_read_addr(func, address, data, data_size); } WHD_BUS_STATS_CONDITIONAL_INCREMENT_VARIABLE( whd_driver->bus_priv, ((ret != WHD_SUCCESS) && (direction == BUS_READ)), cmd53_read_fail); WHD_BUS_STATS_CONDITIONAL_INCREMENT_VARIABLE( whd_driver->bus_priv, ((ret != WHD_SUCCESS) && (direction == BUS_WRITE)), cmd53_write_fail); CHECK_RETURN(ret); return WHD_SUCCESS; } /* * Implement SDIO Card interrupt */ void whd_bus_sdio_irq_handler(const struct device *dev, int reason, const void *user_data) { if (reason == SDHC_INT_SDIO) { whd_driver_t whd_driver = (whd_driver_t)user_data; WHD_BUS_STATS_INCREMENT_VARIABLE(whd_driver->bus_priv, sdio_intrs); /* call thread notify to wake up WHD thread */ whd_thread_notify_irq(whd_driver); } } whd_result_t whd_bus_sdio_irq_register(whd_driver_t whd_driver) { /* Nothing to do here, all handles by whd_bus_sdio_irq_enable function */ return WHD_SUCCESS; } whd_result_t whd_bus_sdio_irq_enable(whd_driver_t whd_driver, whd_bool_t enable) { int ret; struct sd_card *sd = whd_driver->bus_priv->sdio_obj; /* Enable/disable SDIO Card interrupts */ if (enable) { ret = sdhc_enable_interrupt(sd->sdhc, whd_bus_sdio_irq_handler, SDHC_INT_SDIO, whd_driver); } else { ret = sdhc_disable_interrupt(sd->sdhc, SDHC_INT_SDIO); } return ret; } /* * Implement OOB functionality */ void whd_bus_sdio_oob_irq_handler(const struct device *port, struct gpio_callback *cb, gpio_port_pins_t pins) { #if DT_INST_NODE_HAS_PROP(0, wifi_host_wake_gpios) struct airoc_wifi_data *data = CONTAINER_OF(cb, struct airoc_wifi_data, host_oob_pin_cb); /* Get OOB pin info */ const whd_oob_config_t *oob_config = &data->whd_drv->bus_priv->sdio_config.oob_config; const struct gpio_dt_spec *host_oob_pin = oob_config->host_oob_pin; /* Check OOB state is correct */ int expected_event = (oob_config->is_falling_edge == WHD_TRUE) ? 0 : 1; if (!(pins & BIT(host_oob_pin->pin)) || (gpio_pin_get_dt(host_oob_pin) != expected_event)) { WPRINT_WHD_ERROR(("Unexpected interrupt event %d\n", expected_event)); WHD_BUS_STATS_INCREMENT_VARIABLE(data->whd_drv->bus_priv, error_intrs); return; } WHD_BUS_STATS_INCREMENT_VARIABLE(data->whd_drv->bus_priv, oob_intrs); /* Call thread notify to wake up WHD thread */ whd_thread_notify_irq(data->whd_drv); #endif /* DT_INST_NODE_HAS_PROP(0, wifi-host-wake-gpios) */ } whd_result_t whd_bus_sdio_register_oob_intr(whd_driver_t whd_driver) { #if DT_INST_NODE_HAS_PROP(0, wifi_host_wake_gpios) int ret; const struct device *dev = DEVICE_DT_GET(DT_DRV_INST(0)); struct airoc_wifi_data *data = dev->data; /* Get OOB pin info */ const whd_oob_config_t *oob_config = &whd_driver->bus_priv->sdio_config.oob_config; const struct gpio_dt_spec *host_oob_pin = oob_config->host_oob_pin; /* Check if OOB pin is ready */ if (!gpio_is_ready_dt(host_oob_pin)) { WPRINT_WHD_ERROR(("%s: Failed at gpio_is_ready_dt for host_oob_pin\n", __func__)); return WHD_HAL_ERROR; } /* Configure OOB pin as output */ ret = gpio_pin_configure_dt(host_oob_pin, GPIO_INPUT); if (ret != 0) { WPRINT_WHD_ERROR(( " %s: Failed at gpio_pin_configure_dt for host_oob_pin, result code = %d\n", __func__, ret)); return WHD_HAL_ERROR; } /* Initialize/add OOB pin callback */ gpio_init_callback(&data->host_oob_pin_cb, whd_bus_sdio_oob_irq_handler, BIT(host_oob_pin->pin)); ret = gpio_add_callback_dt(host_oob_pin, &data->host_oob_pin_cb); if (ret != 0) { WPRINT_WHD_ERROR( ("%s: Failed at gpio_add_callback_dt for host_oob_pin, result code = %d\n", __func__, ret)); return WHD_HAL_ERROR; } #endif /* DT_INST_NODE_HAS_PROP(0, wifi_host_wake_gpios) */ return WHD_SUCCESS; } whd_result_t whd_bus_sdio_unregister_oob_intr(whd_driver_t whd_driver) { #if DT_INST_NODE_HAS_PROP(0, wifi_host_wake_gpios) int ret; const whd_oob_config_t *oob_config = &whd_driver->bus_priv->sdio_config.oob_config; /* Disable OOB pin interrupts */ ret = gpio_pin_interrupt_configure_dt(oob_config->host_oob_pin, GPIO_INT_DISABLE); if (ret != 0) { WPRINT_WHD_ERROR(("%s: Failed at gpio_pin_interrupt_configure_dt for host_oob_pin, " "result code = %d\n", __func__, ret)); return WHD_HAL_ERROR; } #endif /* DT_INST_NODE_HAS_PROP(0, wifi_host_wake_gpios) */ return WHD_SUCCESS; } whd_result_t whd_bus_sdio_enable_oob_intr(whd_driver_t whd_driver, whd_bool_t enable) { #if DT_INST_NODE_HAS_PROP(0, wifi_host_wake_gpios) int ret; const whd_oob_config_t *oob_config = &whd_driver->bus_priv->sdio_config.oob_config; uint32_t trig_conf = (oob_config->is_falling_edge == WHD_TRUE) ? GPIO_INT_TRIG_LOW : GPIO_INT_TRIG_HIGH; /* Enable OOB pin interrupts */ ret = gpio_pin_interrupt_configure_dt(oob_config->host_oob_pin, GPIO_INT_ENABLE | GPIO_INT_EDGE | trig_conf); if (ret != 0) { WPRINT_WHD_ERROR(("%s: Failed at gpio_pin_interrupt_configure_dt for host_oob_pin, " "result code = %d\n", __func__, ret)); return WHD_HAL_ERROR; } #endif /* DT_INST_NODE_HAS_PROP(0, wifi_host_wake_gpios) */ return WHD_SUCCESS; } /* * Implement WHD memory wrappers */ void *whd_mem_malloc(size_t size) { return k_malloc(size); } void *whd_mem_calloc(size_t nitems, size_t size) { return k_calloc(nitems, size); } void whd_mem_free(void *ptr) { k_free(ptr); } #ifdef __cplusplus } /* extern "C" */ #endif ```
/content/code_sandbox/drivers/wifi/infineon/airoc_whd_hal.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,670
```unknown # an affiliate of Cypress Semiconductor Corporation menuconfig WIFI_AIROC bool "Infineon AIROC SoC Wi-Fi support" select THREAD_CUSTOM_DATA select WIFI_OFFLOAD select NET_L2_WIFI_MGMT select SDIO_STACK select SDHC select WIFI_USE_NATIVE_NETWORKING select USE_INFINEON_ABSTRACTION_RTOS depends on DT_HAS_INFINEON_AIROC_WIFI_ENABLED help Enable Infineon AIROC SoC Wi-Fi support. if WIFI_AIROC config AIROC_WIFI_EVENT_TASK_STACK_SIZE int "Event Task Stack Size" default 4096 config AIROC_WIFI_EVENT_TASK_PRIO int "Event Task Priority" default 4 config AIROC_WLAN_MFG_FIRMWARE bool "WLAN Manufacturing Firmware" help Enable WLAN Manufacturing Firmware. config AIROC_WIFI_CUSTOM bool "Custom CYW43xx device/module" help Select Custom CYW43xx device/module. For this option, user must to provide path to FW, CLM and NVRAM for custom or vendor CYW43xx modules. choice AIROC_PART prompt "Select AIROC part" depends on !AIROC_WIFI_CUSTOM config CYW4343W bool "CYW4343W" help Enable Infineon AIROC CYW4343W Wi-Fi connectivity, More information about CYW4343W device you can find on path_to_url config CYW4373 bool "CYW4373" help Enable Infineon AIROC CYW4373 Wi-Fi connectivity, More information about CYW4373 device you can find on path_to_url config CYW43012 bool "CYW43012" help Enable Infineon AIROC CYW43012 Wi-Fi connectivity, More information about CYW43012 device you can find on path_to_url config CYW43438 bool "CYW43438" help Enable Infineon AIROC CYW43438 Wi-Fi connectivity, More information about CYW43438 device you can find on path_to_url config CYW43439 bool "CYW43439" help Enable Infineon AIROC CYW43439 Wi-Fi connectivity, More information about CYW43439 device you can find on path_to_url endchoice choice CYW43012_MODULE prompt "Select CYW43012 module" depends on CYW43012 && !AIROC_WIFI_CUSTOM config CYW43012_MURATA_1LV bool "MURATA-1LV" help Murata Type 1LV module based on Infineon CYW43012 combo chipset which supports Wi-Fi 802.11a/b/g/n + Bluetooth 5.0 BR/EDR/LE up to 72.2Mbps PHY data rate on Wi-fi and 3Mbps PHY data rate on Bluetooth. 2Mbps LE PHY is also supported. Detailed information about Murata Type 1LV module you can find on path_to_url endchoice choice CYW4343W_MODULE prompt "Select CYW4343W module" depends on CYW4343W && !AIROC_WIFI_CUSTOM config CYW4343W_MURATA_1DX bool "MURATA-1DX" help Murata Type 1DX modules based on Infineon CYW4343W combo chipset which supports Wi-Fi 802.11b/g/n + Bluetooth 5.1 BR/EDR/LE up to 65Mbps PHY data rate on Wi-fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Type 1DX module you can find on path_to_url endchoice choice CYW4373_MODULE prompt "Select CYW4373 module" depends on CYW4373 && !AIROC_WIFI_CUSTOM config CYW4373_STERLING_LWB5PLUS bool "STERLING-LWB5plus" help Ezurio Sterling LWB5+ 802.11ac / Bluetooth 5.0 M.2 Carrier Board (E-Type Key w/ SDIO/UART) Detailed information about Type Sterling LWB5+ module you can find on path_to_url endchoice choice CYW43439_MODULE prompt "Select CYW43439 module" depends on CYW43439 && !AIROC_WIFI_CUSTOM config CYW43439_MURATA_1YN bool "MURATA_1YN" help Murata Type 1YN module based on Infineon CYW43439 combo chipset which supports Wi-Fi 802.11b/g/n + Bluetooth 5.2 BR/EDR/LE up to 65Mbps PHY data rate on Wi-fi and 3Mbps PHY data rate on Bluetooth. Detailed information about Murata Type 1YN module you can find on path_to_url endchoice endif # AIROC_WIFI ```
/content/code_sandbox/drivers/wifi/infineon/Kconfig.airoc
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,088
```objective-c /** * */ #ifndef ZEPHYR_DRIVERS_WIFI_ESWIFI_ESWIFI_OFFLOAD_H_ #define ZEPHYR_DRIVERS_WIFI_ESWIFI_ESWIFI_OFFLOAD_H_ #include <zephyr/net/net_offload.h> #include "eswifi.h" #define ESWIFI_OFFLOAD_MAX_SOCKETS 4 enum eswifi_transport_type { ESWIFI_TRANSPORT_TCP, ESWIFI_TRANSPORT_UDP, ESWIFI_TRANSPORT_UDP_LITE, ESWIFI_TRANSPORT_TCP_SSL, }; enum eswifi_socket_state { ESWIFI_SOCKET_STATE_NONE, ESWIFI_SOCKET_STATE_CONNECTING, ESWIFI_SOCKET_STATE_CONNECTED, ESWIFI_SOCKET_STATE_ACCEPTING, }; struct eswifi_off_socket { uint8_t index; enum eswifi_transport_type type; enum eswifi_socket_state state; struct net_context *context; net_context_recv_cb_t recv_cb; net_context_connect_cb_t conn_cb; net_context_send_cb_t send_cb; net_tcp_accept_cb_t accept_cb; void *recv_data; void *conn_data; void *send_data; void *accept_data; struct net_pkt *tx_pkt; struct k_work connect_work; struct k_work send_work; struct k_work_delayable read_work; struct sockaddr peer_addr; struct k_sem read_sem; struct k_sem accept_sem; uint16_t port; bool is_server; int usage; struct k_fifo fifo; struct net_pkt *prev_pkt_rem; }; #endif ```
/content/code_sandbox/drivers/wifi/eswifi/eswifi_offload.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
307
```c /* * an affiliate of Cypress Semiconductor Corporation * */ /** * @brief AIROC Wi-Fi driver. */ #define DT_DRV_COMPAT infineon_airoc_wifi #include <zephyr/logging/log.h> #include <zephyr/net/conn_mgr/connectivity_wifi_mgmt.h> #include <airoc_wifi.h> LOG_MODULE_REGISTER(infineon_airoc_wifi, CONFIG_WIFI_LOG_LEVEL); #ifndef AIROC_WIFI_TX_PACKET_POOL_COUNT #define AIROC_WIFI_TX_PACKET_POOL_COUNT (10) #endif #ifndef AIROC_WIFI_RX_PACKET_POOL_COUNT #define AIROC_WIFI_RX_PACKET_POOL_COUNT (10) #endif #ifndef AIROC_WIFI_PACKET_POOL_SIZE #define AIROC_WIFI_PACKET_POOL_SIZE (1600) #endif #define AIROC_WIFI_PACKET_POOL_COUNT \ (AIROC_WIFI_TX_PACKET_POOL_COUNT + AIROC_WIFI_RX_PACKET_POOL_COUNT) #define AIROC_WIFI_WAIT_SEMA_MS (30 * 1000) #define AIROC_WIFI_SCAN_TIMEOUT_MS (12 * 1000) /* AIROC private functions */ static whd_result_t airoc_wifi_host_buffer_get(whd_buffer_t *buffer, whd_buffer_dir_t direction, uint16_t size, uint32_t timeout_ms); static void airoc_wifi_buffer_release(whd_buffer_t buffer, whd_buffer_dir_t direction); static uint8_t *airoc_wifi_buffer_get_current_piece_data_pointer(whd_buffer_t buffer); static uint16_t airoc_wifi_buffer_get_current_piece_size(whd_buffer_t buffer); static whd_result_t airoc_wifi_buffer_set_size(whd_buffer_t buffer, unsigned short size); static whd_result_t airoc_wifi_buffer_add_remove_at_front(whd_buffer_t *buffer, int32_t add_remove_amount); static void airoc_wifi_network_process_ethernet_data(whd_interface_t interface, whd_buffer_t buffer); int airoc_wifi_init_primary(const struct device *dev, whd_interface_t *interface, whd_netif_funcs_t *netif_funcs, whd_buffer_funcs_t *buffer_if); /* Allocate network pool */ NET_BUF_POOL_FIXED_DEFINE(airoc_pool, AIROC_WIFI_PACKET_POOL_COUNT, AIROC_WIFI_PACKET_POOL_SIZE, 0, NULL); /* AIROC globals */ static uint16_t ap_event_handler_index = 0xFF; /* Use global iface pointer to support any Ethernet driver */ /* necessary for wifi callback functions */ static struct net_if *airoc_wifi_iface; static whd_interface_t airoc_if; static whd_interface_t airoc_sta_if; static whd_interface_t airoc_ap_if; static const whd_event_num_t sta_link_events[] = { WLC_E_LINK, WLC_E_DEAUTH_IND, WLC_E_DISASSOC_IND, WLC_E_PSK_SUP, WLC_E_CSA_COMPLETE_IND, WLC_E_NONE}; static const whd_event_num_t ap_link_events[] = {WLC_E_DISASSOC_IND, WLC_E_DEAUTH_IND, WLC_E_ASSOC_IND, WLC_E_REASSOC_IND, WLC_E_AUTHORIZED, WLC_E_NONE}; static uint16_t sta_event_handler_index = 0xFF; static void airoc_event_task(void); static struct airoc_wifi_data airoc_wifi_data = {0}; static struct airoc_wifi_config airoc_wifi_config = { .sdhc_dev = DEVICE_DT_GET(DT_INST_PARENT(0)), .wifi_reg_on_gpio = GPIO_DT_SPEC_GET_OR(DT_DRV_INST(0), wifi_reg_on_gpios, {0}), .wifi_host_wake_gpio = GPIO_DT_SPEC_GET_OR(DT_DRV_INST(0), wifi_host_wake_gpios, {0}), .wifi_dev_wake_gpio = GPIO_DT_SPEC_GET_OR(DT_DRV_INST(0), wifi_dev_wake_gpios, {0}), }; static whd_buffer_funcs_t airoc_wifi_buffer_if_default = { .whd_host_buffer_get = airoc_wifi_host_buffer_get, .whd_buffer_release = airoc_wifi_buffer_release, .whd_buffer_get_current_piece_data_pointer = airoc_wifi_buffer_get_current_piece_data_pointer, .whd_buffer_get_current_piece_size = airoc_wifi_buffer_get_current_piece_size, .whd_buffer_set_size = airoc_wifi_buffer_set_size, .whd_buffer_add_remove_at_front = airoc_wifi_buffer_add_remove_at_front, }; static whd_netif_funcs_t airoc_wifi_netif_if_default = { .whd_network_process_ethernet_data = airoc_wifi_network_process_ethernet_data, }; K_MSGQ_DEFINE(airoc_wifi_msgq, sizeof(whd_event_header_t), 10, 4); K_THREAD_STACK_DEFINE(airoc_wifi_event_stack, CONFIG_AIROC_WIFI_EVENT_TASK_STACK_SIZE); static struct k_thread airoc_wifi_event_thread; struct airoc_wifi_event_t { uint8_t is_ap_event; uint32_t event_type; }; /* * AIROC Wi-Fi helper functions */ whd_interface_t airoc_wifi_get_whd_interface(void) { return airoc_if; } static void airoc_wifi_scan_cb_search(whd_scan_result_t **result_ptr, void *user_data, whd_scan_status_t status) { if (status == WHD_SCAN_ABORTED) { k_sem_give(&airoc_wifi_data.sema_scan); return; } if (status == WHD_SCAN_COMPLETED_SUCCESSFULLY) { k_sem_give(&airoc_wifi_data.sema_scan); } else if ((status == WHD_SCAN_INCOMPLETE) && (user_data != NULL) && ((**result_ptr).SSID.length == ((whd_scan_result_t *)user_data)->SSID.length)) { if (strncmp(((whd_scan_result_t *)user_data)->SSID.value, (**result_ptr).SSID.value, (**result_ptr).SSID.length) == 0) { memcpy(user_data, *result_ptr, sizeof(whd_scan_result_t)); } } } static int convert_whd_security_to_zephyr(whd_security_t security) { int zephyr_security = WIFI_SECURITY_TYPE_UNKNOWN; switch (security) { case WHD_SECURITY_OPEN: zephyr_security = WIFI_SECURITY_TYPE_NONE; break; case WHD_SECURITY_WEP_PSK: zephyr_security = WIFI_SECURITY_TYPE_WEP; break; case WHD_SECURITY_WPA3_WPA2_PSK: case WHD_SECURITY_WPA2_AES_PSK: zephyr_security = WIFI_SECURITY_TYPE_PSK; break; case WHD_SECURITY_WPA2_AES_PSK_SHA256: zephyr_security = WIFI_SECURITY_TYPE_PSK_SHA256; break; case WHD_SECURITY_WPA3_SAE: zephyr_security = WIFI_SECURITY_TYPE_SAE; break; case WHD_SECURITY_WPA_AES_PSK: zephyr_security = WIFI_SECURITY_TYPE_WPA_PSK; break; default: if ((security & ENTERPRISE_ENABLED) != 0) { zephyr_security = WIFI_SECURITY_TYPE_EAP; } break; } return zephyr_security; } static void parse_scan_result(whd_scan_result_t *p_whd_result, struct wifi_scan_result *p_zy_result) { if (p_whd_result->SSID.length != 0) { p_zy_result->ssid_length = p_whd_result->SSID.length; strncpy(p_zy_result->ssid, p_whd_result->SSID.value, p_whd_result->SSID.length); p_zy_result->channel = p_whd_result->channel; p_zy_result->security = convert_whd_security_to_zephyr(p_whd_result->security); p_zy_result->rssi = (int8_t)p_whd_result->signal_strength; p_zy_result->mac_length = 6; memcpy(p_zy_result->mac, &p_whd_result->BSSID, 6); } } static void scan_callback(whd_scan_result_t **result_ptr, void *user_data, whd_scan_status_t status) { struct airoc_wifi_data *data = user_data; whd_scan_result_t whd_scan_result; struct wifi_scan_result zephyr_scan_result; if (status == WHD_SCAN_COMPLETED_SUCCESSFULLY || status == WHD_SCAN_ABORTED) { data->scan_rslt_cb(data->iface, 0, NULL); data->scan_rslt_cb = NULL; /* NOTE: It is complete of scan packet, do not need to clean result_ptr, * WHD will release result_ptr buffer */ return; } /* We recived scan data so process it */ if ((result_ptr != NULL) && (*result_ptr != NULL)) { memcpy(&whd_scan_result, *result_ptr, sizeof(whd_scan_result_t)); parse_scan_result(&whd_scan_result, &zephyr_scan_result); data->scan_rslt_cb(data->iface, 0, &zephyr_scan_result); } memset(*result_ptr, 0, sizeof(whd_scan_result_t)); } /* * Implement WHD network buffers functions */ static whd_result_t airoc_wifi_host_buffer_get(whd_buffer_t *buffer, whd_buffer_dir_t direction, uint16_t size, uint32_t timeout_ms) { ARG_UNUSED(direction); ARG_UNUSED(timeout_ms); struct net_buf *buf; buf = net_buf_alloc_len(&airoc_pool, size, K_NO_WAIT); if ((buf == NULL) || (buf->size < size)) { return WHD_BUFFER_ALLOC_FAIL; } *buffer = buf; /* Set buffer size */ (void) airoc_wifi_buffer_set_size(*buffer, size); return WHD_SUCCESS; } static void airoc_wifi_buffer_release(whd_buffer_t buffer, whd_buffer_dir_t direction) { CY_UNUSED_PARAMETER(direction); (void)net_buf_destroy((struct net_buf *)buffer); } static uint8_t *airoc_wifi_buffer_get_current_piece_data_pointer(whd_buffer_t buffer) { CY_ASSERT(buffer != NULL); struct net_buf *buf = (struct net_buf *)buffer; return (uint8_t *)buf->data; } static uint16_t airoc_wifi_buffer_get_current_piece_size(whd_buffer_t buffer) { CY_ASSERT(buffer != NULL); struct net_buf *buf = (struct net_buf *)buffer; return (uint16_t)buf->size; } static whd_result_t airoc_wifi_buffer_set_size(whd_buffer_t buffer, unsigned short size) { CY_ASSERT(buffer != NULL); struct net_buf *buf = (struct net_buf *)buffer; buf->size = size; return CY_RSLT_SUCCESS; } static whd_result_t airoc_wifi_buffer_add_remove_at_front(whd_buffer_t *buffer, int32_t add_remove_amount) { CY_ASSERT(buffer != NULL); struct net_buf **buf = (struct net_buf **)buffer; if (add_remove_amount > 0) { (*buf)->len = (*buf)->size; (*buf)->data = net_buf_pull(*buf, add_remove_amount); } else { (*buf)->data = net_buf_push(*buf, -add_remove_amount); (*buf)->len = (*buf)->size; } return WHD_SUCCESS; } static int airoc_mgmt_send(const struct device *dev, struct net_pkt *pkt) { struct airoc_wifi_data *data = dev->data; cy_rslt_t ret; size_t pkt_len = net_pkt_get_len(pkt); struct net_buf *buf = NULL; /* Read the packet payload */ if (net_pkt_read(pkt, data->frame_buf, pkt_len) < 0) { LOG_ERR("net_pkt_read failed"); return -EIO; } /* Allocate Network Buffer from pool with Packet Length + Data Header */ ret = airoc_wifi_host_buffer_get((whd_buffer_t *) &buf, WHD_NETWORK_TX, pkt_len + sizeof(data_header_t), 0); if ((ret != WHD_SUCCESS) || (buf == NULL)) { return -EIO; } /* Reserve the buffer Headroom for WHD Data header */ net_buf_reserve(buf, sizeof(data_header_t)); /* Copy the buffer to network Buffer pointer */ (void)memcpy(buf->data, data->frame_buf, pkt_len); /* Call WHD API to send out the Packet */ ret = whd_network_send_ethernet_data(airoc_if, (void *)buf); if (ret != CY_RSLT_SUCCESS) { LOG_ERR("whd_network_send_ethernet_data failed"); #if defined(CONFIG_NET_STATISTICS_WIFI) data->stats.errors.tx++; #endif return -EIO; } #if defined(CONFIG_NET_STATISTICS_WIFI) data->stats.bytes.sent += pkt_len; data->stats.pkts.tx++; #endif return 0; } static void airoc_wifi_network_process_ethernet_data(whd_interface_t interface, whd_buffer_t buffer) { struct net_pkt *pkt; uint8_t *data = whd_buffer_get_current_piece_data_pointer(interface->whd_driver, buffer); uint32_t len = whd_buffer_get_current_piece_size(interface->whd_driver, buffer); bool net_pkt_unref_flag = false; if ((airoc_wifi_iface != NULL) && net_if_flag_is_set(airoc_wifi_iface, NET_IF_UP)) { pkt = net_pkt_rx_alloc_with_buffer(airoc_wifi_iface, len, AF_UNSPEC, 0, K_NO_WAIT); if (pkt != NULL) { if (net_pkt_write(pkt, data, len) < 0) { LOG_ERR("Failed to write pkt"); net_pkt_unref_flag = true; } if ((net_pkt_unref_flag) || (net_recv_data(airoc_wifi_iface, pkt) < 0)) { LOG_ERR("Failed to push received data"); net_pkt_unref_flag = true; } } else { LOG_ERR("Failed to get net buffer"); } } /* Release a packet buffer */ airoc_wifi_buffer_release(buffer, WHD_NETWORK_RX); #if defined(CONFIG_NET_STATISTICS_WIFI) airoc_wifi_data.stats.bytes.received += len; airoc_wifi_data.stats.pkts.rx++; #endif if (net_pkt_unref_flag) { net_pkt_unref(pkt); #if defined(CONFIG_NET_STATISTICS_WIFI) airoc_wifi_data.stats.errors.rx++; #endif } } static enum ethernet_hw_caps airoc_get_capabilities(const struct device *dev) { ARG_UNUSED(dev); return ETHERNET_HW_FILTERING; } static int airoc_set_config(const struct device *dev, enum ethernet_config_type type, const struct ethernet_config *config) { ARG_UNUSED(dev); whd_mac_t whd_mac_addr; switch (type) { case ETHERNET_CONFIG_TYPE_FILTER: for (int i = 0; i < WHD_ETHER_ADDR_LEN; i++) { whd_mac_addr.octet[i] = config->filter.mac_address.addr[i]; } if (config->filter.set) { whd_wifi_register_multicast_address(airoc_if, &whd_mac_addr); } else { whd_wifi_unregister_multicast_address(airoc_if, &whd_mac_addr); } return 0; default: break; } return -ENOTSUP; } static void *link_events_handler(whd_interface_t ifp, const whd_event_header_t *event_header, const uint8_t *event_data, void *handler_user_data) { ARG_UNUSED(ifp); ARG_UNUSED(event_data); ARG_UNUSED(handler_user_data); k_msgq_put(&airoc_wifi_msgq, event_header, K_FOREVER); return NULL; } static void airoc_event_task(void) { whd_event_header_t event_header; while (1) { k_msgq_get(&airoc_wifi_msgq, &event_header, K_FOREVER); switch ((whd_event_num_t)event_header.event_type) { case WLC_E_LINK: break; case WLC_E_DEAUTH_IND: case WLC_E_DISASSOC_IND: net_if_dormant_on(airoc_wifi_iface); break; default: break; } } } static void airoc_mgmt_init(struct net_if *iface) { const struct device *dev = net_if_get_device(iface); struct airoc_wifi_data *data = dev->data; struct ethernet_context *eth_ctx = net_if_l2_data(iface); eth_ctx->eth_if_type = L2_ETH_IF_TYPE_WIFI; data->iface = iface; airoc_wifi_iface = iface; /* Read WLAN MAC Address */ if (whd_wifi_get_mac_address(airoc_sta_if, &airoc_sta_if->mac_addr) != WHD_SUCCESS) { LOG_ERR("Failed to get mac address"); } else { (void)memcpy(&data->mac_addr, &airoc_sta_if->mac_addr, sizeof(airoc_sta_if->mac_addr)); } /* Assign link local address. */ if (net_if_set_link_addr(iface, data->mac_addr, 6, NET_LINK_ETHERNET)) { LOG_ERR("Failed to set link addr"); } /* Initialize Ethernet L2 stack */ ethernet_init(iface); /* Not currently connected to a network */ net_if_dormant_on(iface); /* L1 network layer (physical layer) is up */ net_if_carrier_on(data->iface); } static int airoc_mgmt_scan(const struct device *dev, struct wifi_scan_params *params, scan_result_cb_t cb) { struct airoc_wifi_data *data = dev->data; if (data->scan_rslt_cb != NULL) { LOG_INF("Scan callback in progress"); return -EINPROGRESS; } if (k_sem_take(&data->sema_common, K_MSEC(AIROC_WIFI_WAIT_SEMA_MS)) != 0) { return -EAGAIN; } data->scan_rslt_cb = cb; /* Connect to the network */ if (whd_wifi_scan(airoc_sta_if, params->scan_type, WHD_BSS_TYPE_ANY, &(data->ssid), NULL, NULL, NULL, scan_callback, &(data->scan_result), data) != WHD_SUCCESS) { LOG_ERR("Failed to start scan"); k_sem_give(&data->sema_common); return -EAGAIN; } k_sem_give(&data->sema_common); return 0; } static int airoc_mgmt_connect(const struct device *dev, struct wifi_connect_req_params *params) { struct airoc_wifi_data *data = (struct airoc_wifi_data *)dev->data; whd_ssid_t ssid = {0}; int ret = 0; if (k_sem_take(&data->sema_common, K_MSEC(AIROC_WIFI_WAIT_SEMA_MS)) != 0) { return -EAGAIN; } if (data->is_sta_connected) { LOG_ERR("Already connected"); ret = -EALREADY; goto error; } if (data->is_ap_up) { LOG_ERR("Network interface is busy AP. Please first disable AP."); ret = -EBUSY; goto error; } ssid.length = params->ssid_length; memcpy(ssid.value, params->ssid, params->ssid_length); whd_scan_result_t scan_result; whd_scan_result_t usr_result = {0}; usr_result.SSID.length = ssid.length; memcpy(usr_result.SSID.value, ssid.value, ssid.length); if (whd_wifi_scan(airoc_sta_if, WHD_SCAN_TYPE_ACTIVE, WHD_BSS_TYPE_ANY, NULL, NULL, NULL, NULL, airoc_wifi_scan_cb_search, &scan_result, &(usr_result)) != WHD_SUCCESS) { LOG_ERR("Failed start scan"); ret = -EAGAIN; goto error; } if (k_sem_take(&airoc_wifi_data.sema_scan, K_MSEC(AIROC_WIFI_SCAN_TIMEOUT_MS)) != 0) { whd_wifi_stop_scan(airoc_sta_if); ret = -EAGAIN; goto error; } if (usr_result.security == WHD_SECURITY_UNKNOWN) { ret = -EAGAIN; LOG_ERR("Could not scan device"); goto error; } /* Connect to the network */ if (whd_wifi_join(airoc_sta_if, &usr_result.SSID, usr_result.security, params->psk, params->psk_length) != WHD_SUCCESS) { LOG_ERR("Failed to connect with network"); ret = -EAGAIN; goto error; } error: if (ret < 0) { net_if_dormant_on(data->iface); } else { net_if_dormant_off(data->iface); data->is_sta_connected = true; #if defined(CONFIG_NET_DHCPV4) net_dhcpv4_restart(data->iface); #endif /* defined(CONFIG_NET_DHCPV4) */ } wifi_mgmt_raise_connect_result_event(data->iface, ret); k_sem_give(&data->sema_common); return ret; } static int airoc_mgmt_disconnect(const struct device *dev) { int ret = 0; struct airoc_wifi_data *data = (struct airoc_wifi_data *)dev->data; if (k_sem_take(&data->sema_common, K_MSEC(AIROC_WIFI_WAIT_SEMA_MS)) != 0) { return -EAGAIN; } if (whd_wifi_leave(airoc_sta_if) != WHD_SUCCESS) { k_sem_give(&data->sema_common); ret = -EAGAIN; } else { data->is_sta_connected = false; net_if_dormant_on(data->iface); } wifi_mgmt_raise_disconnect_result_event(data->iface, ret); k_sem_give(&data->sema_common); return ret; } static void *airoc_wifi_ap_link_events_handler(whd_interface_t ifp, const whd_event_header_t *event_header, const uint8_t *event_data, void *handler_user_data) { struct airoc_wifi_event_t airoc_event = { .is_ap_event = 1, .event_type = event_header->event_type }; k_msgq_put(&airoc_wifi_msgq, &airoc_event, K_FOREVER); return NULL; } static int airoc_mgmt_ap_enable(const struct device *dev, struct wifi_connect_req_params *params) { struct airoc_wifi_data *data = dev->data; whd_security_t security; whd_ssid_t ssid; uint8_t channel; int ret = 0; if (k_sem_take(&data->sema_common, K_MSEC(AIROC_WIFI_WAIT_SEMA_MS)) != 0) { return -EAGAIN; } if (data->is_sta_connected) { LOG_ERR("Network interface is busy in STA mode. Please first disconnect STA."); ret = -EBUSY; goto error; } if (data->is_ap_up) { LOG_ERR("Already AP is on - first disable"); ret = -EAGAIN; goto error; } if (!data->second_interface_init) { if (whd_add_secondary_interface(data->whd_drv, NULL, &airoc_ap_if) != CY_RSLT_SUCCESS) { LOG_ERR("Error Unable to bring up the whd secondary interface"); ret = -EAGAIN; goto error; } data->second_interface_init = true; } ssid.length = params->ssid_length; memcpy(ssid.value, params->ssid, ssid.length); /* make sure to set valid channels for 2G and 5G: * - 2G channels from 1 to 11, * - 5G channels from 36 to 165 */ if (((params->channel > 0) && (params->channel < 12)) || ((params->channel > 35) && (params->channel < 166))) { channel = params->channel; } else { channel = 1; LOG_WRN("Discard of setting unsupported channel: %u (will set 1)", params->channel); } switch (params->security) { case WIFI_SECURITY_TYPE_NONE: security = WHD_SECURITY_OPEN; break; case WIFI_SECURITY_TYPE_PSK: security = WHD_SECURITY_WPA2_AES_PSK; break; case WIFI_SECURITY_TYPE_SAE: security = WHD_SECURITY_WPA3_SAE; break; default: goto error; } if (whd_wifi_init_ap(airoc_ap_if, &ssid, security, (const uint8_t *)params->psk, params->psk_length, channel) != 0) { LOG_ERR("Failed to init whd ap interface"); ret = -EAGAIN; goto error; } if (whd_wifi_start_ap(airoc_ap_if) != 0) { LOG_ERR("Failed to start whd ap interface"); ret = -EAGAIN; goto error; } /* set event handler */ if (whd_management_set_event_handler(airoc_ap_if, ap_link_events, airoc_wifi_ap_link_events_handler, NULL, &ap_event_handler_index) != 0) { whd_wifi_stop_ap(airoc_ap_if); ret = -EAGAIN; goto error; } data->is_ap_up = true; airoc_if = airoc_ap_if; net_if_dormant_off(data->iface); error: k_sem_give(&data->sema_common); return ret; } #if defined(CONFIG_NET_STATISTICS_WIFI) static int airoc_mgmt_wifi_stats(const struct device *dev, struct net_stats_wifi *stats) { struct airoc_wifi_data *data = dev->data; stats->bytes.received = data->stats.bytes.received; stats->bytes.sent = data->stats.bytes.sent; stats->pkts.rx = data->stats.pkts.rx; stats->pkts.tx = data->stats.pkts.tx; stats->errors.rx = data->stats.errors.rx; stats->errors.tx = data->stats.errors.tx; stats->broadcast.rx = data->stats.broadcast.rx; stats->broadcast.tx = data->stats.broadcast.tx; stats->multicast.rx = data->stats.multicast.rx; stats->multicast.tx = data->stats.multicast.tx; stats->sta_mgmt.beacons_rx = data->stats.sta_mgmt.beacons_rx; stats->sta_mgmt.beacons_miss = data->stats.sta_mgmt.beacons_miss; return 0; } #endif static int airoc_mgmt_ap_disable(const struct device *dev) { cy_rslt_t whd_ret; struct airoc_wifi_data *data = dev->data; if (k_sem_take(&data->sema_common, K_MSEC(AIROC_WIFI_WAIT_SEMA_MS)) != 0) { return -EAGAIN; } if (whd_wifi_deregister_event_handler(airoc_ap_if, ap_event_handler_index)) { LOG_ERR("Can't whd_wifi_deregister_event_handler"); } whd_ret = whd_wifi_stop_ap(airoc_ap_if); if (whd_ret == CY_RSLT_SUCCESS) { data->is_ap_up = false; airoc_if = airoc_sta_if; net_if_dormant_on(data->iface); } else { LOG_ERR("Can't stop wifi ap: %u", whd_ret); } k_sem_give(&data->sema_common); if (whd_ret != CY_RSLT_SUCCESS) { return -ENODEV; } return 0; } static int airoc_init(const struct device *dev) { int ret; cy_rslt_t whd_ret; struct airoc_wifi_data *data = dev->data; k_tid_t tid = k_thread_create( &airoc_wifi_event_thread, airoc_wifi_event_stack, CONFIG_AIROC_WIFI_EVENT_TASK_STACK_SIZE, (k_thread_entry_t)airoc_event_task, NULL, NULL, NULL, CONFIG_AIROC_WIFI_EVENT_TASK_PRIO, K_INHERIT_PERMS, K_NO_WAIT); if (!tid) { LOG_ERR("ERROR spawning tx thread"); return -EAGAIN; } k_thread_name_set(tid, "airoc_event"); whd_ret = airoc_wifi_init_primary(dev, &airoc_sta_if, &airoc_wifi_netif_if_default, &airoc_wifi_buffer_if_default); if (whd_ret != CY_RSLT_SUCCESS) { LOG_ERR("airoc_wifi_init_primary failed ret = %d \r\n", whd_ret); return -EAGAIN; } airoc_if = airoc_sta_if; whd_ret = whd_management_set_event_handler(airoc_sta_if, sta_link_events, link_events_handler, NULL, &sta_event_handler_index); if (whd_ret != CY_RSLT_SUCCESS) { LOG_ERR("whd_management_set_event_handler failed ret = %d \r\n", whd_ret); return -EAGAIN; } ret = k_sem_init(&data->sema_common, 1, 1); if (ret != 0) { LOG_ERR("k_sem_init(sema_common) failure"); return ret; } ret = k_sem_init(&data->sema_scan, 0, 1); if (ret != 0) { LOG_ERR("k_sem_init(sema_scan) failure"); return ret; } return 0; } static const struct wifi_mgmt_ops airoc_wifi_mgmt = { .scan = airoc_mgmt_scan, .connect = airoc_mgmt_connect, .disconnect = airoc_mgmt_disconnect, .ap_enable = airoc_mgmt_ap_enable, .ap_disable = airoc_mgmt_ap_disable, #if defined(CONFIG_NET_STATISTICS_ETHERNET) .get_stats = airoc_mgmt_wifi_stats, #endif }; static const struct net_wifi_mgmt_offload airoc_api = { .wifi_iface.iface_api.init = airoc_mgmt_init, .wifi_iface.send = airoc_mgmt_send, .wifi_iface.get_capabilities = airoc_get_capabilities, .wifi_iface.set_config = airoc_set_config, .wifi_mgmt_api = &airoc_wifi_mgmt, }; NET_DEVICE_DT_INST_DEFINE(0, airoc_init, NULL, &airoc_wifi_data, &airoc_wifi_config, CONFIG_WIFI_INIT_PRIORITY, &airoc_api, ETHERNET_L2, NET_L2_GET_CTX_TYPE(ETHERNET_L2), WHD_LINK_MTU); CONNECTIVITY_WIFI_MGMT_BIND(Z_DEVICE_DT_DEV_ID(DT_DRV_INST(0))); ```
/content/code_sandbox/drivers/wifi/infineon/airoc_wifi.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
6,655
```objective-c /** * */ #ifndef ZEPHYR_DRIVERS_WIFI_ESWIFI_ESWIFI_LOG_H_ #define ZEPHYR_DRIVERS_WIFI_ESWIFI_ESWIFI_LOG_H_ #define LOG_MODULE_NAME wifi_eswifi #define LOG_LEVEL CONFIG_WIFI_LOG_LEVEL #include <zephyr/logging/log.h> #endif /* ZEPHYR_DRIVERS_WIFI_ESWIFI_ESWIFI_LOG_H_ */ ```
/content/code_sandbox/drivers/wifi/eswifi/eswifi_log.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
82
```unknown # es-WiFi driver options menuconfig WIFI_ESWIFI bool "Inventek eS-WiFi support" default y depends on DT_HAS_INVENTEK_ESWIFI_ENABLED || DT_HAS_INVENTEK_ESWIFI_UART_ENABLED select NET_L2_WIFI_MGMT select WIFI_OFFLOAD select NET_OFFLOAD select NET_SOCKETS imply NET_SOCKETS_OFFLOAD select GPIO if WIFI_ESWIFI choice WIFI_ESWIFI_BUS bool "Select BUS interface" default WIFI_ESWIFI_BUS_SPI config WIFI_ESWIFI_BUS_SPI bool "SPI Bus interface" select SPI config WIFI_ESWIFI_BUS_UART bool "UART Bus interface" select SERIAL endchoice config WIFI_ESWIFI_MAX_DATA_SIZE int "esWiFi message size" default 1600 range 500 4000 help This option sets the size of the esWiFi message buffer. It can be increased to handle larger messages, like scan results. config WIFI_ESWIFI_THREAD_PRIO int "esWiFi threads priority" default 2 help This option sets the priority of the esWiFi threads. Do not touch it unless you know what you are doing. config WIFI_ESWIFI_SHELL bool "esWiFi shell" depends on SHELL help Enable esWiFi shell endif ```
/content/code_sandbox/drivers/wifi/eswifi/Kconfig.eswifi
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
287
```c /* * */ #include "eswifi_log.h" LOG_MODULE_DECLARE(LOG_MODULE_NAME); #include <zephyr/kernel.h> #include <zephyr/device.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <zephyr/net/socket_offload.h> #include <zephyr/net/tls_credentials.h> #include "sockets_internal.h" #if defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) #include "tls_internal.h" #endif #include "eswifi.h" #include <zephyr/net/net_pkt.h> /* Increment by 1 to make sure we do not store the value of 0, which has * a special meaning in the fdtable subsys. */ #define SD_TO_OBJ(sd) ((void *)(sd + 1)) #define OBJ_TO_SD(obj) (((int)obj) - 1) /* Default socket context (50CE) */ #define ESWIFI_INIT_CONTEXT INT_TO_POINTER(0x50CE) static struct eswifi_dev *eswifi; static const struct socket_op_vtable eswifi_socket_fd_op_vtable; static void __process_received(struct net_context *context, struct net_pkt *pkt, union net_ip_header *ip_hdr, union net_proto_header *proto_hdr, int status, void *user_data) { struct eswifi_off_socket *socket = user_data; if (!pkt) { k_fifo_cancel_wait(&socket->fifo); return; } k_fifo_put(&socket->fifo, pkt); } static int eswifi_socket_connect(void *obj, const struct sockaddr *addr, socklen_t addrlen) { int sock = OBJ_TO_SD(obj); struct eswifi_off_socket *socket; int ret; if ((addrlen == 0) || (addr == NULL) || (sock >= ESWIFI_OFFLOAD_MAX_SOCKETS)) { return -EINVAL; } if (addr->sa_family != AF_INET) { LOG_ERR("Only AF_INET is supported!"); return -EPFNOSUPPORT; } eswifi_lock(eswifi); socket = &eswifi->socket[sock]; if (socket->state != ESWIFI_SOCKET_STATE_NONE) { eswifi_unlock(eswifi); return -EBUSY; } socket->peer_addr = *addr; socket->state = ESWIFI_SOCKET_STATE_CONNECTING; ret = __eswifi_off_start_client(eswifi, socket); if (!ret) { socket->state = ESWIFI_SOCKET_STATE_CONNECTED; } else { socket->state = ESWIFI_SOCKET_STATE_NONE; } eswifi_unlock(eswifi); return ret; } static int eswifi_socket_listen(void *obj, int backlog) { struct eswifi_off_socket *socket; int sock = OBJ_TO_SD(obj); int ret; eswifi_lock(eswifi); socket = &eswifi->socket[sock]; ret = __eswifi_listen(eswifi, socket, backlog); eswifi_unlock(eswifi); return ret; } void __eswifi_socket_accept_cb(struct net_context *context, struct sockaddr *addr, unsigned int len, int val, void *data) { struct sockaddr *addr_target = data; memcpy(addr_target, addr, len); } static int __eswifi_socket_accept(void *obj, struct sockaddr *addr, socklen_t *addrlen) { int sock = OBJ_TO_SD(obj); struct eswifi_off_socket *socket; int ret; if ((addrlen == NULL) || (addr == NULL) || (sock >= ESWIFI_OFFLOAD_MAX_SOCKETS)) { return -EINVAL; } eswifi_lock(eswifi); socket = &eswifi->socket[sock]; ret = __eswifi_accept(eswifi, socket); socket->accept_cb = __eswifi_socket_accept_cb; socket->accept_data = addr; k_sem_reset(&socket->accept_sem); eswifi_unlock(eswifi); *addrlen = sizeof(struct sockaddr_in); k_sem_take(&socket->accept_sem, K_FOREVER); return 0; } static int eswifi_socket_accept(void *obj, struct sockaddr *addr, socklen_t *addrlen) { int fd = zvfs_reserve_fd(); int sock; if (fd < 0) { return -1; } sock = __eswifi_socket_accept(obj, addr, addrlen); if (sock < 0) { zvfs_free_fd(fd); return -1; } zvfs_finalize_typed_fd(fd, SD_TO_OBJ(sock), (const struct fd_op_vtable *)&eswifi_socket_fd_op_vtable, ZVFS_MODE_IFSOCK); return fd; } #if defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) static int map_credentials(int sd, const void *optval, socklen_t optlen) { sec_tag_t *sec_tags = (sec_tag_t *)optval; int ret = 0; int tags_len; sec_tag_t tag; int id; int i, bytes; struct tls_credential *cert; if ((optlen % sizeof(sec_tag_t)) != 0 || (optlen == 0)) { return -EINVAL; } tags_len = optlen / sizeof(sec_tag_t); /* For each tag, retrieve the credentials value and type: */ for (i = 0; i < tags_len; i++) { tag = sec_tags[i]; cert = credential_next_get(tag, NULL); while (cert != NULL) { /* Map Zephyr cert types to Simplelink cert options: */ switch (cert->type) { case TLS_CREDENTIAL_CA_CERTIFICATE: id = 0; break; case TLS_CREDENTIAL_SERVER_CERTIFICATE: id = 1; break; case TLS_CREDENTIAL_PRIVATE_KEY: id = 2; break; case TLS_CREDENTIAL_NONE: case TLS_CREDENTIAL_PSK: case TLS_CREDENTIAL_PSK_ID: default: /* Not handled */ return -EINVAL; } snprintk(eswifi->buf, sizeof(eswifi->buf), "PG=%d,%d,%d\r", 0, id, cert->len); bytes = strlen(eswifi->buf); memcpy(&eswifi->buf[bytes], cert->buf, cert->len); bytes += cert->len; LOG_DBG("cert write len %d\n", cert->len); ret = eswifi_request(eswifi, eswifi->buf, bytes + 1, eswifi->buf, sizeof(eswifi->buf)); LOG_DBG("cert write err %d\n", ret); if (ret < 0) { return ret; } snprintk(eswifi->buf, sizeof(eswifi->buf), "PF=0,0\r"); ret = eswifi_at_cmd(eswifi, eswifi->buf); if (ret < 0) { return ret; } cert = credential_next_get(tag, cert); } } return 0; } #else static int map_credentials(int sd, const void *optval, socklen_t optlen) { return 0; } #endif static int eswifi_socket_setsockopt(void *obj, int level, int optname, const void *optval, socklen_t optlen) { int sd = OBJ_TO_SD(obj); int ret; if (IS_ENABLED(CONFIG_NET_SOCKETS_SOCKOPT_TLS) && level == SOL_TLS) { switch (optname) { case TLS_SEC_TAG_LIST: ret = map_credentials(sd, optval, optlen); break; case TLS_HOSTNAME: case TLS_PEER_VERIFY: ret = 0; break; default: return -EINVAL; } } else { return -EINVAL; } return ret; } static ssize_t eswifi_socket_send(void *obj, const void *buf, size_t len, int flags) { int sock = OBJ_TO_SD(obj); struct eswifi_off_socket *socket; int ret; int offset; if (!buf) { return -EINVAL; } eswifi_lock(eswifi); socket = &eswifi->socket[sock]; if (socket->state != ESWIFI_SOCKET_STATE_CONNECTED) { eswifi_unlock(eswifi); return -ENOTCONN; } __select_socket(eswifi, socket->index); /* header */ snprintk(eswifi->buf, sizeof(eswifi->buf), "S3=%u\r", len); offset = strlen(eswifi->buf); /* copy payload */ memcpy(&eswifi->buf[offset], buf, len); offset += len; ret = eswifi_request(eswifi, eswifi->buf, offset + 1, eswifi->buf, sizeof(eswifi->buf)); if (ret < 0) { LOG_DBG("Unable to send data"); ret = -EIO; } else { ret = len; } eswifi_unlock(eswifi); return ret; } static ssize_t eswifi_socket_sendto(void *obj, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen) { if (to != NULL) { errno = EOPNOTSUPP; return -1; } return eswifi_socket_send(obj, buf, len, flags); } static ssize_t eswifi_socket_recv(void *obj, void *buf, size_t max_len, int flags) { int sock = OBJ_TO_SD(obj); struct eswifi_off_socket *socket; int len = 0, ret = 0; struct net_pkt *pkt; if ((max_len == 0) || (buf == NULL) || (sock >= ESWIFI_OFFLOAD_MAX_SOCKETS)) { return -EINVAL; } eswifi_lock(eswifi); socket = &eswifi->socket[sock]; if (socket->prev_pkt_rem) { pkt = socket->prev_pkt_rem; goto skip_wait; } ret = k_work_reschedule_for_queue(&eswifi->work_q, &socket->read_work, K_NO_WAIT); if (ret < 0) { LOG_ERR("Rescheduling socket read error"); errno = -ret; len = -1; } if (flags & ZSOCK_MSG_DONTWAIT) { pkt = k_fifo_get(&socket->fifo, K_NO_WAIT); if (!pkt) { errno = EAGAIN; len = -1; goto done; } } else { eswifi_unlock(eswifi); pkt = k_fifo_get(&socket->fifo, K_FOREVER); if (!pkt) { return 0; /* EOF */ } eswifi_lock(eswifi); } skip_wait: len = net_pkt_remaining_data(pkt); if (len > max_len) { len = max_len; socket->prev_pkt_rem = pkt; } else { socket->prev_pkt_rem = NULL; } ret = net_pkt_read(pkt, buf, len); if (!socket->prev_pkt_rem) { net_pkt_unref(pkt); } done: LOG_DBG("read %d %d %p", len, ret, pkt); eswifi_unlock(eswifi); if (ret) { len = 0; } return len; } static ssize_t eswifi_socket_recvfrom(void *obj, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen) { if (fromlen != NULL) { errno = EOPNOTSUPP; return -1; } return eswifi_socket_recv(obj, buf, len, flags); } static int eswifi_socket_close(void *obj) { int sock = OBJ_TO_SD(obj); struct eswifi_off_socket *socket; struct net_pkt *pkt; int ret; if (sock >= ESWIFI_OFFLOAD_MAX_SOCKETS) { return -EINVAL; } eswifi_lock(eswifi); socket = &eswifi->socket[sock]; ret = __eswifi_socket_free(eswifi, socket); if (ret) { goto done; } /* consume all net pkt */ while (1) { pkt = k_fifo_get(&socket->fifo, K_NO_WAIT); if (!pkt) { break; } net_pkt_unref(pkt); } if (--socket->usage <= 0) { socket->context = NULL; } done: eswifi_unlock(eswifi); return ret; } static int eswifi_socket_open(int family, int type, int proto) { struct eswifi_off_socket *socket = NULL; int idx; eswifi_lock(eswifi); idx = __eswifi_socket_new(eswifi, family, type, proto, ESWIFI_INIT_CONTEXT); if (idx < 0) { goto unlock; } socket = &eswifi->socket[idx]; k_fifo_init(&socket->fifo); k_sem_init(&socket->read_sem, 0, 200); k_sem_init(&socket->accept_sem, 1, 1); socket->prev_pkt_rem = NULL; socket->recv_cb = __process_received; socket->recv_data = socket; k_work_reschedule_for_queue(&eswifi->work_q, &socket->read_work, K_MSEC(500)); unlock: eswifi_unlock(eswifi); return idx; } static int eswifi_socket_poll(struct zsock_pollfd *fds, int nfds, int msecs) { struct eswifi_off_socket *socket; k_timeout_t timeout; int sock, ret; void *obj; if (nfds != 1) { errno = EINVAL; return -1; } obj = zvfs_get_fd_obj(fds[0].fd, (const struct fd_op_vtable *) &eswifi_socket_fd_op_vtable, 0); if (obj != NULL) { sock = OBJ_TO_SD(obj); } else { errno = EINVAL; return -1; } if (sock >= ESWIFI_OFFLOAD_MAX_SOCKETS) { errno = EINVAL; return -1; } if (!(fds[0].events & ZSOCK_POLLIN)) { errno = ENOTSUP; return -1; } eswifi_lock(eswifi); socket = &eswifi->socket[sock]; ret = k_work_reschedule_for_queue(&eswifi->work_q, &socket->read_work, K_NO_WAIT); if (ret < 0) { LOG_ERR("Rescheduling socket read error"); errno = -ret; eswifi_unlock(eswifi); return -1; } eswifi_unlock(eswifi); if (socket->state != ESWIFI_SOCKET_STATE_CONNECTED) { errno = EINVAL; return -1; } if (!k_fifo_is_empty(&socket->fifo)) { goto done; } if (msecs == SYS_FOREVER_MS) { timeout = K_FOREVER; } else { timeout = K_MSEC(msecs); } ret = k_sem_take(&socket->read_sem, timeout); if (ret) { errno = ETIMEDOUT; return -1; } done: fds[0].revents = ZSOCK_POLLIN; /* Report one event */ return 1; } static int eswifi_socket_bind(void *obj, const struct sockaddr *addr, socklen_t addrlen) { int sock = OBJ_TO_SD(obj); struct eswifi_off_socket *socket; int ret; if ((addrlen == 0) || (addr == NULL) || (sock >= ESWIFI_OFFLOAD_MAX_SOCKETS)) { return -EINVAL; } eswifi_lock(eswifi); socket = &eswifi->socket[sock]; ret = __eswifi_bind(eswifi, socket, addr, addrlen); eswifi_unlock(eswifi); return ret; } static bool eswifi_socket_is_supported(int family, int type, int proto) { enum eswifi_transport_type eswifi_socket_type; int err; if (family != AF_INET) { return false; } if (type != SOCK_DGRAM && type != SOCK_STREAM) { return false; } err = eswifi_socket_type_from_zephyr(proto, &eswifi_socket_type); if (err) { return false; } return true; } int eswifi_socket_create(int family, int type, int proto) { int fd = zvfs_reserve_fd(); int sock; if (fd < 0) { return -1; } sock = eswifi_socket_open(family, type, proto); if (sock < 0) { zvfs_free_fd(fd); return -1; } zvfs_finalize_typed_fd(fd, SD_TO_OBJ(sock), (const struct fd_op_vtable *)&eswifi_socket_fd_op_vtable, ZVFS_MODE_IFSOCK); return fd; } static int eswifi_socket_ioctl(void *obj, unsigned int request, va_list args) { switch (request) { case ZFD_IOCTL_POLL_PREPARE: return -EXDEV; case ZFD_IOCTL_POLL_UPDATE: return -EOPNOTSUPP; case ZFD_IOCTL_POLL_OFFLOAD: { struct zsock_pollfd *fds; int nfds; int timeout; fds = va_arg(args, struct zsock_pollfd *); nfds = va_arg(args, int); timeout = va_arg(args, int); return eswifi_socket_poll(fds, nfds, timeout); } default: errno = EINVAL; return -1; } } static ssize_t eswifi_socket_read(void *obj, void *buffer, size_t count) { return eswifi_socket_recvfrom(obj, buffer, count, 0, NULL, 0); } static ssize_t eswifi_socket_write(void *obj, const void *buffer, size_t count) { return eswifi_socket_sendto(obj, buffer, count, 0, NULL, 0); } static const struct socket_op_vtable eswifi_socket_fd_op_vtable = { .fd_vtable = { .read = eswifi_socket_read, .write = eswifi_socket_write, .close = eswifi_socket_close, .ioctl = eswifi_socket_ioctl, }, .bind = eswifi_socket_bind, .connect = eswifi_socket_connect, .listen = eswifi_socket_listen, .accept = eswifi_socket_accept, .sendto = eswifi_socket_sendto, .recvfrom = eswifi_socket_recvfrom, .setsockopt = eswifi_socket_setsockopt, }; #ifdef CONFIG_NET_SOCKETS_OFFLOAD NET_SOCKET_OFFLOAD_REGISTER(eswifi, CONFIG_NET_SOCKETS_OFFLOAD_PRIORITY, AF_UNSPEC, eswifi_socket_is_supported, eswifi_socket_create); #endif static int eswifi_off_getaddrinfo(const char *node, const char *service, const struct zsock_addrinfo *hints, struct zsock_addrinfo **res) { struct sockaddr_in *ai_addr; struct zsock_addrinfo *ai; unsigned long port = 0; char *rsp; int err; if (!node) { return DNS_EAI_NONAME; } if (service) { port = strtol(service, NULL, 10); if (port < 1 || port > USHRT_MAX) { return DNS_EAI_SERVICE; } } if (!res) { return DNS_EAI_NONAME; } if (hints && hints->ai_family != AF_INET) { return DNS_EAI_FAIL; } eswifi_lock(eswifi); /* DNS lookup */ snprintk(eswifi->buf, sizeof(eswifi->buf), "D0=%s\r", node); err = eswifi_at_cmd_rsp(eswifi, eswifi->buf, &rsp); if (err < 0) { err = DNS_EAI_FAIL; goto done_unlock; } /* Allocate out res (addrinfo) struct. Just one. */ *res = calloc(1, sizeof(struct zsock_addrinfo)); ai = *res; if (!ai) { err = DNS_EAI_MEMORY; goto done_unlock; } /* Now, alloc the embedded sockaddr struct: */ ai_addr = calloc(1, sizeof(*ai_addr)); if (!ai_addr) { free(*res); err = DNS_EAI_MEMORY; goto done_unlock; } ai->ai_family = AF_INET; ai->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM; ai->ai_protocol = ai->ai_socktype == SOCK_STREAM ? IPPROTO_TCP : IPPROTO_UDP; ai_addr->sin_family = ai->ai_family; ai_addr->sin_port = htons(port); if (!net_ipaddr_parse(rsp, strlen(rsp), (struct sockaddr *)ai_addr)) { free(ai_addr); free(*res); err = DNS_EAI_FAIL; goto done_unlock; } ai->ai_addrlen = sizeof(*ai_addr); ai->ai_addr = (struct sockaddr *)ai_addr; err = 0; done_unlock: eswifi_unlock(eswifi); return err; } static void eswifi_off_freeaddrinfo(struct zsock_addrinfo *res) { __ASSERT_NO_MSG(res); free(res->ai_addr); free(res); } const struct socket_dns_offload eswifi_dns_ops = { .getaddrinfo = eswifi_off_getaddrinfo, .freeaddrinfo = eswifi_off_freeaddrinfo, }; int eswifi_socket_offload_init(struct eswifi_dev *leswifi) { eswifi = leswifi; socket_offload_dns_register(&eswifi_dns_ops); return 0; } ```
/content/code_sandbox/drivers/wifi/eswifi/eswifi_socket_offload.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
4,590
```c /** * */ #include <zephyr/kernel.h> #include <zephyr/shell/shell.h> #include "eswifi.h" static struct eswifi_dev *eswifi; void eswifi_shell_register(struct eswifi_dev *dev) { /* only one instance supported */ if (eswifi) { return; } eswifi = dev; } static int eswifi_shell_atcmd(const struct shell *sh, size_t argc, char **argv) { int i; size_t len = 0; if (eswifi == NULL) { shell_print(sh, "no eswifi device registered"); return -ENOEXEC; } if (argc < 2) { shell_help(sh); return -ENOEXEC; } eswifi_lock(eswifi); memset(eswifi->buf, 0, sizeof(eswifi->buf)); for (i = 1; i < argc; i++) { size_t argv_len = strlen(argv[i]); if ((len + argv_len) >= sizeof(eswifi->buf) - 1) { break; } memcpy(eswifi->buf + len, argv[i], argv_len); len += argv_len; } eswifi->buf[len] = '\r'; shell_print(sh, "> %s", eswifi->buf); eswifi_at_cmd(eswifi, eswifi->buf); shell_print(sh, "< %s", eswifi->buf); eswifi_unlock(eswifi); return 0; } SHELL_STATIC_SUBCMD_SET_CREATE(eswifi_shell, SHELL_CMD(atcmd, NULL, "<atcmd>", eswifi_shell_atcmd), SHELL_SUBCMD_SET_END /* Array terminated. */ ); SHELL_CMD_REGISTER(eswifi, &eswifi_shell, "esWiFi debug shell", NULL); ```
/content/code_sandbox/drivers/wifi/eswifi/eswifi_shell.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
375
```objective-c /** * */ #ifndef ZEPHYR_DRIVERS_WIFI_ESWIFI_ESWIFI_H_ #define ZEPHYR_DRIVERS_WIFI_ESWIFI_ESWIFI_H_ #include <zephyr/kernel.h> #include <stdio.h> #include <zephyr/kernel_structs.h> #include <zephyr/drivers/gpio.h> #include <zephyr/net/wifi_mgmt.h> #include "eswifi_offload.h" #define AT_OK_STR "\r\nOK\r\n> " #define AT_OK_STR_LEN 8 #define AT_RSP_DELIMITER "\r\n" #define AT_RSP_DELIMITER_LEN 2 enum eswifi_security_type { ESWIFI_SEC_OPEN, ESWIFI_SEC_WEP, ESWIFI_SEC_WPA, ESWIFI_SEC_WPA2_AES, ESWIFI_SEC_WPA2_MIXED, ESWIFI_SEC_MAX }; enum eswifi_request { ESWIFI_REQ_SCAN, ESWIFI_REQ_CONNECT, ESWIFI_REQ_DISCONNECT, ESWIFI_REQ_NONE }; enum eswifi_role { ESWIFI_ROLE_CLIENT, ESWIFI_ROLE_AP, }; struct eswifi_sta { char ssid[WIFI_SSID_MAX_LEN + 1]; enum eswifi_security_type security; char pass[65]; bool connected; uint8_t channel; int rssi; }; struct eswifi_bus_ops; struct eswifi_cfg { struct gpio_dt_spec resetn; struct gpio_dt_spec wakeup; }; struct eswifi_dev { struct net_if *iface; struct eswifi_bus_ops *bus; scan_result_cb_t scan_cb; struct k_work_q work_q; struct k_work request_work; struct k_work_delayable status_work; struct eswifi_sta sta; enum eswifi_request req; enum eswifi_role role; uint8_t mac[6]; char buf[CONFIG_WIFI_ESWIFI_MAX_DATA_SIZE]; struct k_mutex mutex; atomic_val_t mutex_owner; unsigned int mutex_depth; void *bus_data; struct eswifi_off_socket socket[ESWIFI_OFFLOAD_MAX_SOCKETS]; }; struct eswifi_bus_ops { int (*init)(struct eswifi_dev *eswifi); int (*request)(struct eswifi_dev *eswifi, char *cmd, size_t clen, char *rsp, size_t rlen); }; static inline int eswifi_request(struct eswifi_dev *eswifi, char *cmd, size_t clen, char *rsp, size_t rlen) { return eswifi->bus->request(eswifi, cmd, clen, rsp, rlen); } static inline void eswifi_lock(struct eswifi_dev *eswifi) { /* Nested locking */ if (atomic_get(&eswifi->mutex_owner) != (atomic_t)(uintptr_t)_current) { k_mutex_lock(&eswifi->mutex, K_FOREVER); atomic_set(&eswifi->mutex_owner, (atomic_t)(uintptr_t)_current); eswifi->mutex_depth = 1; } else { eswifi->mutex_depth++; } } static inline void eswifi_unlock(struct eswifi_dev *eswifi) { if (!--eswifi->mutex_depth) { atomic_set(&eswifi->mutex_owner, -1); k_mutex_unlock(&eswifi->mutex); } } int eswifi_at_cmd(struct eswifi_dev *eswifi, char *cmd); static inline int __select_socket(struct eswifi_dev *eswifi, uint8_t idx) { snprintk(eswifi->buf, sizeof(eswifi->buf), "P0=%d\r", idx); return eswifi_at_cmd(eswifi, eswifi->buf); } static inline struct eswifi_dev *eswifi_socket_to_dev(struct eswifi_off_socket *socket) { return CONTAINER_OF(socket - socket->index, struct eswifi_dev, socket[0]); } struct eswifi_bus_ops *eswifi_get_bus(void); int eswifi_offload_init(struct eswifi_dev *eswifi); struct eswifi_dev *eswifi_by_iface_idx(uint8_t iface); int eswifi_at_cmd_rsp(struct eswifi_dev *eswifi, char *cmd, char **rsp); void eswifi_async_msg(struct eswifi_dev *eswifi, char *msg, size_t len); void eswifi_offload_async_msg(struct eswifi_dev *eswifi, char *msg, size_t len); int eswifi_socket_create(int family, int type, int proto); int eswifi_socket_type_from_zephyr(int proto, enum eswifi_transport_type *type); int __eswifi_socket_free(struct eswifi_dev *eswifi, struct eswifi_off_socket *socket); int __eswifi_socket_new(struct eswifi_dev *eswifi, int family, int type, int proto, void *context); int __eswifi_off_start_client(struct eswifi_dev *eswifi, struct eswifi_off_socket *socket); int __eswifi_listen(struct eswifi_dev *eswifi, struct eswifi_off_socket *socket, int backlog); int __eswifi_accept(struct eswifi_dev *eswifi, struct eswifi_off_socket *socket); int __eswifi_bind(struct eswifi_dev *eswifi, struct eswifi_off_socket *socket, const struct sockaddr *addr, socklen_t addrlen); #if defined(CONFIG_NET_SOCKETS_OFFLOAD) int eswifi_socket_offload_init(struct eswifi_dev *leswifi); #endif #if defined(CONFIG_WIFI_ESWIFI_SHELL) void eswifi_shell_register(struct eswifi_dev *dev); #else #define eswifi_shell_register(dev) #endif #endif ```
/content/code_sandbox/drivers/wifi/eswifi/eswifi.h
objective-c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,151