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 |
|---|---|---|---|---|---|---|---|---|
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_BATTERY_H_
#define ZEPHYR_INCLUDE_DRIVERS_BATTERY_H_
/**
* @brief Fuel Gauge Interface
* @defgroup fuel_gauge_interface Fuel Gauge Interface
* @since 3.3
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <zephyr/device.h>
enum fuel_gauge_prop_type {
/** Runtime Dynamic Battery Parameters */
/**
* Provide a 1 minute average of the current on the battery.
* Does not check for flags or whether those values are bad readings.
* See driver instance header for details on implementation and
* how the average is calculated. Units in uA negative=discharging
*/
FUEL_GAUGE_AVG_CURRENT = 0,
/** Used to cutoff the battery from the system - useful for storage/shipping of devices */
FUEL_GAUGE_BATTERY_CUTOFF,
/** Battery current (uA); negative=discharging */
FUEL_GAUGE_CURRENT,
/** Whether the battery underlying the fuel-gauge is cut off from charge */
FUEL_GAUGE_CHARGE_CUTOFF,
/** Cycle count in 1/100ths (number of charge/discharge cycles) */
FUEL_GAUGE_CYCLE_COUNT,
/** Connect state of battery */
FUEL_GAUGE_CONNECT_STATE,
/** General Error/Runtime Flags */
FUEL_GAUGE_FLAGS,
/** Full Charge Capacity in uAh (might change in some implementations to determine wear) */
FUEL_GAUGE_FULL_CHARGE_CAPACITY,
/** Is the battery physically present */
FUEL_GAUGE_PRESENT_STATE,
/** Remaining capacity in uAh */
FUEL_GAUGE_REMAINING_CAPACITY,
/** Remaining battery life time in minutes */
FUEL_GAUGE_RUNTIME_TO_EMPTY,
/** Remaining time in minutes until battery reaches full charge */
FUEL_GAUGE_RUNTIME_TO_FULL,
/** Retrieve word from SBS1.1 ManufactuerAccess */
FUEL_GAUGE_SBS_MFR_ACCESS,
/** Absolute state of charge (percent, 0-100) - expressed as % of design capacity */
FUEL_GAUGE_ABSOLUTE_STATE_OF_CHARGE,
/** Relative state of charge (percent, 0-100) - expressed as % of full charge capacity */
FUEL_GAUGE_RELATIVE_STATE_OF_CHARGE,
/** Temperature in 0.1 K */
FUEL_GAUGE_TEMPERATURE,
/** Battery voltage (uV) */
FUEL_GAUGE_VOLTAGE,
/** Battery Mode (flags) */
FUEL_GAUGE_SBS_MODE,
/** Battery desired Max Charging Current (uA) */
FUEL_GAUGE_CHARGE_CURRENT,
/** Battery desired Max Charging Voltage (uV) */
FUEL_GAUGE_CHARGE_VOLTAGE,
/** Alarm, Status and Error codes (flags) */
FUEL_GAUGE_STATUS,
/** Design Capacity (mAh or 10mWh) */
FUEL_GAUGE_DESIGN_CAPACITY,
/** Design Voltage (mV) */
FUEL_GAUGE_DESIGN_VOLTAGE,
/** AtRate (mA or 10 mW) */
FUEL_GAUGE_SBS_ATRATE,
/** AtRateTimeToFull (minutes) */
FUEL_GAUGE_SBS_ATRATE_TIME_TO_FULL,
/** AtRateTimeToEmpty (minutes) */
FUEL_GAUGE_SBS_ATRATE_TIME_TO_EMPTY,
/** AtRateOK (boolean) */
FUEL_GAUGE_SBS_ATRATE_OK,
/** Remaining Capacity Alarm (mAh or 10mWh) */
FUEL_GAUGE_SBS_REMAINING_CAPACITY_ALARM,
/** Remaining Time Alarm (minutes) */
FUEL_GAUGE_SBS_REMAINING_TIME_ALARM,
/** Manufacturer of pack (1 byte length + 20 bytes data) */
FUEL_GAUGE_MANUFACTURER_NAME,
/** Name of pack (1 byte length + 20 bytes data) */
FUEL_GAUGE_DEVICE_NAME,
/** Chemistry (1 byte length + 4 bytes data) */
FUEL_GAUGE_DEVICE_CHEMISTRY,
/** Reserved to demark end of common fuel gauge properties */
FUEL_GAUGE_COMMON_COUNT,
/**
* Reserved to demark downstream custom properties - use this value as the actual value may
* change over future versions of this API
*/
FUEL_GAUGE_CUSTOM_BEGIN,
/** Reserved to demark end of valid enum properties */
FUEL_GAUGE_PROP_MAX = UINT16_MAX,
};
typedef uint16_t fuel_gauge_prop_t;
/** Property field to value/type union */
union fuel_gauge_prop_val {
/* Fields have the format: */
/* FUEL_GAUGE_PROPERTY_FIELD */
/* type property_field; */
/* Dynamic Battery Info */
/** FUEL_GAUGE_AVG_CURRENT */
int avg_current;
/** FUEL_GAUGE_CHARGE_CUTOFF */
bool cutoff;
/** FUEL_GAUGE_CURRENT */
int current;
/** FUEL_GAUGE_CYCLE_COUNT */
uint32_t cycle_count;
/** FUEL_GAUGE_FLAGS */
uint32_t flags;
/** FUEL_GAUGE_FULL_CHARGE_CAPACITY */
uint32_t full_charge_capacity;
/** FUEL_GAUGE_REMAINING_CAPACITY */
uint32_t remaining_capacity;
/** FUEL_GAUGE_RUNTIME_TO_EMPTY */
uint32_t runtime_to_empty;
/** FUEL_GAUGE_RUNTIME_TO_FULL */
uint32_t runtime_to_full;
/** FUEL_GAUGE_SBS_MFR_ACCESS */
uint16_t sbs_mfr_access_word;
/** FUEL_GAUGE_ABSOLUTE_STATE_OF_CHARGE */
uint8_t absolute_state_of_charge;
/** FUEL_GAUGE_RELATIVE_STATE_OF_CHARGE */
uint8_t relative_state_of_charge;
/** FUEL_GAUGE_TEMPERATURE */
uint16_t temperature;
/** FUEL_GAUGE_VOLTAGE */
int voltage;
/** FUEL_GAUGE_SBS_MODE */
uint16_t sbs_mode;
/** FUEL_GAUGE_CHARGE_CURRENT */
uint32_t chg_current;
/** FUEL_GAUGE_CHARGE_VOLTAGE */
uint32_t chg_voltage;
/** FUEL_GAUGE_STATUS */
uint16_t fg_status;
/** FUEL_GAUGE_DESIGN_CAPACITY */
uint16_t design_cap;
/** FUEL_GAUGE_DESIGN_VOLTAGE */
uint16_t design_volt;
/** FUEL_GAUGE_SBS_ATRATE */
int16_t sbs_at_rate;
/** FUEL_GAUGE_SBS_ATRATE_TIME_TO_FULL */
uint16_t sbs_at_rate_time_to_full;
/** FUEL_GAUGE_SBS_ATRATE_TIME_TO_EMPTY */
uint16_t sbs_at_rate_time_to_empty;
/** FUEL_GAUGE_SBS_ATRATE_OK */
bool sbs_at_rate_ok;
/** FUEL_GAUGE_SBS_REMAINING_CAPACITY_ALARM */
uint16_t sbs_remaining_capacity_alarm;
/** FUEL_GAUGE_SBS_REMAINING_TIME_ALARM */
uint16_t sbs_remaining_time_alarm;
};
/**
* Data structures for reading SBS buffer properties
*/
#define SBS_GAUGE_MANUFACTURER_NAME_MAX_SIZE 20
#define SBS_GAUGE_DEVICE_NAME_MAX_SIZE 20
#define SBS_GAUGE_DEVICE_CHEMISTRY_MAX_SIZE 4
struct sbs_gauge_manufacturer_name {
uint8_t manufacturer_name_length;
char manufacturer_name[SBS_GAUGE_MANUFACTURER_NAME_MAX_SIZE];
} __packed;
struct sbs_gauge_device_name {
uint8_t device_name_length;
char device_name[SBS_GAUGE_DEVICE_NAME_MAX_SIZE];
} __packed;
struct sbs_gauge_device_chemistry {
uint8_t device_chemistry_length;
char device_chemistry[SBS_GAUGE_DEVICE_CHEMISTRY_MAX_SIZE];
} __packed;
/**
* @typedef fuel_gauge_get_property_t
* @brief Callback API for getting a fuel_gauge property.
*
* See fuel_gauge_get_property() for argument description
*/
typedef int (*fuel_gauge_get_property_t)(const struct device *dev, fuel_gauge_prop_t prop,
union fuel_gauge_prop_val *val);
/**
* @typedef fuel_gauge_set_property_t
* @brief Callback API for setting a fuel_gauge property.
*
* See fuel_gauge_set_property() for argument description
*/
typedef int (*fuel_gauge_set_property_t)(const struct device *dev, fuel_gauge_prop_t prop,
union fuel_gauge_prop_val val);
/**
* @typedef fuel_gauge_get_buffer_property_t
* @brief Callback API for getting a fuel_gauge buffer property.
*
* See fuel_gauge_get_buffer_property() for argument description
*/
typedef int (*fuel_gauge_get_buffer_property_t)(const struct device *dev,
fuel_gauge_prop_t prop_type,
void *dst, size_t dst_len);
/**
* @typedef fuel_gauge_battery_cutoff_t
* @brief Callback API for doing a battery cutoff.
*
* See fuel_gauge_battery_cutoff() for argument description
*/
typedef int (*fuel_gauge_battery_cutoff_t)(const struct device *dev);
/* Caching is entirely on the onus of the client */
__subsystem struct fuel_gauge_driver_api {
/**
* Note: Historically this API allowed drivers to implement a custom multi-get/set property
* function, this was added so drivers could potentially optimize batch read with their
* specific chip. However, it was removed because of no existing concrete case upstream.
* If this need is demonstrated, we can add this back in as an API field.
*/
fuel_gauge_get_property_t get_property;
fuel_gauge_set_property_t set_property;
fuel_gauge_get_buffer_property_t get_buffer_property;
fuel_gauge_battery_cutoff_t battery_cutoff;
};
/**
* @brief Fetch a battery fuel-gauge property
*
* @param dev Pointer to the battery fuel-gauge device
* @param prop Type of property to be fetched from device
* @param val pointer to a union fuel_gauge_prop_val where the property is read into from the
* fuel gauge device.
* @return 0 if successful, negative errno code if failure.
*/
__syscall int fuel_gauge_get_prop(const struct device *dev, fuel_gauge_prop_t prop,
union fuel_gauge_prop_val *val);
static inline int z_impl_fuel_gauge_get_prop(const struct device *dev, fuel_gauge_prop_t prop,
union fuel_gauge_prop_val *val)
{
const struct fuel_gauge_driver_api *api = (const struct fuel_gauge_driver_api *)dev->api;
if (api->get_property == NULL) {
return -ENOSYS;
}
return api->get_property(dev, prop, val);
}
/**
* @brief Fetch multiple battery fuel-gauge properties. The default implementation is the same as
* calling fuel_gauge_get_prop() multiple times. A driver may implement the `get_properties` field
* of the fuel gauge driver APIs struct to override this implementation.
*
* @param dev Pointer to the battery fuel-gauge device
* @param props Array of the type of property to be fetched from device, each index corresponds
* to the same index of the vals input array.
* @param vals Pointer to array of union fuel_gauge_prop_val where the property is read into from
* the fuel gauge device. The vals array is not permuted.
* @param len number of properties in props & vals array
*
* @return 0 if successful, negative errno code of first failing property
*/
__syscall int fuel_gauge_get_props(const struct device *dev, fuel_gauge_prop_t *props,
union fuel_gauge_prop_val *vals, size_t len);
static inline int z_impl_fuel_gauge_get_props(const struct device *dev,
fuel_gauge_prop_t *props,
union fuel_gauge_prop_val *vals, size_t len)
{
const struct fuel_gauge_driver_api *api = dev->api;
for (int i = 0; i < len; i++) {
int ret = api->get_property(dev, props[i], vals + i);
if (ret) {
return ret;
}
}
return 0;
}
/**
* @brief Set a battery fuel-gauge property
*
* @param dev Pointer to the battery fuel-gauge device
* @param prop Type of property that's being set
* @param val Value to set associated prop property.
*
* @return 0 if successful, negative errno code of first failing property
*/
__syscall int fuel_gauge_set_prop(const struct device *dev, fuel_gauge_prop_t prop,
union fuel_gauge_prop_val val);
static inline int z_impl_fuel_gauge_set_prop(const struct device *dev, fuel_gauge_prop_t prop,
union fuel_gauge_prop_val val)
{
const struct fuel_gauge_driver_api *api = dev->api;
if (api->set_property == NULL) {
return -ENOSYS;
}
return api->set_property(dev, prop, val);
}
/**
* @brief Set a battery fuel-gauge property
*
* @param dev Pointer to the battery fuel-gauge device
* @param props Array of the type of property to be set, each index corresponds
* to the same index of the vals input array.
* @param vals Pointer to array of union fuel_gauge_prop_val where the property is written
* the fuel gauge device. The vals array is not permuted.
* @param len number of properties in props array
*
* @return return=0 if successful. Otherwise, return array index of failing property.
*/
__syscall int fuel_gauge_set_props(const struct device *dev, fuel_gauge_prop_t *props,
union fuel_gauge_prop_val *vals, size_t len);
static inline int z_impl_fuel_gauge_set_props(const struct device *dev,
fuel_gauge_prop_t *props,
union fuel_gauge_prop_val *vals, size_t len)
{
for (int i = 0; i < len; i++) {
int ret = fuel_gauge_set_prop(dev, props[i], vals[i]);
if (ret) {
return ret;
}
}
return 0;
}
/**
* @brief Fetch a battery fuel-gauge buffer property
*
* @param dev Pointer to the battery fuel-gauge device
* @param prop_type Type of property to be fetched from device
* @param dst byte array or struct that will hold the buffer data that is read from the fuel gauge
* @param dst_len the length of the destination array in bytes
*
* @return return=0 if successful, return < 0 if getting property failed, return 0 on success
*/
__syscall int fuel_gauge_get_buffer_prop(const struct device *dev, fuel_gauge_prop_t prop_type,
void *dst, size_t dst_len);
static inline int z_impl_fuel_gauge_get_buffer_prop(const struct device *dev,
fuel_gauge_prop_t prop_type,
void *dst, size_t dst_len)
{
const struct fuel_gauge_driver_api *api = (const struct fuel_gauge_driver_api *)dev->api;
if (api->get_buffer_property == NULL) {
return -ENOSYS;
}
return api->get_buffer_property(dev, prop_type, dst, dst_len);
}
/**
* @brief Have fuel gauge cutoff its associated battery.
*
* @param dev Pointer to the battery fuel-gauge device
*
* @return return=0 if successful and battery cutoff is now in process, return < 0 if failed to do
* battery cutoff.
*/
__syscall int fuel_gauge_battery_cutoff(const struct device *dev);
static inline int z_impl_fuel_gauge_battery_cutoff(const struct device *dev)
{
const struct fuel_gauge_driver_api *api = (const struct fuel_gauge_driver_api *)dev->api;
if (api->battery_cutoff == NULL) {
return -ENOSYS;
}
return api->battery_cutoff(dev);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* __cplusplus */
#include <zephyr/syscalls/fuel_gauge.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_BATTERY_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/fuel_gauge.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 3,466 |
```objective-c
/**
* @file drivers/entropy.h
*
* @brief Public APIs for the entropy driver.
*/
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_ENTROPY_H_
#define ZEPHYR_INCLUDE_DRIVERS_ENTROPY_H_
/**
* @brief Entropy Interface
* @defgroup entropy_interface Entropy Interface
* @since 1.10
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @brief Driver is allowed to busy-wait for random data to be ready */
#define ENTROPY_BUSYWAIT BIT(0)
/**
* @typedef entropy_get_entropy_t
* @brief Callback API to get entropy.
*
* @note This call has to be thread safe to satisfy requirements
* of the random subsystem.
*
* See entropy_get_entropy() for argument description
*/
typedef int (*entropy_get_entropy_t)(const struct device *dev,
uint8_t *buffer,
uint16_t length);
/**
* @typedef entropy_get_entropy_isr_t
* @brief Callback API to get entropy from an ISR.
*
* See entropy_get_entropy_isr() for argument description
*/
typedef int (*entropy_get_entropy_isr_t)(const struct device *dev,
uint8_t *buffer,
uint16_t length,
uint32_t flags);
/**
* @brief Entropy driver API structure.
*
* This is the mandatory API any Entropy driver needs to expose.
*/
__subsystem struct entropy_driver_api {
entropy_get_entropy_t get_entropy;
entropy_get_entropy_isr_t get_entropy_isr;
};
/**
* @brief Fills a buffer with entropy. Blocks if required in order to
* generate the necessary random data.
*
* @param dev Pointer to the entropy device.
* @param buffer Buffer to fill with entropy.
* @param length Buffer length.
* @retval 0 on success.
* @retval -ERRNO errno code on error.
*/
__syscall int entropy_get_entropy(const struct device *dev,
uint8_t *buffer,
uint16_t length);
static inline int z_impl_entropy_get_entropy(const struct device *dev,
uint8_t *buffer,
uint16_t length)
{
const struct entropy_driver_api *api =
(const struct entropy_driver_api *)dev->api;
__ASSERT(api->get_entropy != NULL,
"Callback pointer should not be NULL");
return api->get_entropy(dev, buffer, length);
}
/**
* @brief Fills a buffer with entropy in a non-blocking or busy-wait manner.
* Callable from ISRs.
*
* @param dev Pointer to the device structure.
* @param buffer Buffer to fill with entropy.
* @param length Buffer length.
* @param flags Flags to modify the behavior of the call.
* @retval number of bytes filled with entropy or -error.
*/
static inline int entropy_get_entropy_isr(const struct device *dev,
uint8_t *buffer,
uint16_t length,
uint32_t flags)
{
const struct entropy_driver_api *api =
(const struct entropy_driver_api *)dev->api;
if (unlikely(!api->get_entropy_isr)) {
return -ENOTSUP;
}
return api->get_entropy_isr(dev, buffer, length, flags);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/entropy.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_ENTROPY_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/entropy.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 743 |
```objective-c
/*
*
*/
/**
* @file
* Public APIs for external cache controller drivers
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CACHE_H_
#define ZEPHYR_INCLUDE_DRIVERS_CACHE_H_
#include <stddef.h>
/**
* @brief External Cache Controller Interface
* @defgroup cache_external_interface External Cache Controller Interface
* @ingroup io_interfaces
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
#if defined(CONFIG_DCACHE)
/**
* @brief Enable the d-cache
*
* Enable the data cache.
*/
void cache_data_enable(void);
/**
* @brief Disable the d-cache
*
* Disable the data cache.
*/
void cache_data_disable(void);
/**
* @brief Flush the d-cache
*
* Flush the whole data cache.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_data_flush_all(void);
/**
* @brief Invalidate the d-cache
*
* Invalidate the whole data cache.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_data_invd_all(void);
/**
* @brief Flush and Invalidate the d-cache
*
* Flush and Invalidate the whole data cache.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_data_flush_and_invd_all(void);
/**
* @brief Flush an address range in the d-cache
*
* Flush the specified address range of the data cache.
*
* @note the cache operations act on cache line. When multiple data structures
* share the same cache line being flushed, all the portions of the
* data structures sharing the same line will be flushed. This is usually
* not a problem because writing back is a non-destructive process that
* could be triggered by hardware at any time, so having an aligned
* @p addr or a padded @p size is not strictly necessary.
*
* @param addr Starting address to flush.
* @param size Range size.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_data_flush_range(void *addr, size_t size);
/**
* @brief Invalidate an address range in the d-cache
*
* Invalidate the specified address range of the data cache.
*
* @note the cache operations act on cache line. When multiple data structures
* share the same cache line being invalidated, all the portions of the
* non-read-only data structures sharing the same line will be
* invalidated as well. This is a destructive process that could lead to
* data loss and/or corruption. When @p addr is not aligned to the cache
* line and/or @p size is not a multiple of the cache line size the
* behaviour is undefined.
*
* @param addr Starting address to invalidate.
* @param size Range size.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_data_invd_range(void *addr, size_t size);
/**
* @brief Flush and Invalidate an address range in the d-cache
*
* Flush and Invalidate the specified address range of the data cache.
*
* @note the cache operations act on cache line. When multiple data structures
* share the same cache line being flushed, all the portions of the
* data structures sharing the same line will be flushed before being
* invalidated. This is usually not a problem because writing back is a
* non-destructive process that could be triggered by hardware at any
* time, so having an aligned @p addr or a padded @p size is not strictly
* necessary.
*
* @param addr Starting address to flush and invalidate.
* @param size Range size.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_data_flush_and_invd_range(void *addr, size_t size);
#if defined(CONFIG_DCACHE_LINE_SIZE_DETECT)
/**
*
* @brief Get the d-cache line size.
*
* The API is provided to dynamically detect the data cache line size at run
* time.
*
* The function must be implemented only when CONFIG_DCACHE_LINE_SIZE_DETECT is
* defined.
*
* @retval size Size of the d-cache line.
* @retval 0 If the d-cache is not enabled.
*/
size_t cache_data_line_size_get(void);
#endif /* CONFIG_DCACHE_LINE_SIZE_DETECT */
#endif /* CONFIG_DCACHE */
#if defined(CONFIG_ICACHE)
/**
* @brief Enable the i-cache
*
* Enable the instruction cache.
*/
void cache_instr_enable(void);
/**
* @brief Disable the i-cache
*
* Disable the instruction cache.
*/
void cache_instr_disable(void);
/**
* @brief Flush the i-cache
*
* Flush the whole instruction cache.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_instr_flush_all(void);
/**
* @brief Invalidate the i-cache
*
* Invalidate the whole instruction cache.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_instr_invd_all(void);
/**
* @brief Flush and Invalidate the i-cache
*
* Flush and Invalidate the whole instruction cache.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_instr_flush_and_invd_all(void);
/**
* @brief Flush an address range in the i-cache
*
* Flush the specified address range of the instruction cache.
*
* @note the cache operations act on cache line. When multiple data structures
* share the same cache line being flushed, all the portions of the
* data structures sharing the same line will be flushed. This is usually
* not a problem because writing back is a non-destructive process that
* could be triggered by hardware at any time, so having an aligned
* @p addr or a padded @p size is not strictly necessary.
*
* @param addr Starting address to flush.
* @param size Range size.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_instr_flush_range(void *addr, size_t size);
/**
* @brief Invalidate an address range in the i-cache
*
* Invalidate the specified address range of the instruction cache.
*
* @note the cache operations act on cache line. When multiple data structures
* share the same cache line being invalidated, all the portions of the
* non-read-only data structures sharing the same line will be
* invalidated as well. This is a destructive process that could lead to
* data loss and/or corruption. When @p addr is not aligned to the cache
* line and/or @p size is not a multiple of the cache line size the
* behaviour is undefined.
*
* @param addr Starting address to invalidate.
* @param size Range size.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_instr_invd_range(void *addr, size_t size);
/**
* @brief Flush and Invalidate an address range in the i-cache
*
* Flush and Invalidate the specified address range of the instruction cache.
*
* @note the cache operations act on cache line. When multiple data structures
* share the same cache line being flushed, all the portions of the
* data structures sharing the same line will be flushed before being
* invalidated. This is usually not a problem because writing back is a
* non-destructive process that could be triggered by hardware at any
* time, so having an aligned @p addr or a padded @p size is not strictly
* necessary.
*
* @param addr Starting address to flush and invalidate.
* @param size Range size.
*
* @retval 0 If succeeded.
* @retval -ENOTSUP If not supported.
* @retval -errno Negative errno for other failures.
*/
int cache_instr_flush_and_invd_range(void *addr, size_t size);
#ifdef CONFIG_ICACHE_LINE_SIZE_DETECT
/**
*
* @brief Get the i-cache line size.
*
* The API is provided to dynamically detect the instruction cache line size at
* run time.
*
* The function must be implemented only when CONFIG_ICACHE_LINE_SIZE_DETECT is
* defined.
*
* @retval size Size of the d-cache line.
* @retval 0 If the d-cache is not enabled.
*/
size_t cache_instr_line_size_get(void);
#endif /* CONFIG_ICACHE_LINE_SIZE_DETECT */
#endif /* CONFIG_ICACHE */
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_CACHE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/cache.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,944 |
```objective-c
/**
* @file
*
* @brief Public APIs to get device Information.
*/
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_HWINFO_H_
#define ZEPHYR_INCLUDE_DRIVERS_HWINFO_H_
/**
* @brief Hardware Information Interface
* @defgroup hwinfo_interface Hardware Info Interface
* @since 1.14
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <zephyr/types.h>
#include <sys/types.h>
#include <stddef.h>
#include <errno.h>
#include <zephyr/kernel.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name Reset cause flags
* @anchor reset_cause
* @{
*/
/** External pin */
#define RESET_PIN BIT(0)
/** Software reset */
#define RESET_SOFTWARE BIT(1)
/** Brownout (drop in voltage) */
#define RESET_BROWNOUT BIT(2)
/** Power-on reset (POR) */
#define RESET_POR BIT(3)
/** Watchdog timer expiration */
#define RESET_WATCHDOG BIT(4)
/** Debug event */
#define RESET_DEBUG BIT(5)
/** Security violation */
#define RESET_SECURITY BIT(6)
/** Waking up from low power mode */
#define RESET_LOW_POWER_WAKE BIT(7)
/** CPU lock-up detected */
#define RESET_CPU_LOCKUP BIT(8)
/** Parity error */
#define RESET_PARITY BIT(9)
/** PLL error */
#define RESET_PLL BIT(10)
/** Clock error */
#define RESET_CLOCK BIT(11)
/** Hardware reset */
#define RESET_HARDWARE BIT(12)
/** User reset */
#define RESET_USER BIT(13)
/** Temperature reset */
#define RESET_TEMPERATURE BIT(14)
/**
* @}
*/
/**
* @brief Copy the device id to a buffer
*
* This routine copies "length" number of bytes of the device ID to the buffer.
* If the device ID is smaller than length, the rest of the buffer is left unchanged.
* The ID depends on the hardware and is not guaranteed unique.
*
* Drivers are responsible for ensuring that the ID data structure is a
* sequence of bytes. The returned ID value is not supposed to be interpreted
* based on vendor-specific assumptions of byte order. It should express the
* identifier as a raw byte sequence, doing any endian conversion necessary so
* that a hex representation of the bytes produces the intended serial number.
*
* @param buffer Buffer to write the ID to.
* @param length Max length of the buffer.
*
* @retval size of the device ID copied.
* @retval -ENOSYS if there is no implementation for the particular device.
* @retval any negative value on driver specific errors.
*/
__syscall ssize_t hwinfo_get_device_id(uint8_t *buffer, size_t length);
ssize_t z_impl_hwinfo_get_device_id(uint8_t *buffer, size_t length);
/**
* @brief Copy the device EUI64 to a buffer
*
* This routine copies the device EUI64 (8 bytes) to the buffer.
* The EUI64 depends on the hardware and is guaranteed unique.
*
* @param buffer Buffer of 8 bytes to write the ID to.
*
* @retval zero if successful.
* @retval -ENOSYS if there is no implementation for the particular device.
* @retval any negative value on driver specific errors.
*/
__syscall int hwinfo_get_device_eui64(uint8_t *buffer);
int z_impl_hwinfo_get_device_eui64(uint8_t *buffer);
/**
* @brief Retrieve cause of device reset.
*
* @param cause OR'd @ref reset_cause "reset cause" flags
*
* This routine retrieves the flags that indicate why the device was reset.
*
* On some platforms the reset cause flags accumulate between successive resets
* and this routine may return multiple flags indicating all reset causes
* since the device was powered on. If you need to retrieve the cause only for
* the most recent reset call `hwinfo_clear_reset_cause` after calling this
* routine to clear the hardware flags before the next reset event.
*
* Successive calls to this routine will return the same value, unless
* `hwinfo_clear_reset_cause` has been called.
*
* @retval zero if successful.
* @retval -ENOSYS if there is no implementation for the particular device.
* @retval any negative value on driver specific errors.
*/
__syscall int hwinfo_get_reset_cause(uint32_t *cause);
int z_impl_hwinfo_get_reset_cause(uint32_t *cause);
/**
* @brief Clear cause of device reset.
*
* Clears reset cause flags.
*
* @retval zero if successful.
* @retval -ENOSYS if there is no implementation for the particular device.
* @retval any negative value on driver specific errors.
*/
__syscall int hwinfo_clear_reset_cause(void);
int z_impl_hwinfo_clear_reset_cause(void);
/**
* @brief Get supported reset cause flags
*
* @param supported OR'd @ref reset_cause "reset cause" flags that are supported
*
* Retrieves all `reset_cause` flags that are supported by this device.
*
* @retval zero if successful.
* @retval -ENOSYS if there is no implementation for the particular device.
* @retval any negative value on driver specific errors.
*/
__syscall int hwinfo_get_supported_reset_cause(uint32_t *supported);
int z_impl_hwinfo_get_supported_reset_cause(uint32_t *supported);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/hwinfo.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_HWINFO_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/hwinfo.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,193 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public API for counter and timer drivers
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_COUNTER_H_
#define ZEPHYR_INCLUDE_DRIVERS_COUNTER_H_
/**
* @brief Counter Interface
* @defgroup counter_interface Counter Interface
* @since 1.14
* @version 0.8.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <stddef.h>
#include <zephyr/device.h>
#include <zephyr/sys_clock.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @anchor COUNTER_FLAGS
* @name Counter device capabilities
* @{
*/
/**
* @brief Counter count up flag.
*/
#define COUNTER_CONFIG_INFO_COUNT_UP BIT(0)
/**@} */
/**
* @anchor COUNTER_TOP_FLAGS
* @name Flags used by counter_top_cfg.
* @{
*/
/**
* @brief Flag preventing counter reset when top value is changed.
*
* If flags is set then counter is free running while top value is updated,
* otherwise counter is reset (see @ref counter_set_top_value()).
*/
#define COUNTER_TOP_CFG_DONT_RESET BIT(0)
/**
* @brief Flag instructing counter to reset itself if changing top value
* results in counter going out of new top value bound.
*
* See @ref COUNTER_TOP_CFG_DONT_RESET.
*/
#define COUNTER_TOP_CFG_RESET_WHEN_LATE BIT(1)
/**@} */
/**
* @anchor COUNTER_ALARM_FLAGS
* @name Alarm configuration flags
*
* @brief Used in alarm configuration structure (@ref counter_alarm_cfg).
* @{ */
/**
* @brief Counter alarm absolute value flag.
*
* Ticks relation to counter value. If set ticks are treated as absolute value,
* else it is relative to the counter reading performed during the call.
*/
#define COUNTER_ALARM_CFG_ABSOLUTE BIT(0)
/**
* @brief Alarm flag enabling immediate expiration when driver detects that
* absolute alarm was set too late.
*
* Alarm callback must be called from the same context as if it was set on time.
*/
#define COUNTER_ALARM_CFG_EXPIRE_WHEN_LATE BIT(1)
/**@} */
/**
* @anchor COUNTER_GUARD_PERIOD_FLAGS
* @name Counter guard period flags
*
* @brief Used by @ref counter_set_guard_period and
* @ref counter_get_guard_period.
* @{ */
/**
* @brief Identifies guard period needed for detection of late setting of
* absolute alarm (see @ref counter_set_channel_alarm).
*/
#define COUNTER_GUARD_PERIOD_LATE_TO_SET BIT(0)
/**@} */
/** @brief Alarm callback
*
* @param dev Pointer to the device structure for the driver instance.
* @param chan_id Channel ID.
* @param ticks Counter value that triggered the alarm.
* @param user_data User data.
*/
typedef void (*counter_alarm_callback_t)(const struct device *dev,
uint8_t chan_id, uint32_t ticks,
void *user_data);
/** @brief Alarm callback structure.
*/
struct counter_alarm_cfg {
/**
* Callback called on alarm (cannot be NULL).
*/
counter_alarm_callback_t callback;
/**
* Number of ticks that triggers the alarm.
*
* It can be relative (to now) or an absolute value (see @ref
* COUNTER_ALARM_CFG_ABSOLUTE). Both, relative and absolute, alarm
* values can be any value between zero and the current top value (see
* @ref counter_get_top_value). When setting an absolute alarm value
* close to the current counter value there is a risk that the counter
* will have counted past the given absolute value before the driver
* manages to activate the alarm. Therefore a guard period can be
* defined that lets the driver decide unambiguously whether it is late
* or not (see @ref counter_set_guard_period). If the counter is clock
* driven then ticks can be converted to microseconds (see @ref
* counter_ticks_to_us). Alternatively, the counter implementation may
* count asynchronous events.
*/
uint32_t ticks;
/**
* User data returned in callback.
*/
void *user_data;
/**
* Alarm flags (see @ref COUNTER_ALARM_FLAGS).
*/
uint32_t flags;
};
/** @brief Callback called when counter turns around.
*
* @param dev Pointer to the device structure for the driver instance.
* @param user_data User data provided in @ref counter_set_top_value.
*/
typedef void (*counter_top_callback_t)(const struct device *dev,
void *user_data);
/** @brief Top value configuration structure.
*/
struct counter_top_cfg {
/**
* Top value.
*/
uint32_t ticks;
/**
* Callback function (can be NULL).
*/
counter_top_callback_t callback;
/**
* User data passed to callback function (not valid if callback is NULL).
*/
void *user_data;
/**
* Flags (see @ref COUNTER_TOP_FLAGS).
*/
uint32_t flags;
};
/** @brief Structure with generic counter features.
*/
struct counter_config_info {
/**
* Maximal (default) top value on which counter is reset (cleared or reloaded).
*/
uint32_t max_top_value;
/**
* Frequency of the source clock if synchronous events are counted.
*/
uint32_t freq;
/**
* Flags (see @ref COUNTER_FLAGS).
*/
uint8_t flags;
/**
* Number of channels that can be used for setting alarm.
*
* @see counter_set_channel_alarm
*/
uint8_t channels;
};
typedef int (*counter_api_start)(const struct device *dev);
typedef int (*counter_api_stop)(const struct device *dev);
typedef int (*counter_api_get_value)(const struct device *dev,
uint32_t *ticks);
typedef int (*counter_api_get_value_64)(const struct device *dev,
uint64_t *ticks);
typedef int (*counter_api_set_alarm)(const struct device *dev,
uint8_t chan_id,
const struct counter_alarm_cfg *alarm_cfg);
typedef int (*counter_api_cancel_alarm)(const struct device *dev,
uint8_t chan_id);
typedef int (*counter_api_set_top_value)(const struct device *dev,
const struct counter_top_cfg *cfg);
typedef uint32_t (*counter_api_get_pending_int)(const struct device *dev);
typedef uint32_t (*counter_api_get_top_value)(const struct device *dev);
typedef uint32_t (*counter_api_get_guard_period)(const struct device *dev,
uint32_t flags);
typedef int (*counter_api_set_guard_period)(const struct device *dev,
uint32_t ticks,
uint32_t flags);
typedef uint32_t (*counter_api_get_freq)(const struct device *dev);
__subsystem struct counter_driver_api {
counter_api_start start;
counter_api_stop stop;
counter_api_get_value get_value;
counter_api_get_value_64 get_value_64;
counter_api_set_alarm set_alarm;
counter_api_cancel_alarm cancel_alarm;
counter_api_set_top_value set_top_value;
counter_api_get_pending_int get_pending_int;
counter_api_get_top_value get_top_value;
counter_api_get_guard_period get_guard_period;
counter_api_set_guard_period set_guard_period;
counter_api_get_freq get_freq;
};
/**
* @brief Function to check if counter is counting up.
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @retval true if counter is counting up.
* @retval false if counter is counting down.
*/
__syscall bool counter_is_counting_up(const struct device *dev);
static inline bool z_impl_counter_is_counting_up(const struct device *dev)
{
const struct counter_config_info *config =
(const struct counter_config_info *)dev->config;
return config->flags & COUNTER_CONFIG_INFO_COUNT_UP;
}
/**
* @brief Function to get number of alarm channels.
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @return Number of alarm channels.
*/
__syscall uint8_t counter_get_num_of_channels(const struct device *dev);
static inline uint8_t z_impl_counter_get_num_of_channels(const struct device *dev)
{
const struct counter_config_info *config =
(const struct counter_config_info *)dev->config;
return config->channels;
}
/**
* @brief Function to get counter frequency.
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @return Frequency of the counter in Hz, or zero if the counter does
* not have a fixed frequency.
*/
__syscall uint32_t counter_get_frequency(const struct device *dev);
static inline uint32_t z_impl_counter_get_frequency(const struct device *dev)
{
const struct counter_config_info *config =
(const struct counter_config_info *)dev->config;
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
return api->get_freq ? api->get_freq(dev) : config->freq;
}
/**
* @brief Function to convert microseconds to ticks.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param[in] us Microseconds.
*
* @return Converted ticks. Ticks will be saturated if exceed 32 bits.
*/
__syscall uint32_t counter_us_to_ticks(const struct device *dev, uint64_t us);
static inline uint32_t z_impl_counter_us_to_ticks(const struct device *dev,
uint64_t us)
{
uint64_t ticks = (us * z_impl_counter_get_frequency(dev)) / USEC_PER_SEC;
return (ticks > (uint64_t)UINT32_MAX) ? UINT32_MAX : ticks;
}
/**
* @brief Function to convert ticks to microseconds.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param[in] ticks Ticks.
*
* @return Converted microseconds.
*/
__syscall uint64_t counter_ticks_to_us(const struct device *dev, uint32_t ticks);
static inline uint64_t z_impl_counter_ticks_to_us(const struct device *dev,
uint32_t ticks)
{
return ((uint64_t)ticks * USEC_PER_SEC) / z_impl_counter_get_frequency(dev);
}
/**
* @brief Function to retrieve maximum top value that can be set.
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @return Max top value.
*/
__syscall uint32_t counter_get_max_top_value(const struct device *dev);
static inline uint32_t z_impl_counter_get_max_top_value(const struct device *dev)
{
const struct counter_config_info *config =
(const struct counter_config_info *)dev->config;
return config->max_top_value;
}
/**
* @brief Start counter device in free running mode.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int counter_start(const struct device *dev);
static inline int z_impl_counter_start(const struct device *dev)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
return api->start(dev);
}
/**
* @brief Stop counter device.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval -ENOTSUP if the device doesn't support stopping the
* counter.
*/
__syscall int counter_stop(const struct device *dev);
static inline int z_impl_counter_stop(const struct device *dev)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
return api->stop(dev);
}
/**
* @brief Get current counter value.
* @param dev Pointer to the device structure for the driver instance.
* @param ticks Pointer to where to store the current counter value
*
* @retval 0 If successful.
* @retval Negative error code on failure getting the counter value
*/
__syscall int counter_get_value(const struct device *dev, uint32_t *ticks);
static inline int z_impl_counter_get_value(const struct device *dev,
uint32_t *ticks)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
return api->get_value(dev, ticks);
}
/**
* @brief Get current counter 64-bit value.
* @param dev Pointer to the device structure for the driver instance.
* @param ticks Pointer to where to store the current counter value
*
* @retval 0 If successful.
* @retval Negative error code on failure getting the counter value
*/
__syscall int counter_get_value_64(const struct device *dev, uint64_t *ticks);
static inline int z_impl_counter_get_value_64(const struct device *dev,
uint64_t *ticks)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
if (!api->get_value_64) {
return -ENOTSUP;
}
return api->get_value_64(dev, ticks);
}
/**
* @brief Set a single shot alarm on a channel.
*
* After expiration alarm can be set again, disabling is not needed. When alarm
* expiration handler is called, channel is considered available and can be
* set again in that context.
*
* @note API is not thread safe.
*
* @param dev Pointer to the device structure for the driver instance.
* @param chan_id Channel ID.
* @param alarm_cfg Alarm configuration.
*
* @retval 0 If successful.
* @retval -ENOTSUP if request is not supported (device does not support
* interrupts or requested channel).
* @retval -EINVAL if alarm settings are invalid.
* @retval -ETIME if absolute alarm was set too late.
* @retval -EBUSY if alarm is already active.
*/
__syscall int counter_set_channel_alarm(const struct device *dev,
uint8_t chan_id,
const struct counter_alarm_cfg *alarm_cfg);
static inline int z_impl_counter_set_channel_alarm(const struct device *dev,
uint8_t chan_id,
const struct counter_alarm_cfg *alarm_cfg)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
if (chan_id >= counter_get_num_of_channels(dev)) {
return -ENOTSUP;
}
return api->set_alarm(dev, chan_id, alarm_cfg);
}
/**
* @brief Cancel an alarm on a channel.
*
* @note API is not thread safe.
*
* @param dev Pointer to the device structure for the driver instance.
* @param chan_id Channel ID.
*
* @retval 0 If successful.
* @retval -ENOTSUP if request is not supported or the counter was not started
* yet.
*/
__syscall int counter_cancel_channel_alarm(const struct device *dev,
uint8_t chan_id);
static inline int z_impl_counter_cancel_channel_alarm(const struct device *dev,
uint8_t chan_id)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
if (chan_id >= counter_get_num_of_channels(dev)) {
return -ENOTSUP;
}
return api->cancel_alarm(dev, chan_id);
}
/**
* @brief Set counter top value.
*
* Function sets top value and optionally resets the counter to 0 or top value
* depending on counter direction. On turnaround, counter can be reset and
* optional callback is periodically called. Top value can only be changed when
* there is no active channel alarm.
*
* @ref COUNTER_TOP_CFG_DONT_RESET prevents counter reset. When counter is
* running while top value is updated, it is possible that counter progresses
* outside the new top value. In that case, error is returned and optionally
* driver can reset the counter (see @ref COUNTER_TOP_CFG_RESET_WHEN_LATE).
*
* @param dev Pointer to the device structure for the driver instance.
* @param cfg Configuration. Cannot be NULL.
*
* @retval 0 If successful.
* @retval -ENOTSUP if request is not supported (e.g. top value cannot be
* changed or counter cannot/must be reset during top value
update).
* @retval -EBUSY if any alarm is active.
* @retval -ETIME if @ref COUNTER_TOP_CFG_DONT_RESET was set and new top value
* is smaller than current counter value (counter counting up).
*/
__syscall int counter_set_top_value(const struct device *dev,
const struct counter_top_cfg *cfg);
static inline int z_impl_counter_set_top_value(const struct device *dev,
const struct counter_top_cfg
*cfg)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
if (cfg->ticks > counter_get_max_top_value(dev)) {
return -EINVAL;
}
return api->set_top_value(dev, cfg);
}
/**
* @brief Function to get pending interrupts
*
* The purpose of this function is to return the interrupt
* status register for the device.
* This is especially useful when waking up from
* low power states to check the wake up source.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 1 if any counter interrupt is pending.
* @retval 0 if no counter interrupt is pending.
*/
__syscall int counter_get_pending_int(const struct device *dev);
static inline int z_impl_counter_get_pending_int(const struct device *dev)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
return api->get_pending_int(dev);
}
/**
* @brief Function to retrieve current top value.
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @return Top value.
*/
__syscall uint32_t counter_get_top_value(const struct device *dev);
static inline uint32_t z_impl_counter_get_top_value(const struct device *dev)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
return api->get_top_value(dev);
}
/**
* @brief Set guard period in counter ticks.
*
* When setting an absolute alarm value close to the current counter value there
* is a risk that the counter will have counted past the given absolute value
* before the driver manages to activate the alarm. If this would go unnoticed
* then the alarm would only expire after the timer has wrapped and reached the
* given absolute value again after a full timer period. This could take a long
* time in case of a 32 bit timer. Setting a sufficiently large guard period will
* help the driver detect unambiguously whether it is late or not.
*
* The guard period should be as many counter ticks as the driver will need at
* most to actually activate the alarm after the driver API has been called. If
* the driver finds that the counter has just passed beyond the given absolute
* tick value but is still close enough to fall within the guard period, it will
* assume that it is "late", i.e. that the intended expiry time has already passed.
* Depending on the @ref COUNTER_ALARM_CFG_EXPIRE_WHEN_LATE flag the driver will
* either ignore the alarm or expire it immediately in such a case.
*
* If, however, the counter is past the given absolute tick value but outside
* the guard period, then the driver will assume that this is intentional and
* let the counter wrap around to/from zero before it expires.
*
* More precisely:
*
* - When counting upwards (see @ref COUNTER_CONFIG_INFO_COUNT_UP) the given
* absolute tick value must be above (now + guard_period) % top_value to be
* accepted by the driver.
* - When counting downwards, the given absolute tick value must be less than
* (now + top_value - guard_period) % top_value to be accepted.
*
* Examples:
*
* - counting upwards, now = 4950, top value = 5000, guard period = 100:
* absolute tick value >= (4950 + 100) % 5000 = 50
* - counting downwards, now = 50, top value = 5000, guard period = 100:
* absolute tick value <= (50 + 5000 - * 100) % 5000 = 4950
*
* If you need only short alarm periods, you can set the guard period very high
* (e.g. half of the counter top value) which will make it highly unlikely that
* the counter will ever unintentionally wrap.
*
* The guard period is set to 0 on initialization (no protection).
*
* @param dev Pointer to the device structure for the driver instance.
* @param ticks Guard period in counter ticks.
* @param flags See @ref COUNTER_GUARD_PERIOD_FLAGS.
*
* @retval 0 if successful.
* @retval -ENOTSUP if function or flags are not supported.
* @retval -EINVAL if ticks value is invalid.
*/
__syscall int counter_set_guard_period(const struct device *dev,
uint32_t ticks,
uint32_t flags);
static inline int z_impl_counter_set_guard_period(const struct device *dev,
uint32_t ticks, uint32_t flags)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
if (!api->set_guard_period) {
return -ENOTSUP;
}
return api->set_guard_period(dev, ticks, flags);
}
/**
* @brief Return guard period.
*
* @see counter_set_guard_period.
*
* @param dev Pointer to the device structure for the driver instance.
* @param flags See @ref COUNTER_GUARD_PERIOD_FLAGS.
*
* @return Guard period given in counter ticks or 0 if function or flags are
* not supported.
*/
__syscall uint32_t counter_get_guard_period(const struct device *dev,
uint32_t flags);
static inline uint32_t z_impl_counter_get_guard_period(const struct device *dev,
uint32_t flags)
{
const struct counter_driver_api *api =
(struct counter_driver_api *)dev->api;
return (api->get_guard_period) ? api->get_guard_period(dev, flags) : 0;
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/counter.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_COUNTER_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/counter.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 4,774 |
```objective-c
/*
*
*/
/**
* @file
* @brief DAC public API header file.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_DAC_H_
#define ZEPHYR_INCLUDE_DRIVERS_DAC_H_
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief DAC driver APIs
* @defgroup dac_interface DAC driver APIs
* @since 2.3
* @version 0.8.0
* @ingroup io_interfaces
* @{
*/
/**
* @brief Structure for specifying the configuration of a DAC channel.
*/
struct dac_channel_cfg {
/** Channel identifier of the DAC that should be configured. */
uint8_t channel_id;
/** Desired resolution of the DAC (depends on device capabilities). */
uint8_t resolution;
/** Enable output buffer for this channel.
* This is relevant for instance if the output is directly connected to the load,
* without an amplifierin between. The actual details on this are hardware dependent.
*/
bool buffered;
};
/**
* @cond INTERNAL_HIDDEN
*
* For internal use only, skip these in public documentation.
*/
/*
* Type definition of DAC API function for configuring a channel.
* See dac_channel_setup() for argument descriptions.
*/
typedef int (*dac_api_channel_setup)(const struct device *dev,
const struct dac_channel_cfg *channel_cfg);
/*
* Type definition of DAC API function for setting a write request.
* See dac_write_value() for argument descriptions.
*/
typedef int (*dac_api_write_value)(const struct device *dev,
uint8_t channel, uint32_t value);
/*
* DAC driver API
*
* This is the mandatory API any DAC driver needs to expose.
*/
__subsystem struct dac_driver_api {
dac_api_channel_setup channel_setup;
dac_api_write_value write_value;
};
/**
* @endcond
*/
/**
* @brief Configure a DAC channel.
*
* It is required to call this function and configure each channel before it is
* selected for a write request.
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel_cfg Channel configuration.
*
* @retval 0 On success.
* @retval -EINVAL If a parameter with an invalid value has been provided.
* @retval -ENOTSUP If the requested resolution is not supported.
*/
__syscall int dac_channel_setup(const struct device *dev,
const struct dac_channel_cfg *channel_cfg);
static inline int z_impl_dac_channel_setup(const struct device *dev,
const struct dac_channel_cfg *channel_cfg)
{
const struct dac_driver_api *api =
(const struct dac_driver_api *)dev->api;
return api->channel_setup(dev, channel_cfg);
}
/**
* @brief Write a single value to a DAC channel
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel Number of the channel to be used.
* @param value Data to be written to DAC output registers.
*
* @retval 0 On success.
* @retval -EINVAL If a parameter with an invalid value has been provided.
*/
__syscall int dac_write_value(const struct device *dev, uint8_t channel,
uint32_t value);
static inline int z_impl_dac_write_value(const struct device *dev,
uint8_t channel, uint32_t value)
{
const struct dac_driver_api *api =
(const struct dac_driver_api *)dev->api;
return api->write_value(dev, channel, value);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/dac.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_DAC_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/dac.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 768 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_HAPTICS_H_
#define ZEPHYR_INCLUDE_DRIVERS_HAPTICS_H_
/**
* @brief Haptics Interface
* @defgroup haptics_interface Haptics Interface
* @ingroup io_interfaces
* @{
*/
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @typedef haptics_stop_output_t
* @brief Set the haptic device to stop output
* @param dev Pointer to the device structure for haptic device instance
*/
typedef int (*haptics_stop_output_t)(const struct device *dev);
/**
* @typedef haptics_start_output_t
* @brief Set the haptic device to start output for a playback event
*/
typedef int (*haptics_start_output_t)(const struct device *dev);
/**
* @brief Haptic device API
*/
__subsystem struct haptics_driver_api {
haptics_start_output_t start_output;
haptics_stop_output_t stop_output;
};
/**
* @brief Set the haptic device to start output for a playback event
*
* @param dev Pointer to the device structure for haptic device instance
*
* @retval 0 if successful
* @retval <0 if failed
*/
__syscall int haptics_start_output(const struct device *dev);
static inline int z_impl_haptics_start_output(const struct device *dev)
{
const struct haptics_driver_api *api = (const struct haptics_driver_api *)dev->api;
return api->start_output(dev);
}
/**
* @brief Set the haptic device to stop output for a playback event
*
* @param dev Pointer to the device structure for haptic device instance
*
* @retval 0 if successful
* @retval <0 if failed
*/
__syscall int haptics_stop_output(const struct device *dev);
static inline int z_impl_haptics_stop_output(const struct device *dev)
{
const struct haptics_driver_api *api = (const struct haptics_driver_api *)dev->api;
return api->stop_output(dev);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* __cplusplus */
#include <syscalls/haptics.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_HAPTICS_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/haptics.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 482 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public API for auxiliary (textual/non-graphical) display drivers
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_AUXDISPLAY_H_
#define ZEPHYR_INCLUDE_DRIVERS_AUXDISPLAY_H_
/**
* @brief Auxiliary (Text) Display Interface
* @defgroup auxdisplay_interface Text Display Interface
* @since 3.4
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#include <stdint.h>
#include <stddef.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @brief Used for minimum and maximum brightness/backlight values if not supported */
#define AUXDISPLAY_LIGHT_NOT_SUPPORTED 0
/** @brief Used to describe the mode of an auxiliary (text) display */
typedef uint32_t auxdisplay_mode_t;
/** @brief Used for moving the cursor or display position */
enum auxdisplay_position {
/** Moves to specified X,Y position */
AUXDISPLAY_POSITION_ABSOLUTE = 0,
/** Shifts current position by +/- X,Y position, does not take display direction into
* consideration
*/
AUXDISPLAY_POSITION_RELATIVE,
/** Shifts current position by +/- X,Y position, takes display direction into
* consideration
*/
AUXDISPLAY_POSITION_RELATIVE_DIRECTION,
AUXDISPLAY_POSITION_COUNT,
};
/** @brief Used for setting character append position */
enum auxdisplay_direction {
/** Each character will be placed to the right of existing characters */
AUXDISPLAY_DIRECTION_RIGHT = 0,
/** Each character will be placed to the left of existing characters */
AUXDISPLAY_DIRECTION_LEFT,
AUXDISPLAY_DIRECTION_COUNT,
};
/** @brief Light levels for brightness and/or backlight. If not supported by a
* display/driver, both minimum and maximum will be AUXDISPLAY_LIGHT_NOT_SUPPORTED.
*/
struct auxdisplay_light {
/** Minimum light level supported */
uint8_t minimum;
/** Maximum light level supported */
uint8_t maximum;
};
/** @brief Structure holding display capabilities. */
struct auxdisplay_capabilities {
/** Number of character columns */
uint16_t columns;
/** Number of character rows */
uint16_t rows;
/** Display-specific data (e.g. 4-bit or 8-bit mode for HD44780-based displays) */
auxdisplay_mode_t mode;
/** Brightness details for display (if supported) */
struct auxdisplay_light brightness;
/** Backlight details for display (if supported) */
struct auxdisplay_light backlight;
/** Number of custom characters supported by display (0 if unsupported) */
uint8_t custom_characters;
/** Width (in pixels) of a custom character, supplied custom characters should match. */
uint8_t custom_character_width;
/** Height (in pixels) of a custom character, supplied custom characters should match. */
uint8_t custom_character_height;
};
/** @brief Structure for a custom command. This may be extended by specific drivers. */
struct auxdisplay_custom_data {
/** Raw command data to be sent */
uint8_t *data;
/** Length of supplied data */
uint16_t len;
/** Display-driver specific options for command */
uint32_t options;
};
/** @brief Structure for a custom character. */
struct auxdisplay_character {
/** Custom character index on the display */
uint8_t index;
/** Custom character pixel data, a character must be valid for a display consisting
* of a uint8 array of size character width by character height, values should be
* 0x00 for pixel off or 0xff for pixel on, if a display supports shades then values
* between 0x00 and 0xff may be used (display driver dependent).
*/
uint8_t *data;
/** Will be updated with custom character index to use in the display write function to
* disaplay this custom character
*/
uint8_t character_code;
};
/**
* @cond INTERNAL_HIDDEN
*
* For internal use only, skip these in public documentation.
*/
/**
* @typedef auxdisplay_display_on_t
* @brief Callback API to turn display on
* See auxdisplay_display_on() for argument description
*/
typedef int (*auxdisplay_display_on_t)(const struct device *dev);
/**
* @typedef auxdisplay_display_off_t
* @brief Callback API to turn display off
* See auxdisplay_display_off() for argument description
*/
typedef int (*auxdisplay_display_off_t)(const struct device *dev);
/**
* @typedef auxdisplay_cursor_set_enabled_t
* @brief Callback API to turn display cursor visibility on or off
* See auxdisplay_cursor_set_enabled() for argument description
*/
typedef int (*auxdisplay_cursor_set_enabled_t)(const struct device *dev, bool enabled);
/**
* @typedef auxdisplay_position_blinking_set_enabled_t
* @brief Callback API to turn the current position blinking on or off
* See auxdisplay_position_blinking_set_enabled() for argument description
*/
typedef int (*auxdisplay_position_blinking_set_enabled_t)(const struct device *dev,
bool enabled);
/**
* @typedef auxdisplay_cursor_shift_set_t
* @brief Callback API to set how the cursor shifts after a character is written
* See auxdisplay_cursor_shift_set() for argument description
*/
typedef int (*auxdisplay_cursor_shift_set_t)(const struct device *dev, uint8_t direction,
bool display_shift);
/**
* @typedef auxdisplay_cursor_position_set_t
* @brief Callback API to set the cursor position
* See auxdisplay_cursor_position_set() for argument description
*/
typedef int (*auxdisplay_cursor_position_set_t)(const struct device *dev,
enum auxdisplay_position type,
int16_t x, int16_t y);
/**
* @typedef auxdisplay_cursor_position_get_t
* @brief Callback API to get the cursor position
* See auxdisplay_cursor_position_get() for argument description
*/
typedef int (*auxdisplay_cursor_position_get_t)(const struct device *dev, int16_t *x,
int16_t *y);
/**
* @typedef auxdisplay_display_position_set_t
* @brief Callback API to set the current position of the display
* See auxdisplay_display_position_set() for argument description
*/
typedef int (*auxdisplay_display_position_set_t)(const struct device *dev,
enum auxdisplay_position type,
int16_t x, int16_t y);
/**
* @typedef auxdisplay_display_position_get_t
* @brief Callback API to get the current position of the display
* See auxdisplay_display_position_get() for argument description
*/
typedef int (*auxdisplay_display_position_get_t)(const struct device *dev, int16_t *x,
int16_t *y);
/**
* @typedef auxdisplay_capabilities_get_t
* @brief Callback API to get details on the display
* See auxdisplay_capabilities_get() for argument description
*/
typedef int (*auxdisplay_capabilities_get_t)(const struct device *dev,
struct auxdisplay_capabilities *capabilities);
/**
* @typedef auxdisplay_clear_t
* @brief Callback API to clear the contents of the display
* See auxdisplay_clear() for argument description
*/
typedef int (*auxdisplay_clear_t)(const struct device *dev);
/**
* @typedef auxdisplay_brightness_get_t
* @brief Callback API to get the current and minimum/maximum supported
* brightness settings of the display
* See auxdisplay_brightness_get_api() for argument description
*/
typedef int (*auxdisplay_brightness_get_t)(const struct device *dev, uint8_t *brightness);
/**
* @typedef auxdisplay_brightness_set_t
* @brief Callback API to set the brightness of the display
* See auxdisplay_brightness_set_api() for argument description
*/
typedef int (*auxdisplay_brightness_set_t)(const struct device *dev, uint8_t brightness);
/**
* @typedef auxdisplay_backlight_get_t
* @brief Callback API to get the current and minimum/maximum supported
* backlight settings of the display
* See auxdisplay_backlight_set() for argument description
*/
typedef int (*auxdisplay_backlight_get_t)(const struct device *dev, uint8_t *backlight);
/**
* @typedef auxdisplay_backlight_set_t
* @brief Callback API to set the backlight status
* See auxdisplay_backlight_set() for argument description
*/
typedef int (*auxdisplay_backlight_set_t)(const struct device *dev, uint8_t backlight);
/**
* @typedef auxdisplay_is_busy_t
* @brief Callback API to check if the display is busy with an operation
* See auxdisplay_is_busy() for argument description
*/
typedef int (*auxdisplay_is_busy_t)(const struct device *dev);
/**
* @typedef auxdisplay_custom_character_set_t
* @brief Callback API to set a customer character on the display for usage
* See auxdisplay_custom_character_set() for argument description
*/
typedef int (*auxdisplay_custom_character_set_t)(const struct device *dev,
struct auxdisplay_character *character);
/**
* @typedef auxdisplay_write_t
* @brief Callback API to write text to the display
* See auxdisplay_write() for argument description
*/
typedef int (*auxdisplay_write_t)(const struct device *dev, const uint8_t *data, uint16_t len);
/**
* @typedef auxdisplay_custom_command_t
* @brief Callback API to send a custom command to the display
* See auxdisplay_custom_command() for argument description
*/
typedef int (*auxdisplay_custom_command_t)(const struct device *dev,
struct auxdisplay_custom_data *command);
__subsystem struct auxdisplay_driver_api {
auxdisplay_display_on_t display_on;
auxdisplay_display_off_t display_off;
auxdisplay_cursor_set_enabled_t cursor_set_enabled;
auxdisplay_position_blinking_set_enabled_t position_blinking_set_enabled;
auxdisplay_cursor_shift_set_t cursor_shift_set;
auxdisplay_cursor_position_set_t cursor_position_set;
auxdisplay_cursor_position_get_t cursor_position_get;
auxdisplay_display_position_set_t display_position_set;
auxdisplay_display_position_get_t display_position_get;
auxdisplay_capabilities_get_t capabilities_get;
auxdisplay_clear_t clear;
auxdisplay_brightness_get_t brightness_get;
auxdisplay_brightness_set_t brightness_set;
auxdisplay_backlight_get_t backlight_get;
auxdisplay_backlight_set_t backlight_set;
auxdisplay_is_busy_t is_busy;
auxdisplay_custom_character_set_t custom_character_set;
auxdisplay_write_t write;
auxdisplay_custom_command_t custom_command;
};
/**
* @endcond
*/
/**
* @brief Turn display on.
*
* @param dev Auxiliary display device instance
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_display_on(const struct device *dev);
static inline int z_impl_auxdisplay_display_on(const struct device *dev)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->display_on) {
return -ENOSYS;
}
return api->display_on(dev);
}
/**
* @brief Turn display off.
*
* @param dev Auxiliary display device instance
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_display_off(const struct device *dev);
static inline int z_impl_auxdisplay_display_off(const struct device *dev)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->display_off) {
return -ENOSYS;
}
return api->display_off(dev);
}
/**
* @brief Set cursor enabled status on an auxiliary display
*
* @param dev Auxiliary display device instance
* @param enabled True to enable cursor, false to disable
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_cursor_set_enabled(const struct device *dev,
bool enabled);
static inline int z_impl_auxdisplay_cursor_set_enabled(const struct device *dev,
bool enabled)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->cursor_set_enabled) {
return -ENOSYS;
}
return api->cursor_set_enabled(dev, enabled);
}
/**
* @brief Set cursor blinking status on an auxiliary display
*
* @param dev Auxiliary display device instance
* @param enabled Set to true to enable blinking position, false to disable
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_position_blinking_set_enabled(const struct device *dev,
bool enabled);
static inline int z_impl_auxdisplay_position_blinking_set_enabled(const struct device *dev,
bool enabled)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->position_blinking_set_enabled) {
return -ENOSYS;
}
return api->position_blinking_set_enabled(dev, enabled);
}
/**
* @brief Set cursor shift after character write and display shift
*
* @param dev Auxiliary display device instance
* @param direction Sets the direction of the display when characters are written
* @param display_shift If true, will shift the display when characters are written
* (which makes it look like the display is moving, not the cursor)
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -EINVAL if provided argument is invalid.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_cursor_shift_set(const struct device *dev,
uint8_t direction, bool display_shift);
static inline int z_impl_auxdisplay_cursor_shift_set(const struct device *dev,
uint8_t direction,
bool display_shift)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->cursor_shift_set) {
return -ENOSYS;
}
if (direction >= AUXDISPLAY_DIRECTION_COUNT) {
return -EINVAL;
}
return api->cursor_shift_set(dev, direction, display_shift);
}
/**
* @brief Set cursor (and write position) on an auxiliary display
*
* @param dev Auxiliary display device instance
* @param type Type of move, absolute or offset
* @param x Exact or offset X position
* @param y Exact or offset Y position
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -EINVAL if provided argument is invalid.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_cursor_position_set(const struct device *dev,
enum auxdisplay_position type,
int16_t x, int16_t y);
static inline int z_impl_auxdisplay_cursor_position_set(const struct device *dev,
enum auxdisplay_position type,
int16_t x, int16_t y)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->cursor_position_set) {
return -ENOSYS;
} else if (type >= AUXDISPLAY_POSITION_COUNT) {
return -EINVAL;
} else if (type == AUXDISPLAY_POSITION_ABSOLUTE && (x < 0 || y < 0)) {
return -EINVAL;
}
return api->cursor_position_set(dev, type, x, y);
}
/**
* @brief Get current cursor on an auxiliary display
*
* @param dev Auxiliary display device instance
* @param x Will be updated with the exact X position
* @param y Will be updated with the exact Y position
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -EINVAL if provided argument is invalid.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_cursor_position_get(const struct device *dev,
int16_t *x, int16_t *y);
static inline int z_impl_auxdisplay_cursor_position_get(const struct device *dev,
int16_t *x, int16_t *y)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->cursor_position_get) {
return -ENOSYS;
}
return api->cursor_position_get(dev, x, y);
}
/**
* @brief Set display position on an auxiliary display
*
* @param dev Auxiliary display device instance
* @param type Type of move, absolute or offset
* @param x Exact or offset X position
* @param y Exact or offset Y position
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -EINVAL if provided argument is invalid.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_display_position_set(const struct device *dev,
enum auxdisplay_position type,
int16_t x, int16_t y);
static inline int z_impl_auxdisplay_display_position_set(const struct device *dev,
enum auxdisplay_position type,
int16_t x, int16_t y)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->display_position_set) {
return -ENOSYS;
} else if (type >= AUXDISPLAY_POSITION_COUNT) {
return -EINVAL;
} else if (type == AUXDISPLAY_POSITION_ABSOLUTE && (x < 0 || y < 0)) {
return -EINVAL;
}
return api->display_position_set(dev, type, x, y);
}
/**
* @brief Get current display position on an auxiliary display
*
* @param dev Auxiliary display device instance
* @param x Will be updated with the exact X position
* @param y Will be updated with the exact Y position
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -EINVAL if provided argument is invalid.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_display_position_get(const struct device *dev,
int16_t *x, int16_t *y);
static inline int z_impl_auxdisplay_display_position_get(const struct device *dev,
int16_t *x, int16_t *y)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->display_position_get) {
return -ENOSYS;
}
return api->display_position_get(dev, x, y);
}
/**
* @brief Fetch capabilities (and details) of auxiliary display
*
* @param dev Auxiliary display device instance
* @param capabilities Will be updated with the details of the auxiliary display
*
* @retval 0 on success.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_capabilities_get(const struct device *dev,
struct auxdisplay_capabilities *capabilities);
static inline int z_impl_auxdisplay_capabilities_get(const struct device *dev,
struct auxdisplay_capabilities *capabilities)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
return api->capabilities_get(dev, capabilities);
}
/**
* @brief Clear display of auxiliary display and return to home position (note that
* this does not reset the display configuration, e.g. custom characters and
* display mode will persist).
*
* @param dev Auxiliary display device instance
*
* @retval 0 on success.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_clear(const struct device *dev);
static inline int z_impl_auxdisplay_clear(const struct device *dev)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
return api->clear(dev);
}
/**
* @brief Get the current brightness level of an auxiliary display
*
* @param dev Auxiliary display device instance
* @param brightness Will be updated with the current brightness
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_brightness_get(const struct device *dev,
uint8_t *brightness);
static inline int z_impl_auxdisplay_brightness_get(const struct device *dev,
uint8_t *brightness)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->brightness_get) {
return -ENOSYS;
}
return api->brightness_get(dev, brightness);
}
/**
* @brief Update the brightness level of an auxiliary display
*
* @param dev Auxiliary display device instance
* @param brightness The brightness level to set
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -EINVAL if provided argument is invalid.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_brightness_set(const struct device *dev,
uint8_t brightness);
static inline int z_impl_auxdisplay_brightness_set(const struct device *dev,
uint8_t brightness)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->brightness_set) {
return -ENOSYS;
}
return api->brightness_set(dev, brightness);
}
/**
* @brief Get the backlight level details of an auxiliary display
*
* @param dev Auxiliary display device instance
* @param backlight Will be updated with the current backlight level
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_backlight_get(const struct device *dev,
uint8_t *backlight);
static inline int z_impl_auxdisplay_backlight_get(const struct device *dev,
uint8_t *backlight)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->backlight_get) {
return -ENOSYS;
}
return api->backlight_get(dev, backlight);
}
/**
* @brief Update the backlight level of an auxiliary display
*
* @param dev Auxiliary display device instance
* @param backlight The backlight level to set
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -EINVAL if provided argument is invalid.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_backlight_set(const struct device *dev,
uint8_t backlight);
static inline int z_impl_auxdisplay_backlight_set(const struct device *dev,
uint8_t backlight)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->backlight_set) {
return -ENOSYS;
}
return api->backlight_set(dev, backlight);
}
/**
* @brief Check if an auxiliary display driver is busy
*
* @param dev Auxiliary display device instance
*
* @retval 1 on success and display busy.
* @retval 0 on success and display not busy.
* @retval -ENOSYS if not supported/implemented.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_is_busy(const struct device *dev);
static inline int z_impl_auxdisplay_is_busy(const struct device *dev)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->is_busy) {
return -ENOSYS;
}
return api->is_busy(dev);
}
/**
* @brief Sets a custom character in the display, the custom character struct
* must contain the pixel data for the custom character to add and valid
* custom character index, if successful then the character_code variable
* in the struct will be set to the character code that can be used with
* the auxdisplay_write() function to show it.
*
* A character must be valid for a display consisting of a uint8 array of
* size character width by character height, values should be 0x00 for
* pixel off or 0xff for pixel on, if a display supports shades then
* values between 0x00 and 0xff may be used (display driver dependent).
*
* @param dev Auxiliary display device instance
* @param character Pointer to custom character structure
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -EINVAL if provided argument is invalid.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_custom_character_set(const struct device *dev,
struct auxdisplay_character *character);
static inline int z_impl_auxdisplay_custom_character_set(const struct device *dev,
struct auxdisplay_character *character)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->custom_character_set) {
return -ENOSYS;
}
return api->custom_character_set(dev, character);
}
/**
* @brief Write data to auxiliary display screen at current position
*
* @param dev Auxiliary display device instance
* @param data Text data to write
* @param len Length of text data to write
*
* @retval 0 on success.
* @retval -EINVAL if provided argument is invalid.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_write(const struct device *dev, const uint8_t *data,
uint16_t len);
static inline int z_impl_auxdisplay_write(const struct device *dev,
const uint8_t *data, uint16_t len)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
return api->write(dev, data, len);
}
/**
* @brief Send a custom command to the display (if supported by driver)
*
* @param dev Auxiliary display device instance
* @param data Custom command structure (this may be extended by specific drivers)
*
* @retval 0 on success.
* @retval -ENOSYS if not supported/implemented.
* @retval -EINVAL if provided argument is invalid.
* @retval -errno Negative errno code on other failure.
*/
__syscall int auxdisplay_custom_command(const struct device *dev,
struct auxdisplay_custom_data *data);
static inline int z_impl_auxdisplay_custom_command(const struct device *dev,
struct auxdisplay_custom_data *data)
{
struct auxdisplay_driver_api *api = (struct auxdisplay_driver_api *)dev->api;
if (!api->custom_command) {
return -ENOSYS;
}
return api->custom_command(dev, data);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/auxdisplay.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_AUXDISPLAY_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/auxdisplay.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 5,898 |
```objective-c
/*
*
* Heavily based on drivers/flash.h which is:
*
*/
/**
* @file
* @brief Public API for EEPROM drivers
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_EEPROM_H_
#define ZEPHYR_INCLUDE_DRIVERS_EEPROM_H_
/**
* @brief EEPROM Interface
* @defgroup eeprom_interface EEPROM Interface
* @since 2.1
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <zephyr/types.h>
#include <stddef.h>
#include <sys/types.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @cond INTERNAL_HIDDEN
*
* For internal driver use only, skip these in public documentation.
*/
/**
* @brief Callback API upon reading from the EEPROM.
* See @a eeprom_read() for argument description
*/
typedef int (*eeprom_api_read)(const struct device *dev, off_t offset,
void *data,
size_t len);
/**
* @brief Callback API upon writing to the EEPROM.
* See @a eeprom_write() for argument description
*/
typedef int (*eeprom_api_write)(const struct device *dev, off_t offset,
const void *data, size_t len);
/**
* @brief Callback API upon getting the EEPROM size.
* See @a eeprom_get_size() for argument description
*/
typedef size_t (*eeprom_api_size)(const struct device *dev);
__subsystem struct eeprom_driver_api {
eeprom_api_read read;
eeprom_api_write write;
eeprom_api_size size;
};
/** @endcond */
/**
* @brief Read data from EEPROM
*
* @param dev EEPROM device
* @param offset Address offset to read from.
* @param data Buffer to store read data.
* @param len Number of bytes to read.
*
* @return 0 on success, negative errno code on failure.
*/
__syscall int eeprom_read(const struct device *dev, off_t offset, void *data,
size_t len);
static inline int z_impl_eeprom_read(const struct device *dev, off_t offset,
void *data, size_t len)
{
const struct eeprom_driver_api *api =
(const struct eeprom_driver_api *)dev->api;
return api->read(dev, offset, data, len);
}
/**
* @brief Write data to EEPROM
*
* @param dev EEPROM device
* @param offset Address offset to write data to.
* @param data Buffer with data to write.
* @param len Number of bytes to write.
*
* @return 0 on success, negative errno code on failure.
*/
__syscall int eeprom_write(const struct device *dev, off_t offset,
const void *data,
size_t len);
static inline int z_impl_eeprom_write(const struct device *dev, off_t offset,
const void *data, size_t len)
{
const struct eeprom_driver_api *api =
(const struct eeprom_driver_api *)dev->api;
return api->write(dev, offset, data, len);
}
/**
* @brief Get the size of the EEPROM in bytes
*
* @param dev EEPROM device.
*
* @return EEPROM size in bytes.
*/
__syscall size_t eeprom_get_size(const struct device *dev);
static inline size_t z_impl_eeprom_get_size(const struct device *dev)
{
const struct eeprom_driver_api *api =
(const struct eeprom_driver_api *)dev->api;
return api->size(dev);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/eeprom.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_EEPROM_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/eeprom.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 789 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public APIs for eSPI driver
*/
#ifndef ZEPHYR_INCLUDE_ESPI_H_
#define ZEPHYR_INCLUDE_ESPI_H_
#include <errno.h>
#include <zephyr/sys/__assert.h>
#include <zephyr/types.h>
#include <zephyr/device.h>
#include <zephyr/sys/slist.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief eSPI Driver APIs
* @defgroup espi_interface ESPI Driver APIs
* @ingroup io_interfaces
* @{
*/
/**
* @brief eSPI I/O mode capabilities
*/
enum espi_io_mode {
ESPI_IO_MODE_SINGLE_LINE = BIT(0),
ESPI_IO_MODE_DUAL_LINES = BIT(1),
ESPI_IO_MODE_QUAD_LINES = BIT(2),
};
/**
* @code
*+your_sha256_hash------+
*| |
*| eSPI controller +-------------+ |
*| +-----------+ | Power | +----------+ |
*| |Out of band| | management | | GPIO | |
*| +------------+ |processor | | controller | | sources | |
*| | SPI flash | +-----------+ +-------------+ +----------+ |
*| | controller | | | | |
*| +------------+ | | | |
*| | | | +--------+ +---------------+ |
*| | | | | | |
*| | | +-----+ +--------+ +----------+ +----v-----+ |
*| | | | | LPC | | Tunneled | | Tunneled | |
*| | | | | bridge | | SMBus | | GPIO | |
*| | | | +--------+ +----------+ +----------+ |
*| | | | | | | |
*| | | | ------+ | | |
*| | | | | | | |
*| | | +------v-----+ +---v-------v-------------v----+ |
*| | | | eSPI Flash | | eSPI protocol block | |
*| | | | access +--->+ | |
*| | | +------------+ +------------------------------+ |
*| | | | |
*| | +-----------+ | |
*| | v v |
*| | XXXXXXXXXXXXXXXXXXXXXXX |
*| | XXXXXXXXXXXXXXXXXXXXX |
*| | XXXXXXXXXXXXXXXXXXX |
*+your_sha256_hash------+
* | |
* v +-----------------+
* +---------+ | | | | | |
* | Flash | | | | | | |
* +---------+ | + + + + | eSPI bus
* | CH0 CH1 CH2 CH3 | (logical channels)
* | + + + + |
* | | | | | |
* +-----------------+
* |
*+your_sha256_hash-------+
*| eSPI target |
*| |
*| CH0 | CH1 | CH2 | CH3 |
*| eSPI endpoint | VWIRE | OOB | Flash |
*+your_sha256_hash-------+
* @endcode
*/
/**
* @brief eSPI channel.
*
* Identifies each eSPI logical channel supported by eSPI controller
* Each channel allows independent traffic, but the assignment of channel
* type to channel number is fixed.
*
* Note that generic commands are not associated with any channel, so traffic
* over eSPI can occur if all channels are disabled or not ready
*/
enum espi_channel {
ESPI_CHANNEL_PERIPHERAL = BIT(0),
ESPI_CHANNEL_VWIRE = BIT(1),
ESPI_CHANNEL_OOB = BIT(2),
ESPI_CHANNEL_FLASH = BIT(3),
};
/**
* @brief eSPI bus event.
*
* eSPI bus event to indicate events for which user can register callbacks
*/
enum espi_bus_event {
/** Indicates the eSPI bus was reset either via eSPI reset pin.
* eSPI drivers should convey the eSPI reset status to eSPI driver clients
* following eSPI specification reset pin convention:
* 0-eSPI bus in reset, 1-eSPI bus out-of-reset
*
* Note: There is no need to send this callback for in-band reset.
*/
ESPI_BUS_RESET = BIT(0),
/** Indicates the eSPI HW has received channel enable notification from eSPI host,
* once the eSPI channel is signal as ready to the eSPI host,
* eSPI drivers should convey the eSPI channel ready to eSPI driver client via this event.
*/
ESPI_BUS_EVENT_CHANNEL_READY = BIT(1),
/** Indicates the eSPI HW has received a virtual wire message from eSPI host.
* eSPI drivers should convey the eSPI virtual wire latest status.
*/
ESPI_BUS_EVENT_VWIRE_RECEIVED = BIT(2),
/** Indicates the eSPI HW has received a Out-of-band package from eSPI host.
*/
ESPI_BUS_EVENT_OOB_RECEIVED = BIT(3),
/** Indicates the eSPI HW has received a peripheral eSPI host event.
* eSPI drivers should convey the peripheral type.
*/
ESPI_BUS_PERIPHERAL_NOTIFICATION = BIT(4),
ESPI_BUS_TAF_NOTIFICATION = BIT(5),
};
/**
* @brief eSPI peripheral channel events.
*
* eSPI peripheral channel event types to indicate users.
*/
enum espi_pc_event {
ESPI_PC_EVT_BUS_CHANNEL_READY = BIT(0),
ESPI_PC_EVT_BUS_MASTER_ENABLE = BIT(1),
};
/**
* @cond INTERNAL_HIDDEN
*
*/
#define ESPI_PERIPHERAL_INDEX_0 0ul
#define ESPI_PERIPHERAL_INDEX_1 1ul
#define ESPI_PERIPHERAL_INDEX_2 2ul
#define ESPI_TARGET_TO_CONTROLLER 0ul
#define ESPI_CONTROLLER_TO_TARGET 1ul
#define ESPI_VWIRE_SRC_ID0 0ul
#define ESPI_VWIRE_SRC_ID1 1ul
#define ESPI_VWIRE_SRC_ID2 2ul
#define ESPI_VWIRE_SRC_ID3 3ul
#define ESPI_VWIRE_SRC_ID_MAX 4ul
#define ESPI_PERIPHERAL_NODATA 0ul
#define E8042_START_OPCODE 0x50
#define E8042_MAX_OPCODE 0x5F
#define EACPI_START_OPCODE 0x60
#define EACPI_MAX_OPCODE 0x6F
#define ECUSTOM_START_OPCODE 0xF0
#define ECUSTOM_MAX_OPCODE 0xFF
/** @endcond */
/**
* @brief eSPI peripheral notification type.
*
* eSPI peripheral notification event details to indicate which peripheral
* trigger the eSPI callback
*/
enum espi_virtual_peripheral {
ESPI_PERIPHERAL_UART,
ESPI_PERIPHERAL_8042_KBC,
ESPI_PERIPHERAL_HOST_IO,
ESPI_PERIPHERAL_DEBUG_PORT80,
ESPI_PERIPHERAL_HOST_IO_PVT,
#if defined(CONFIG_ESPI_PERIPHERAL_EC_HOST_CMD)
ESPI_PERIPHERAL_EC_HOST_CMD,
#endif /* CONFIG_ESPI_PERIPHERAL_EC_HOST_CMD */
};
/**
* @brief eSPI cycle types supported over eSPI peripheral channel
*/
enum espi_cycle_type {
ESPI_CYCLE_MEMORY_READ32,
ESPI_CYCLE_MEMORY_READ64,
ESPI_CYCLE_MEMORY_WRITE32,
ESPI_CYCLE_MEMORY_WRITE64,
ESPI_CYCLE_MESSAGE_NODATA,
ESPI_CYCLE_MESSAGE_DATA,
ESPI_CYCLE_OK_COMPLETION_NODATA,
ESPI_CYCLE_OKCOMPLETION_DATA,
ESPI_CYCLE_NOK_COMPLETION_NODATA,
};
/**
* @brief eSPI system platform signals that can be send or receive through
* virtual wire channel
*/
enum espi_vwire_signal {
/* Virtual wires that can only be send from controller to target */
ESPI_VWIRE_SIGNAL_SLP_S3,
ESPI_VWIRE_SIGNAL_SLP_S4,
ESPI_VWIRE_SIGNAL_SLP_S5,
ESPI_VWIRE_SIGNAL_OOB_RST_WARN,
ESPI_VWIRE_SIGNAL_PLTRST,
ESPI_VWIRE_SIGNAL_SUS_STAT,
ESPI_VWIRE_SIGNAL_NMIOUT,
ESPI_VWIRE_SIGNAL_SMIOUT,
ESPI_VWIRE_SIGNAL_HOST_RST_WARN,
ESPI_VWIRE_SIGNAL_SLP_A,
ESPI_VWIRE_SIGNAL_SUS_PWRDN_ACK,
ESPI_VWIRE_SIGNAL_SUS_WARN,
ESPI_VWIRE_SIGNAL_SLP_WLAN,
ESPI_VWIRE_SIGNAL_SLP_LAN,
ESPI_VWIRE_SIGNAL_HOST_C10,
ESPI_VWIRE_SIGNAL_DNX_WARN,
/* Virtual wires that can only be sent from target to controller */
ESPI_VWIRE_SIGNAL_PME,
ESPI_VWIRE_SIGNAL_WAKE,
ESPI_VWIRE_SIGNAL_OOB_RST_ACK,
ESPI_VWIRE_SIGNAL_TARGET_BOOT_STS,
ESPI_VWIRE_SIGNAL_ERR_NON_FATAL,
ESPI_VWIRE_SIGNAL_ERR_FATAL,
ESPI_VWIRE_SIGNAL_TARGET_BOOT_DONE,
ESPI_VWIRE_SIGNAL_HOST_RST_ACK,
ESPI_VWIRE_SIGNAL_RST_CPU_INIT,
/* System management interrupt */
ESPI_VWIRE_SIGNAL_SMI,
/* System control interrupt */
ESPI_VWIRE_SIGNAL_SCI,
ESPI_VWIRE_SIGNAL_DNX_ACK,
ESPI_VWIRE_SIGNAL_SUS_ACK,
/*
* Virtual wire GPIOs that can be sent from target to controller for
* platform specific usage.
*/
ESPI_VWIRE_SIGNAL_TARGET_GPIO_0,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_1,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_2,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_3,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_4,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_5,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_6,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_7,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_8,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_9,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_10,
ESPI_VWIRE_SIGNAL_TARGET_GPIO_11,
/* Number of Virtual Wires */
ESPI_VWIRE_SIGNAL_COUNT
};
/* USB-C port over current */
#define ESPI_VWIRE_SIGNAL_OCB_0 ESPI_VWIRE_SIGNAL_TARGET_GPIO_0
#define ESPI_VWIRE_SIGNAL_OCB_1 ESPI_VWIRE_SIGNAL_TARGET_GPIO_1
#define ESPI_VWIRE_SIGNAL_OCB_2 ESPI_VWIRE_SIGNAL_TARGET_GPIO_2
#define ESPI_VWIRE_SIGNAL_OCB_3 ESPI_VWIRE_SIGNAL_TARGET_GPIO_3
/* eSPI LPC peripherals. */
enum lpc_peripheral_opcode {
/* Read transactions */
E8042_OBF_HAS_CHAR = 0x50,
E8042_IBF_HAS_CHAR,
/* Write transactions */
E8042_WRITE_KB_CHAR,
E8042_WRITE_MB_CHAR,
/* Write transactions without input parameters */
E8042_RESUME_IRQ,
E8042_PAUSE_IRQ,
E8042_CLEAR_OBF,
/* Status transactions */
E8042_READ_KB_STS,
E8042_SET_FLAG,
E8042_CLEAR_FLAG,
/* ACPI read transactions */
EACPI_OBF_HAS_CHAR = EACPI_START_OPCODE,
EACPI_IBF_HAS_CHAR,
/* ACPI write transactions */
EACPI_WRITE_CHAR,
/* ACPI status transactions */
EACPI_READ_STS,
EACPI_WRITE_STS,
#if defined(CONFIG_ESPI_PERIPHERAL_ACPI_SHM_REGION)
/* Shared memory region support to return the ACPI response data */
EACPI_GET_SHARED_MEMORY,
#endif /* CONFIG_ESPI_PERIPHERAL_ACPI_SHM_REGION */
#if defined(CONFIG_ESPI_PERIPHERAL_CUSTOM_OPCODE)
/* Other customized transactions */
ECUSTOM_HOST_SUBS_INTERRUPT_EN = ECUSTOM_START_OPCODE,
ECUSTOM_HOST_CMD_GET_PARAM_MEMORY,
ECUSTOM_HOST_CMD_GET_PARAM_MEMORY_SIZE,
ECUSTOM_HOST_CMD_SEND_RESULT,
#endif /* CONFIG_ESPI_PERIPHERAL_CUSTOM_OPCODE */
};
/* KBC 8042 event: Input Buffer Full */
#define HOST_KBC_EVT_IBF BIT(0)
/* KBC 8042 event: Output Buffer Empty */
#define HOST_KBC_EVT_OBE BIT(1)
/**
* @brief Bit field definition of evt_data in struct espi_event for KBC.
*/
struct espi_evt_data_kbc {
uint32_t type:8;
uint32_t data:8;
uint32_t evt:8;
uint32_t reserved:8;
};
/**
* @brief Bit field definition of evt_data in struct espi_event for ACPI.
*/
struct espi_evt_data_acpi {
uint32_t type:8;
uint32_t data:8;
uint32_t reserved:16;
};
/**
* @brief eSPI event
*/
struct espi_event {
/** Event type */
enum espi_bus_event evt_type;
/** Additional details for bus event type */
uint32_t evt_details;
/** Data associated to the event */
uint32_t evt_data;
};
/**
* @brief eSPI bus configuration parameters
*/
struct espi_cfg {
/** Supported I/O mode */
enum espi_io_mode io_caps;
/** Supported channels */
enum espi_channel channel_caps;
/** Maximum supported frequency in MHz */
uint8_t max_freq;
};
/**
* @brief eSPI peripheral request packet format
*/
struct espi_request_packet {
enum espi_cycle_type cycle_type;
uint8_t tag;
uint16_t len;
uint32_t address;
uint8_t *data;
};
/**
* @brief eSPI out-of-band transaction packet format
*
* For Tx packet, eSPI driver client shall specify the OOB payload data and its length in bytes.
* For Rx packet, eSPI driver client shall indicate the maximum number of bytes that can receive,
* while the eSPI driver should update the length field with the actual data received/available.
*
* In all cases, the length does not include OOB header size 3 bytes.
*/
struct espi_oob_packet {
uint8_t *buf;
uint16_t len;
};
/**
* @brief eSPI flash transactions packet format
*/
struct espi_flash_packet {
uint8_t *buf;
uint32_t flash_addr;
uint16_t len;
};
struct espi_callback;
/**
* @typedef espi_callback_handler_t
* @brief Define the application callback handler function signature.
*
* @param dev Device struct for the eSPI device.
* @param cb Original struct espi_callback owning this handler.
* @param espi_evt event details that trigger the callback handler.
*
*/
typedef void (*espi_callback_handler_t) (const struct device *dev,
struct espi_callback *cb,
struct espi_event espi_evt);
/**
* @cond INTERNAL_HIDDEN
*
* Used to register a callback in the driver instance callback list.
* As many callbacks as needed can be added as long as each of them
* are unique pointers of struct espi_callback.
* Beware such structure should not be allocated on stack.
*
* Note: To help setting it, see espi_init_callback() below
*/
struct espi_callback {
/** This is meant to be used in the driver only */
sys_snode_t node;
/** Actual callback function being called when relevant */
espi_callback_handler_t handler;
/** An event which user is interested in, if 0 the callback
* will never be called. Such evt_mask can be modified whenever
* necessary by the owner, and thus will affect the handler being
* called or not.
*/
enum espi_bus_event evt_type;
};
/** @endcond */
/**
* @cond INTERNAL_HIDDEN
*
* eSPI driver API definition and system call entry points
*
* (Internal use only.)
*/
typedef int (*espi_api_config)(const struct device *dev, struct espi_cfg *cfg);
typedef bool (*espi_api_get_channel_status)(const struct device *dev,
enum espi_channel ch);
/* Logical Channel 0 APIs */
typedef int (*espi_api_read_request)(const struct device *dev,
struct espi_request_packet *req);
typedef int (*espi_api_write_request)(const struct device *dev,
struct espi_request_packet *req);
typedef int (*espi_api_lpc_read_request)(const struct device *dev,
enum lpc_peripheral_opcode op,
uint32_t *data);
typedef int (*espi_api_lpc_write_request)(const struct device *dev,
enum lpc_peripheral_opcode op,
uint32_t *data);
/* Logical Channel 1 APIs */
typedef int (*espi_api_send_vwire)(const struct device *dev,
enum espi_vwire_signal vw,
uint8_t level);
typedef int (*espi_api_receive_vwire)(const struct device *dev,
enum espi_vwire_signal vw,
uint8_t *level);
/* Logical Channel 2 APIs */
typedef int (*espi_api_send_oob)(const struct device *dev,
struct espi_oob_packet *pckt);
typedef int (*espi_api_receive_oob)(const struct device *dev,
struct espi_oob_packet *pckt);
/* Logical Channel 3 APIs */
typedef int (*espi_api_flash_read)(const struct device *dev,
struct espi_flash_packet *pckt);
typedef int (*espi_api_flash_write)(const struct device *dev,
struct espi_flash_packet *pckt);
typedef int (*espi_api_flash_erase)(const struct device *dev,
struct espi_flash_packet *pckt);
/* Callbacks and traffic intercept */
typedef int (*espi_api_manage_callback)(const struct device *dev,
struct espi_callback *callback,
bool set);
__subsystem struct espi_driver_api {
espi_api_config config;
espi_api_get_channel_status get_channel_status;
espi_api_read_request read_request;
espi_api_write_request write_request;
espi_api_lpc_read_request read_lpc_request;
espi_api_lpc_write_request write_lpc_request;
espi_api_send_vwire send_vwire;
espi_api_receive_vwire receive_vwire;
espi_api_send_oob send_oob;
espi_api_receive_oob receive_oob;
espi_api_flash_read flash_read;
espi_api_flash_write flash_write;
espi_api_flash_erase flash_erase;
espi_api_manage_callback manage_callback;
};
/**
* @endcond
*/
/**
* @brief Configure operation of a eSPI controller.
*
* This routine provides a generic interface to override eSPI controller
* capabilities.
*
* If this eSPI controller is acting as target, the values set here
* will be discovered as part through the GET_CONFIGURATION command
* issued by the eSPI controller during initialization.
*
* If this eSPI controller is acting as controller, the values set here
* will be used by eSPI controller to determine minimum common capabilities with
* eSPI target then send via SET_CONFIGURATION command.
*
* @code
* +---------+ +---------+ +------+ +---------+ +---------+
* | eSPI | | eSPI | | eSPI | | eSPI | | eSPI |
* | target | | driver | | bus | | driver | | host |
* +--------+ +---------+ +------+ +---------+ +---------+
* | | | | |
* | espi_config | Set eSPI | Set eSPI | espi_config |
* +--------------+ ctrl regs | cap ctrl reg| +-----------+
* | +-------+ | +--------+ |
* | |<------+ | +------->| |
* | | | | |
* | | | | |
* | | | GET_CONFIGURATION | |
* | | +<------------------+ |
* | |<-----------| | |
* | | eSPI caps | | |
* | |----------->+ response | |
* | | |------------------>+ |
* | | | | |
* | | | SET_CONFIGURATION | |
* | | +<------------------+ |
* | | | accept | |
* | | +------------------>+ |
* + + + + +
* @endcode
*
* @param dev Pointer to the device structure for the driver instance.
* @param cfg the device runtime configuration for the eSPI controller.
*
* @retval 0 If successful.
* @retval -EIO General input / output error, failed to configure device.
* @retval -EINVAL invalid capabilities, failed to configure device.
* @retval -ENOTSUP capability not supported by eSPI target.
*/
__syscall int espi_config(const struct device *dev, struct espi_cfg *cfg);
static inline int z_impl_espi_config(const struct device *dev,
struct espi_cfg *cfg)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
return api->config(dev, cfg);
}
/**
* @brief Query to see if it a channel is ready.
*
* This routine allows to check if logical channel is ready before use.
* Note that queries for channels not supported will always return false.
*
* @param dev Pointer to the device structure for the driver instance.
* @param ch the eSPI channel for which status is to be retrieved.
*
* @retval true If eSPI channel is ready.
* @retval false otherwise.
*/
__syscall bool espi_get_channel_status(const struct device *dev,
enum espi_channel ch);
static inline bool z_impl_espi_get_channel_status(const struct device *dev,
enum espi_channel ch)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
return api->get_channel_status(dev, ch);
}
/**
* @brief Sends memory, I/O or message read request over eSPI.
*
* This routines provides a generic interface to send a read request packet.
*
* @param dev Pointer to the device structure for the driver instance.
* @param req Address of structure representing a memory,
* I/O or message read request.
*
* @retval 0 If successful.
* @retval -ENOTSUP if eSPI controller doesn't support raw packets and instead
* low memory transactions are handled by controller hardware directly.
* @retval -EIO General input / output error, failed to send over the bus.
*/
__syscall int espi_read_request(const struct device *dev,
struct espi_request_packet *req);
static inline int z_impl_espi_read_request(const struct device *dev,
struct espi_request_packet *req)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->read_request) {
return -ENOTSUP;
}
return api->read_request(dev, req);
}
/**
* @brief Sends memory, I/O or message write request over eSPI.
*
* This routines provides a generic interface to send a write request packet.
*
* @param dev Pointer to the device structure for the driver instance.
* @param req Address of structure representing a memory, I/O or
* message write request.
*
* @retval 0 If successful.
* @retval -ENOTSUP if eSPI controller doesn't support raw packets and instead
* low memory transactions are handled by controller hardware directly.
* @retval -EINVAL General input / output error, failed to send over the bus.
*/
__syscall int espi_write_request(const struct device *dev,
struct espi_request_packet *req);
static inline int z_impl_espi_write_request(const struct device *dev,
struct espi_request_packet *req)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->write_request) {
return -ENOTSUP;
}
return api->write_request(dev, req);
}
/**
* @brief Reads SOC data from a LPC peripheral with information
* updated over eSPI.
*
* This routine provides a generic interface to read a block whose
* information was updated by an eSPI transaction. Reading may trigger
* a transaction. The eSPI packet is assembled by the HW block.
*
* @param dev Pointer to the device structure for the driver instance.
* @param op Enum representing opcode for peripheral type and read request.
* @param data Parameter to be read from to the LPC peripheral.
*
* @retval 0 If successful.
* @retval -ENOTSUP if eSPI peripheral is off or not supported.
* @retval -EINVAL for unimplemented lpc opcode, but in range.
*/
__syscall int espi_read_lpc_request(const struct device *dev,
enum lpc_peripheral_opcode op,
uint32_t *data);
static inline int z_impl_espi_read_lpc_request(const struct device *dev,
enum lpc_peripheral_opcode op,
uint32_t *data)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->read_lpc_request) {
return -ENOTSUP;
}
return api->read_lpc_request(dev, op, data);
}
/**
* @brief Writes data to a LPC peripheral which generates an eSPI transaction.
*
* This routine provides a generic interface to write data to a block which
* triggers an eSPI transaction. The eSPI packet is assembled by the HW
* block.
*
* @param dev Pointer to the device structure for the driver instance.
* @param op Enum representing an opcode for peripheral type and write request.
* @param data Represents the parameter passed to the LPC peripheral.
*
* @retval 0 If successful.
* @retval -ENOTSUP if eSPI peripheral is off or not supported.
* @retval -EINVAL for unimplemented lpc opcode, but in range.
*/
__syscall int espi_write_lpc_request(const struct device *dev,
enum lpc_peripheral_opcode op,
uint32_t *data);
static inline int z_impl_espi_write_lpc_request(const struct device *dev,
enum lpc_peripheral_opcode op,
uint32_t *data)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->write_lpc_request) {
return -ENOTSUP;
}
return api->write_lpc_request(dev, op, data);
}
/**
* @brief Sends system/platform signal as a virtual wire packet.
*
* This routines provides a generic interface to send a virtual wire packet
* from target to controller.
*
* @param dev Pointer to the device structure for the driver instance.
* @param signal The signal to be send to eSPI controller.
* @param level The level of signal requested LOW or HIGH.
*
* @retval 0 If successful.
* @retval -EIO General input / output error, failed to send over the bus.
*/
__syscall int espi_send_vwire(const struct device *dev,
enum espi_vwire_signal signal,
uint8_t level);
static inline int z_impl_espi_send_vwire(const struct device *dev,
enum espi_vwire_signal signal,
uint8_t level)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
return api->send_vwire(dev, signal, level);
}
/**
* @brief Retrieves level status for a signal encapsulated in a virtual wire.
*
* This routines provides a generic interface to request a virtual wire packet
* from eSPI controller and retrieve the signal level.
*
* @param dev Pointer to the device structure for the driver instance.
* @param signal the signal to be requested from eSPI controller.
* @param level the level of signal requested 0b LOW, 1b HIGH.
*
* @retval -EIO General input / output error, failed request to controller.
*/
__syscall int espi_receive_vwire(const struct device *dev,
enum espi_vwire_signal signal,
uint8_t *level);
static inline int z_impl_espi_receive_vwire(const struct device *dev,
enum espi_vwire_signal signal,
uint8_t *level)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
return api->receive_vwire(dev, signal, level);
}
/**
* @brief Sends SMBus transaction (out-of-band) packet over eSPI bus.
*
* This routines provides an interface to encapsulate a SMBus transaction
* and send into packet over eSPI bus
*
* @param dev Pointer to the device structure for the driver instance.
* @param pckt Address of the packet representation of SMBus transaction.
*
* @retval -EIO General input / output error, failed request to controller.
*/
__syscall int espi_send_oob(const struct device *dev,
struct espi_oob_packet *pckt);
static inline int z_impl_espi_send_oob(const struct device *dev,
struct espi_oob_packet *pckt)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->send_oob) {
return -ENOTSUP;
}
return api->send_oob(dev, pckt);
}
/**
* @brief Receives SMBus transaction (out-of-band) packet from eSPI bus.
*
* This routines provides an interface to receive and decoded a SMBus
* transaction from eSPI bus
*
* @param dev Pointer to the device structure for the driver instance.
* @param pckt Address of the packet representation of SMBus transaction.
*
* @retval -EIO General input / output error, failed request to controller.
*/
__syscall int espi_receive_oob(const struct device *dev,
struct espi_oob_packet *pckt);
static inline int z_impl_espi_receive_oob(const struct device *dev,
struct espi_oob_packet *pckt)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->receive_oob) {
return -ENOTSUP;
}
return api->receive_oob(dev, pckt);
}
/**
* @brief Sends a read request packet for shared flash.
*
* This routines provides an interface to send a request to read the flash
* component shared between the eSPI controller and eSPI targets.
*
* @param dev Pointer to the device structure for the driver instance.
* @param pckt Address of the representation of read flash transaction.
*
* @retval -ENOTSUP eSPI flash logical channel transactions not supported.
* @retval -EBUSY eSPI flash channel is not ready or disabled by controller.
* @retval -EIO General input / output error, failed request to controller.
*/
__syscall int espi_read_flash(const struct device *dev,
struct espi_flash_packet *pckt);
static inline int z_impl_espi_read_flash(const struct device *dev,
struct espi_flash_packet *pckt)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->flash_read) {
return -ENOTSUP;
}
return api->flash_read(dev, pckt);
}
/**
* @brief Sends a write request packet for shared flash.
*
* This routines provides an interface to send a request to write to the flash
* components shared between the eSPI controller and eSPI targets.
*
* @param dev Pointer to the device structure for the driver instance.
* @param pckt Address of the representation of write flash transaction.
*
* @retval -ENOTSUP eSPI flash logical channel transactions not supported.
* @retval -EBUSY eSPI flash channel is not ready or disabled by controller.
* @retval -EIO General input / output error, failed request to controller.
*/
__syscall int espi_write_flash(const struct device *dev,
struct espi_flash_packet *pckt);
static inline int z_impl_espi_write_flash(const struct device *dev,
struct espi_flash_packet *pckt)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->flash_write) {
return -ENOTSUP;
}
return api->flash_write(dev, pckt);
}
/**
* @brief Sends a write request packet for shared flash.
*
* This routines provides an interface to send a request to write to the flash
* components shared between the eSPI controller and eSPI targets.
*
* @param dev Pointer to the device structure for the driver instance.
* @param pckt Address of the representation of write flash transaction.
*
* @retval -ENOTSUP eSPI flash logical channel transactions not supported.
* @retval -EBUSY eSPI flash channel is not ready or disabled by controller.
* @retval -EIO General input / output error, failed request to controller.
*/
__syscall int espi_flash_erase(const struct device *dev,
struct espi_flash_packet *pckt);
static inline int z_impl_espi_flash_erase(const struct device *dev,
struct espi_flash_packet *pckt)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->flash_erase) {
return -ENOTSUP;
}
return api->flash_erase(dev, pckt);
}
/**
* Callback model
*
* @code
*+-------+ +-------------+ +------+ +---------+
*| App | | eSPI driver | | HW | |eSPI Host|
*+---+---+ +-------+-----+ +---+--+ +----+----+
* | | | |
* | espi_init_callback | | |
* +----------------------------> | | |
* | espi_add_callback | |
* +----------------------------->+ |
* | | | eSPI reset | eSPI host
* | | IRQ +<------------+ resets the
* | | <-----------+ | bus
* |<-----------------------------| | |
* | Report eSPI bus reset | Processed | |
* | | within the | |
* | | driver | |
* | | | |
* | | | VW CH ready| eSPI host
* | | IRQ +<------------+ enables VW
* | | <-----------+ | channel
* | | | |
* | | Processed | |
* | | within the | |
* | | driver | |
* | | | |
* | | | Memory I/O | Peripheral
* | | <-------------+ event
* | +<------------+ |
* +<-----------------------------+ callback | |
* | Report peripheral event | | |
* | and data for the event | | |
* | | | |
* | | | SLP_S5 | eSPI host
* | | <-------------+ send VWire
* | +<------------+ |
* +<-----------------------------+ callback | |
* | App enables/configures | | |
* | discrete regulator | | |
* | | | |
* | espi_send_vwire_signal | | |
* +------------------------------>------------>|------------>|
* | | | |
* | | | HOST_RST | eSPI host
* | | <-------------+ send VWire
* | +<------------+ |
* +<-----------------------------+ callback | |
* | App reset host-related | | |
* | data structures | | |
* | | | |
* | | | C10 | eSPI host
* | | +<------------+ send VWire
* | <-------------+ |
* <------------------------------+ | |
* | App executes | | |
* + power mgmt policy | | |
* @endcode
*/
/**
* @brief Helper to initialize a struct espi_callback properly.
*
* @param callback A valid Application's callback structure pointer.
* @param handler A valid handler function pointer.
* @param evt_type indicates the eSPI event relevant for the handler.
* for VWIRE_RECEIVED event the data will indicate the new level asserted
*/
static inline void espi_init_callback(struct espi_callback *callback,
espi_callback_handler_t handler,
enum espi_bus_event evt_type)
{
__ASSERT(callback, "Callback pointer should not be NULL");
__ASSERT(handler, "Callback handler pointer should not be NULL");
callback->handler = handler;
callback->evt_type = evt_type;
}
/**
* @brief Add an application callback.
* @param dev Pointer to the device structure for the driver instance.
* @param callback A valid Application's callback structure pointer.
* @return 0 if successful, negative errno code on failure.
*
* @note Callbacks may be added to the device from within a callback
* handler invocation, but whether they are invoked for the current
* eSPI event is not specified.
*
* Note: enables to add as many callback as needed on the same device.
*/
static inline int espi_add_callback(const struct device *dev,
struct espi_callback *callback)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->manage_callback) {
return -ENOTSUP;
}
return api->manage_callback(dev, callback, true);
}
/**
* @brief Remove an application callback.
* @param dev Pointer to the device structure for the driver instance.
* @param callback A valid application's callback structure pointer.
* @return 0 if successful, negative errno code on failure.
*
* @warning It is explicitly permitted, within a callback handler, to
* remove the registration for the callback that is running, i.e. @p
* callback. Attempts to remove other registrations on the same
* device may result in undefined behavior, including failure to
* invoke callbacks that remain registered and unintended invocation
* of removed callbacks.
*
* Note: enables to remove as many callbacks as added through
* espi_add_callback().
*/
static inline int espi_remove_callback(const struct device *dev,
struct espi_callback *callback)
{
const struct espi_driver_api *api =
(const struct espi_driver_api *)dev->api;
if (!api->manage_callback) {
return -ENOTSUP;
}
return api->manage_callback(dev, callback, false);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/espi.h>
#endif /* ZEPHYR_INCLUDE_ESPI_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/espi.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 8,651 |
```objective-c
/*
*
*/
/**
* @file gnss.h
* @brief Public GNSS API.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_GNSS_H_
#define ZEPHYR_INCLUDE_DRIVERS_GNSS_H_
/**
* @brief GNSS Interface
* @defgroup gnss_interface GNSS Interface
* @since 3.6
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#include <zephyr/types.h>
#include <zephyr/device.h>
#include <zephyr/data/navigation.h>
#include <errno.h>
#ifdef __cplusplus
extern "C" {
#endif
/** GNSS PPS modes */
enum gnss_pps_mode {
/** PPS output disabled */
GNSS_PPS_MODE_DISABLED = 0,
/** PPS output always enabled */
GNSS_PPS_MODE_ENABLED = 1,
/** PPS output enabled from first lock */
GNSS_PPS_MODE_ENABLED_AFTER_LOCK = 2,
/** PPS output enabled while locked */
GNSS_PPS_MODE_ENABLED_WHILE_LOCKED = 3
};
/** API for setting fix rate */
typedef int (*gnss_set_fix_rate_t)(const struct device *dev, uint32_t fix_interval_ms);
/** API for getting fix rate */
typedef int (*gnss_get_fix_rate_t)(const struct device *dev, uint32_t *fix_interval_ms);
/**
* @brief GNSS periodic tracking configuration
*
* @note Setting either active_time or inactive_time to 0 will disable periodic
* function.
*/
struct gnss_periodic_config {
/** The time the GNSS will spend in the active state in ms */
uint32_t active_time_ms;
/** The time the GNSS will spend in the inactive state in ms */
uint32_t inactive_time_ms;
};
/** API for setting periodic tracking configuration */
typedef int (*gnss_set_periodic_config_t)(const struct device *dev,
const struct gnss_periodic_config *periodic_config);
/** API for setting periodic tracking configuration */
typedef int (*gnss_get_periodic_config_t)(const struct device *dev,
struct gnss_periodic_config *periodic_config);
/** GNSS navigation modes */
enum gnss_navigation_mode {
/** Dynamics have no impact on tracking */
GNSS_NAVIGATION_MODE_ZERO_DYNAMICS = 0,
/** Low dynamics have higher impact on tracking */
GNSS_NAVIGATION_MODE_LOW_DYNAMICS = 1,
/** Low and high dynamics have equal impact on tracking */
GNSS_NAVIGATION_MODE_BALANCED_DYNAMICS = 2,
/** High dynamics have higher impact on tracking */
GNSS_NAVIGATION_MODE_HIGH_DYNAMICS = 3
};
/** API for setting navigation mode */
typedef int (*gnss_set_navigation_mode_t)(const struct device *dev,
enum gnss_navigation_mode mode);
/** API for getting navigation mode */
typedef int (*gnss_get_navigation_mode_t)(const struct device *dev,
enum gnss_navigation_mode *mode);
/** Systems contained in gnss_systems_t */
enum gnss_system {
/** Global Positioning System (GPS) */
GNSS_SYSTEM_GPS = BIT(0),
/** GLObal NAvigation Satellite System (GLONASS) */
GNSS_SYSTEM_GLONASS = BIT(1),
/** Galileo */
GNSS_SYSTEM_GALILEO = BIT(2),
/** BeiDou Navigation Satellite System */
GNSS_SYSTEM_BEIDOU = BIT(3),
/** Quasi-Zenith Satellite System (QZSS) */
GNSS_SYSTEM_QZSS = BIT(4),
/** Indian Regional Navigation Satellite System (IRNSS) */
GNSS_SYSTEM_IRNSS = BIT(5),
/** Satellite-Based Augmentation System (SBAS) */
GNSS_SYSTEM_SBAS = BIT(6),
/** Indoor Messaging System (IMES) */
GNSS_SYSTEM_IMES = BIT(7),
};
/** Type storing bitmask of GNSS systems */
typedef uint32_t gnss_systems_t;
/** API for enabling systems */
typedef int (*gnss_set_enabled_systems_t)(const struct device *dev, gnss_systems_t systems);
/** API for getting enabled systems */
typedef int (*gnss_get_enabled_systems_t)(const struct device *dev, gnss_systems_t *systems);
/** API for getting enabled systems */
typedef int (*gnss_get_supported_systems_t)(const struct device *dev, gnss_systems_t *systems);
/** GNSS fix status */
enum gnss_fix_status {
/** No GNSS fix acquired */
GNSS_FIX_STATUS_NO_FIX = 0,
/** GNSS fix acquired */
GNSS_FIX_STATUS_GNSS_FIX = 1,
/** Differential GNSS fix acquired */
GNSS_FIX_STATUS_DGNSS_FIX = 2,
/** Estimated fix acquired */
GNSS_FIX_STATUS_ESTIMATED_FIX = 3,
};
/** GNSS fix quality */
enum gnss_fix_quality {
/** Invalid fix */
GNSS_FIX_QUALITY_INVALID = 0,
/** Standard positioning service */
GNSS_FIX_QUALITY_GNSS_SPS = 1,
/** Differential GNSS */
GNSS_FIX_QUALITY_DGNSS = 2,
/** Precise positioning service */
GNSS_FIX_QUALITY_GNSS_PPS = 3,
/** Real-time kinematic */
GNSS_FIX_QUALITY_RTK = 4,
/** Floating real-time kinematic */
GNSS_FIX_QUALITY_FLOAT_RTK = 5,
/** Estimated fix */
GNSS_FIX_QUALITY_ESTIMATED = 6,
};
/** GNSS info data structure */
struct gnss_info {
/** Number of satellites being tracked */
uint16_t satellites_cnt;
/** Horizontal dilution of precision in 1/1000 */
uint32_t hdop;
/** The fix status */
enum gnss_fix_status fix_status;
/** The fix quality */
enum gnss_fix_quality fix_quality;
};
/** GNSS time data structure */
struct gnss_time {
/** Hour [0, 23] */
uint8_t hour;
/** Minute [0, 59] */
uint8_t minute;
/** Millisecond [0, 60999] */
uint16_t millisecond;
/** Day of month [1, 31] */
uint8_t month_day;
/** Month [1, 12] */
uint8_t month;
/** Year [0, 99] */
uint8_t century_year;
};
/** GNSS API structure */
__subsystem struct gnss_driver_api {
gnss_set_fix_rate_t set_fix_rate;
gnss_get_fix_rate_t get_fix_rate;
gnss_set_periodic_config_t set_periodic_config;
gnss_get_periodic_config_t get_periodic_config;
gnss_set_navigation_mode_t set_navigation_mode;
gnss_get_navigation_mode_t get_navigation_mode;
gnss_set_enabled_systems_t set_enabled_systems;
gnss_get_enabled_systems_t get_enabled_systems;
gnss_get_supported_systems_t get_supported_systems;
};
/** GNSS data structure */
struct gnss_data {
/** Navigation data acquired */
struct navigation_data nav_data;
/** GNSS info when navigation data was acquired */
struct gnss_info info;
/** UTC time when data was acquired */
struct gnss_time utc;
};
/** Template for GNSS data callback */
typedef void (*gnss_data_callback_t)(const struct device *dev, const struct gnss_data *data);
/** GNSS callback structure */
struct gnss_data_callback {
/** Filter callback to GNSS data from this device if not NULL */
const struct device *dev;
/** Callback called when GNSS data is published */
gnss_data_callback_t callback;
};
/** GNSS satellite structure */
struct gnss_satellite {
/** Pseudo-random noise sequence */
uint8_t prn;
/** Signal-to-noise ratio in dB */
uint8_t snr;
/** Elevation in degrees [0, 90] */
uint8_t elevation;
/** Azimuth relative to True North in degrees [0, 359] */
uint16_t azimuth;
/** System of satellite */
enum gnss_system system;
/** True if satellite is being tracked */
uint8_t is_tracked : 1;
};
/** Template for GNSS satellites callback */
typedef void (*gnss_satellites_callback_t)(const struct device *dev,
const struct gnss_satellite *satellites,
uint16_t size);
/** GNSS callback structure */
struct gnss_satellites_callback {
/** Filter callback to GNSS data from this device if not NULL */
const struct device *dev;
/** Callback called when GNSS satellites is published */
gnss_satellites_callback_t callback;
};
/**
* @brief Set the GNSS fix rate
*
* @param dev Device instance
* @param fix_interval_ms Fix interval to set in milliseconds
*
* @return 0 if successful
* @return -errno negative errno code on failure
*/
__syscall int gnss_set_fix_rate(const struct device *dev, uint32_t fix_interval_ms);
static inline int z_impl_gnss_set_fix_rate(const struct device *dev, uint32_t fix_interval_ms)
{
const struct gnss_driver_api *api = (const struct gnss_driver_api *)dev->api;
if (api->set_fix_rate == NULL) {
return -ENOSYS;
}
return api->set_fix_rate(dev, fix_interval_ms);
}
/**
* @brief Get the GNSS fix rate
*
* @param dev Device instance
* @param fix_interval_ms Destination for fix interval in milliseconds
*
* @return 0 if successful
* @return -errno negative errno code on failure
*/
__syscall int gnss_get_fix_rate(const struct device *dev, uint32_t *fix_interval_ms);
static inline int z_impl_gnss_get_fix_rate(const struct device *dev, uint32_t *fix_interval_ms)
{
const struct gnss_driver_api *api = (const struct gnss_driver_api *)dev->api;
if (api->get_fix_rate == NULL) {
return -ENOSYS;
}
return api->get_fix_rate(dev, fix_interval_ms);
}
/**
* @brief Set the GNSS periodic tracking configuration
*
* @param dev Device instance
* @param config Periodic tracking configuration to set
*
* @return 0 if successful
* @return -errno negative errno code on failure
*/
__syscall int gnss_set_periodic_config(const struct device *dev,
const struct gnss_periodic_config *config);
static inline int z_impl_gnss_set_periodic_config(const struct device *dev,
const struct gnss_periodic_config *config)
{
const struct gnss_driver_api *api = (const struct gnss_driver_api *)dev->api;
if (api->set_periodic_config == NULL) {
return -ENOSYS;
}
return api->set_periodic_config(dev, config);
}
/**
* @brief Get the GNSS periodic tracking configuration
*
* @param dev Device instance
* @param config Destination for periodic tracking configuration
*
* @return 0 if successful
* @return -errno negative errno code on failure
*/
__syscall int gnss_get_periodic_config(const struct device *dev,
struct gnss_periodic_config *config);
static inline int z_impl_gnss_get_periodic_config(const struct device *dev,
struct gnss_periodic_config *config)
{
const struct gnss_driver_api *api = (const struct gnss_driver_api *)dev->api;
if (api->get_periodic_config == NULL) {
return -ENOSYS;
}
return api->get_periodic_config(dev, config);
}
/**
* @brief Set the GNSS navigation mode
*
* @param dev Device instance
* @param mode Navigation mode to set
*
* @return 0 if successful
* @return -errno negative errno code on failure
*/
__syscall int gnss_set_navigation_mode(const struct device *dev,
enum gnss_navigation_mode mode);
static inline int z_impl_gnss_set_navigation_mode(const struct device *dev,
enum gnss_navigation_mode mode)
{
const struct gnss_driver_api *api = (const struct gnss_driver_api *)dev->api;
if (api->set_navigation_mode == NULL) {
return -ENOSYS;
}
return api->set_navigation_mode(dev, mode);
}
/**
* @brief Get the GNSS navigation mode
*
* @param dev Device instance
* @param mode Destination for navigation mode
*
* @return 0 if successful
* @return -errno negative errno code on failure
*/
__syscall int gnss_get_navigation_mode(const struct device *dev,
enum gnss_navigation_mode *mode);
static inline int z_impl_gnss_get_navigation_mode(const struct device *dev,
enum gnss_navigation_mode *mode)
{
const struct gnss_driver_api *api = (const struct gnss_driver_api *)dev->api;
if (api->get_navigation_mode == NULL) {
return -ENOSYS;
}
return api->get_navigation_mode(dev, mode);
}
/**
* @brief Set enabled GNSS systems
*
* @param dev Device instance
* @param systems Systems to enable
*
* @return 0 if successful
* @return -errno negative errno code on failure
*/
__syscall int gnss_set_enabled_systems(const struct device *dev, gnss_systems_t systems);
static inline int z_impl_gnss_set_enabled_systems(const struct device *dev,
gnss_systems_t systems)
{
const struct gnss_driver_api *api = (const struct gnss_driver_api *)dev->api;
if (api->set_enabled_systems == NULL) {
return -ENOSYS;
}
return api->set_enabled_systems(dev, systems);
}
/**
* @brief Get enabled GNSS systems
*
* @param dev Device instance
* @param systems Destination for enabled systems
*
* @return 0 if successful
* @return -errno negative errno code on failure
*/
__syscall int gnss_get_enabled_systems(const struct device *dev, gnss_systems_t *systems);
static inline int z_impl_gnss_get_enabled_systems(const struct device *dev,
gnss_systems_t *systems)
{
const struct gnss_driver_api *api = (const struct gnss_driver_api *)dev->api;
if (api->get_enabled_systems == NULL) {
return -ENOSYS;
}
return api->get_enabled_systems(dev, systems);
}
/**
* @brief Get supported GNSS systems
*
* @param dev Device instance
* @param systems Destination for supported systems
*
* @return 0 if successful
* @return -errno negative errno code on failure
*/
__syscall int gnss_get_supported_systems(const struct device *dev, gnss_systems_t *systems);
static inline int z_impl_gnss_get_supported_systems(const struct device *dev,
gnss_systems_t *systems)
{
const struct gnss_driver_api *api = (const struct gnss_driver_api *)dev->api;
if (api->get_supported_systems == NULL) {
return -ENOSYS;
}
return api->get_supported_systems(dev, systems);
}
/**
* @brief Register a callback structure for GNSS data published
*
* @param _dev Device pointer
* @param _callback The callback function
*/
#if CONFIG_GNSS
#define GNSS_DATA_CALLBACK_DEFINE(_dev, _callback) \
static const STRUCT_SECTION_ITERABLE(gnss_data_callback, \
_gnss_data_callback__##_callback) = { \
.dev = _dev, \
.callback = _callback, \
}
#else
#define GNSS_DATA_CALLBACK_DEFINE(_dev, _callback)
#endif
/**
* @brief Register a callback structure for GNSS satellites published
*
* @param _dev Device pointer
* @param _callback The callback function
*/
#if CONFIG_GNSS_SATELLITES
#define GNSS_SATELLITES_CALLBACK_DEFINE(_dev, _callback) \
static const STRUCT_SECTION_ITERABLE(gnss_satellites_callback, \
_gnss_satellites_callback__##_callback) = { \
.dev = _dev, \
.callback = _callback, \
}
#else
#define GNSS_SATELLITES_CALLBACK_DEFINE(_dev, _callback)
#endif
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/gnss.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_GNSS_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/gnss.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 3,473 |
```objective-c
/**
* @file
*
* @brief Generic low-level inter-processor mailbox communication API.
*/
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_IPM_H_
#define ZEPHYR_INCLUDE_DRIVERS_IPM_H_
/**
* @brief IPM Interface
* @defgroup ipm_interface IPM Interface
* @since 1.0
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @typedef ipm_callback_t
* @brief Callback API for incoming IPM messages
*
* These callbacks execute in interrupt context. Therefore, use only
* interrupt-safe APIS. Registration of callbacks is done via
* @a ipm_register_callback
*
* @param ipmdev Driver instance
* @param user_data Pointer to some private data provided at registration
* time.
* @param id Message type identifier.
* @param data Message data pointer. The correct amount of data to read out
* must be inferred using the message id/upper level protocol.
*/
typedef void (*ipm_callback_t)(const struct device *ipmdev, void *user_data,
uint32_t id, volatile void *data);
/**
* @typedef ipm_send_t
* @brief Callback API to send IPM messages
*
* See @a ipm_send() for argument definitions.
*/
typedef int (*ipm_send_t)(const struct device *ipmdev, int wait, uint32_t id,
const void *data, int size);
/**
* @typedef ipm_max_data_size_get_t
* @brief Callback API to get maximum data size
*
* See @a ipm_max_data_size_get() for argument definitions.
*/
typedef int (*ipm_max_data_size_get_t)(const struct device *ipmdev);
/**
* @typedef ipm_max_id_val_get_t
* @brief Callback API to get the ID's maximum value
*
* See @a ipm_max_id_val_get() for argument definitions.
*/
typedef uint32_t (*ipm_max_id_val_get_t)(const struct device *ipmdev);
/**
* @typedef ipm_register_callback_t
* @brief Callback API upon registration
*
* See @a ipm_register_callback() for argument definitions.
*/
typedef void (*ipm_register_callback_t)(const struct device *port,
ipm_callback_t cb,
void *user_data);
/**
* @typedef ipm_set_enabled_t
* @brief Callback API upon enablement of interrupts
*
* See @a ipm_set_enabled() for argument definitions.
*/
typedef int (*ipm_set_enabled_t)(const struct device *ipmdev, int enable);
/**
* @typedef ipm_complete_t
* @brief Callback API upon command completion
*
* See @a ipm_complete() for argument definitions.
*/
typedef void (*ipm_complete_t)(const struct device *ipmdev);
__subsystem struct ipm_driver_api {
ipm_send_t send;
ipm_register_callback_t register_callback;
ipm_max_data_size_get_t max_data_size_get;
ipm_max_id_val_get_t max_id_val_get;
ipm_set_enabled_t set_enabled;
#ifdef CONFIG_IPM_CALLBACK_ASYNC
ipm_complete_t complete;
#endif
};
/**
* @brief Try to send a message over the IPM device.
*
* A message is considered consumed once the remote interrupt handler
* finishes. If there is deferred processing on the remote side,
* or if outgoing messages must be queued and wait on an
* event/semaphore, a high-level driver can implement that.
*
* There are constraints on how much data can be sent or the maximum value
* of id. Use the @a ipm_max_data_size_get and @a ipm_max_id_val_get routines
* to determine them.
*
* The @a size parameter is used only on the sending side to determine
* the amount of data to put in the message registers. It is not passed along
* to the receiving side. The upper-level protocol dictates the amount of
* data read back.
*
* @param ipmdev Driver instance
* @param wait If nonzero, busy-wait for remote to consume the message. The
* message is considered consumed once the remote interrupt handler
* finishes. If there is deferred processing on the remote side,
* or you would like to queue outgoing messages and wait on an
* event/semaphore, you can implement that in a high-level driver
* @param id Message identifier. Values are constrained by
* @a ipm_max_data_size_get since many boards only allow for a
* subset of bits in a 32-bit register to store the ID.
* @param data Pointer to the data sent in the message.
* @param size Size of the data.
*
* @retval -EBUSY If the remote hasn't yet read the last data sent.
* @retval -EMSGSIZE If the supplied data size is unsupported by the driver.
* @retval -EINVAL If there was a bad parameter, such as: too-large id value.
* or the device isn't an outbound IPM channel.
* @retval 0 On success.
*/
__syscall int ipm_send(const struct device *ipmdev, int wait, uint32_t id,
const void *data, int size);
static inline int z_impl_ipm_send(const struct device *ipmdev, int wait,
uint32_t id,
const void *data, int size)
{
const struct ipm_driver_api *api =
(const struct ipm_driver_api *)ipmdev->api;
return api->send(ipmdev, wait, id, data, size);
}
/**
* @brief Register a callback function for incoming messages.
*
* @param ipmdev Driver instance pointer.
* @param cb Callback function to execute on incoming message interrupts.
* @param user_data Application-specific data pointer which will be passed
* to the callback function when executed.
*/
static inline void ipm_register_callback(const struct device *ipmdev,
ipm_callback_t cb, void *user_data)
{
const struct ipm_driver_api *api =
(const struct ipm_driver_api *)ipmdev->api;
api->register_callback(ipmdev, cb, user_data);
}
/**
* @brief Return the maximum number of bytes possible in an outbound message.
*
* IPM implementations vary on the amount of data that can be sent in a
* single message since the data payload is typically stored in registers.
*
* @param ipmdev Driver instance pointer.
*
* @return Maximum possible size of a message in bytes.
*/
__syscall int ipm_max_data_size_get(const struct device *ipmdev);
static inline int z_impl_ipm_max_data_size_get(const struct device *ipmdev)
{
const struct ipm_driver_api *api =
(const struct ipm_driver_api *)ipmdev->api;
return api->max_data_size_get(ipmdev);
}
/**
* @brief Return the maximum id value possible in an outbound message.
*
* Many IPM implementations store the message's ID in a register with
* some bits reserved for other uses.
*
* @param ipmdev Driver instance pointer.
*
* @return Maximum possible value of a message ID.
*/
__syscall uint32_t ipm_max_id_val_get(const struct device *ipmdev);
static inline uint32_t z_impl_ipm_max_id_val_get(const struct device *ipmdev)
{
const struct ipm_driver_api *api =
(const struct ipm_driver_api *)ipmdev->api;
return api->max_id_val_get(ipmdev);
}
/**
* @brief Enable interrupts and callbacks for inbound channels.
*
* @param ipmdev Driver instance pointer.
* @param enable Set to 0 to disable and to nonzero to enable.
*
* @retval 0 On success.
* @retval -EINVAL If it isn't an inbound channel.
*/
__syscall int ipm_set_enabled(const struct device *ipmdev, int enable);
static inline int z_impl_ipm_set_enabled(const struct device *ipmdev,
int enable)
{
const struct ipm_driver_api *api =
(const struct ipm_driver_api *)ipmdev->api;
return api->set_enabled(ipmdev, enable);
}
/**
* @brief Signal asynchronous command completion
*
* Some IPM backends have an ability to deliver a command
* asynchronously. The callback will be invoked in interrupt context,
* but the message (including the provided data pointer) will stay
* "active" and unacknowledged until later code (presumably in thread
* mode) calls ipm_complete().
*
* This function is, obviously, a noop on drivers without async
* support.
*
* @param ipmdev Driver instance pointer.
*/
__syscall void ipm_complete(const struct device *ipmdev);
static inline void z_impl_ipm_complete(const struct device *ipmdev)
{
#ifdef CONFIG_IPM_CALLBACK_ASYNC
const struct ipm_driver_api *api =
(const struct ipm_driver_api *)ipmdev->api;
if (api->complete != NULL) {
api->complete(ipmdev);
}
#endif
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/ipm.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_IPM_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/ipm.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,993 |
```objective-c
/**
* @file drivers/sensor.h
*
* @brief Public APIs for the sensor driver.
*/
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_SENSOR_H_
#define ZEPHYR_INCLUDE_DRIVERS_SENSOR_H_
/**
* @brief Sensor Interface
* @defgroup sensor_interface Sensor Interface
* @since 1.2
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <stdlib.h>
#include <zephyr/device.h>
#include <zephyr/drivers/sensor_data_types.h>
#include <zephyr/dsp/types.h>
#include <zephyr/rtio/rtio.h>
#include <zephyr/sys/iterable_sections.h>
#include <zephyr/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Representation of a sensor readout value.
*
* The value is represented as having an integer and a fractional part,
* and can be obtained using the formula val1 + val2 * 10^(-6). Negative
* values also adhere to the above formula, but may need special attention.
* Here are some examples of the value representation:
*
* 0.5: val1 = 0, val2 = 500000
* -0.5: val1 = 0, val2 = -500000
* -1.0: val1 = -1, val2 = 0
* -1.5: val1 = -1, val2 = -500000
*/
struct sensor_value {
/** Integer part of the value. */
int32_t val1;
/** Fractional part of the value (in one-millionth parts). */
int32_t val2;
};
/**
* @brief Sensor channels.
*/
enum sensor_channel {
/** Acceleration on the X axis, in m/s^2. */
SENSOR_CHAN_ACCEL_X,
/** Acceleration on the Y axis, in m/s^2. */
SENSOR_CHAN_ACCEL_Y,
/** Acceleration on the Z axis, in m/s^2. */
SENSOR_CHAN_ACCEL_Z,
/** Acceleration on the X, Y and Z axes. */
SENSOR_CHAN_ACCEL_XYZ,
/** Angular velocity around the X axis, in radians/s. */
SENSOR_CHAN_GYRO_X,
/** Angular velocity around the Y axis, in radians/s. */
SENSOR_CHAN_GYRO_Y,
/** Angular velocity around the Z axis, in radians/s. */
SENSOR_CHAN_GYRO_Z,
/** Angular velocity around the X, Y and Z axes. */
SENSOR_CHAN_GYRO_XYZ,
/** Magnetic field on the X axis, in Gauss. */
SENSOR_CHAN_MAGN_X,
/** Magnetic field on the Y axis, in Gauss. */
SENSOR_CHAN_MAGN_Y,
/** Magnetic field on the Z axis, in Gauss. */
SENSOR_CHAN_MAGN_Z,
/** Magnetic field on the X, Y and Z axes. */
SENSOR_CHAN_MAGN_XYZ,
/** Device die temperature in degrees Celsius. */
SENSOR_CHAN_DIE_TEMP,
/** Ambient temperature in degrees Celsius. */
SENSOR_CHAN_AMBIENT_TEMP,
/** Pressure in kilopascal. */
SENSOR_CHAN_PRESS,
/**
* Proximity. Adimensional. A value of 1 indicates that an
* object is close.
*/
SENSOR_CHAN_PROX,
/** Humidity, in percent. */
SENSOR_CHAN_HUMIDITY,
/** Illuminance in visible spectrum, in lux. */
SENSOR_CHAN_LIGHT,
/** Illuminance in infra-red spectrum, in lux. */
SENSOR_CHAN_IR,
/** Illuminance in red spectrum, in lux. */
SENSOR_CHAN_RED,
/** Illuminance in green spectrum, in lux. */
SENSOR_CHAN_GREEN,
/** Illuminance in blue spectrum, in lux. */
SENSOR_CHAN_BLUE,
/** Altitude, in meters */
SENSOR_CHAN_ALTITUDE,
/** 1.0 micro-meters Particulate Matter, in ug/m^3 */
SENSOR_CHAN_PM_1_0,
/** 2.5 micro-meters Particulate Matter, in ug/m^3 */
SENSOR_CHAN_PM_2_5,
/** 10 micro-meters Particulate Matter, in ug/m^3 */
SENSOR_CHAN_PM_10,
/** Distance. From sensor to target, in meters */
SENSOR_CHAN_DISTANCE,
/** CO2 level, in parts per million (ppm) **/
SENSOR_CHAN_CO2,
/** O2 level, in parts per million (ppm) **/
SENSOR_CHAN_O2,
/** VOC level, in parts per billion (ppb) **/
SENSOR_CHAN_VOC,
/** Gas sensor resistance in ohms. */
SENSOR_CHAN_GAS_RES,
/** Voltage, in volts **/
SENSOR_CHAN_VOLTAGE,
/** Current Shunt Voltage in milli-volts **/
SENSOR_CHAN_VSHUNT,
/** Current, in amps **/
SENSOR_CHAN_CURRENT,
/** Power in watts **/
SENSOR_CHAN_POWER,
/** Resistance , in Ohm **/
SENSOR_CHAN_RESISTANCE,
/** Angular rotation, in degrees */
SENSOR_CHAN_ROTATION,
/** Position change on the X axis, in points. */
SENSOR_CHAN_POS_DX,
/** Position change on the Y axis, in points. */
SENSOR_CHAN_POS_DY,
/** Position change on the Z axis, in points. */
SENSOR_CHAN_POS_DZ,
/** Position change on the X, Y and Z axis, in points. */
SENSOR_CHAN_POS_DXYZ,
/** Revolutions per minute, in RPM. */
SENSOR_CHAN_RPM,
/** Voltage, in volts **/
SENSOR_CHAN_GAUGE_VOLTAGE,
/** Average current, in amps **/
SENSOR_CHAN_GAUGE_AVG_CURRENT,
/** Standby current, in amps **/
SENSOR_CHAN_GAUGE_STDBY_CURRENT,
/** Max load current, in amps **/
SENSOR_CHAN_GAUGE_MAX_LOAD_CURRENT,
/** Gauge temperature **/
SENSOR_CHAN_GAUGE_TEMP,
/** State of charge measurement in % **/
SENSOR_CHAN_GAUGE_STATE_OF_CHARGE,
/** Full Charge Capacity in mAh **/
SENSOR_CHAN_GAUGE_FULL_CHARGE_CAPACITY,
/** Remaining Charge Capacity in mAh **/
SENSOR_CHAN_GAUGE_REMAINING_CHARGE_CAPACITY,
/** Nominal Available Capacity in mAh **/
SENSOR_CHAN_GAUGE_NOM_AVAIL_CAPACITY,
/** Full Available Capacity in mAh **/
SENSOR_CHAN_GAUGE_FULL_AVAIL_CAPACITY,
/** Average power in mW **/
SENSOR_CHAN_GAUGE_AVG_POWER,
/** State of health measurement in % **/
SENSOR_CHAN_GAUGE_STATE_OF_HEALTH,
/** Time to empty in minutes **/
SENSOR_CHAN_GAUGE_TIME_TO_EMPTY,
/** Time to full in minutes **/
SENSOR_CHAN_GAUGE_TIME_TO_FULL,
/** Cycle count (total number of charge/discharge cycles) **/
SENSOR_CHAN_GAUGE_CYCLE_COUNT,
/** Design voltage of cell in V (max voltage)*/
SENSOR_CHAN_GAUGE_DESIGN_VOLTAGE,
/** Desired voltage of cell in V (nominal voltage) */
SENSOR_CHAN_GAUGE_DESIRED_VOLTAGE,
/** Desired charging current in mA */
SENSOR_CHAN_GAUGE_DESIRED_CHARGING_CURRENT,
/** All channels. */
SENSOR_CHAN_ALL,
/**
* Number of all common sensor channels.
*/
SENSOR_CHAN_COMMON_COUNT,
/**
* This and higher values are sensor specific.
* Refer to the sensor header file.
*/
SENSOR_CHAN_PRIV_START = SENSOR_CHAN_COMMON_COUNT,
/**
* Maximum value describing a sensor channel type.
*/
SENSOR_CHAN_MAX = INT16_MAX,
};
/**
* @brief Sensor trigger types.
*/
enum sensor_trigger_type {
/**
* Timer-based trigger, useful when the sensor does not have an
* interrupt line.
*/
SENSOR_TRIG_TIMER,
/** Trigger fires whenever new data is ready. */
SENSOR_TRIG_DATA_READY,
/**
* Trigger fires when the selected channel varies significantly.
* This includes any-motion detection when the channel is
* acceleration or gyro. If detection is based on slope between
* successive channel readings, the slope threshold is configured
* via the @ref SENSOR_ATTR_SLOPE_TH and @ref SENSOR_ATTR_SLOPE_DUR
* attributes.
*/
SENSOR_TRIG_DELTA,
/** Trigger fires when a near/far event is detected. */
SENSOR_TRIG_NEAR_FAR,
/**
* Trigger fires when channel reading transitions configured
* thresholds. The thresholds are configured via the @ref
* SENSOR_ATTR_LOWER_THRESH, @ref SENSOR_ATTR_UPPER_THRESH, and
* @ref SENSOR_ATTR_HYSTERESIS attributes.
*/
SENSOR_TRIG_THRESHOLD,
/** Trigger fires when a single tap is detected. */
SENSOR_TRIG_TAP,
/** Trigger fires when a double tap is detected. */
SENSOR_TRIG_DOUBLE_TAP,
/** Trigger fires when a free fall is detected. */
SENSOR_TRIG_FREEFALL,
/** Trigger fires when motion is detected. */
SENSOR_TRIG_MOTION,
/** Trigger fires when no motion has been detected for a while. */
SENSOR_TRIG_STATIONARY,
/** Trigger fires when the FIFO watermark has been reached. */
SENSOR_TRIG_FIFO_WATERMARK,
/** Trigger fires when the FIFO becomes full. */
SENSOR_TRIG_FIFO_FULL,
/**
* Number of all common sensor triggers.
*/
SENSOR_TRIG_COMMON_COUNT,
/**
* This and higher values are sensor specific.
* Refer to the sensor header file.
*/
SENSOR_TRIG_PRIV_START = SENSOR_TRIG_COMMON_COUNT,
/**
* Maximum value describing a sensor trigger type.
*/
SENSOR_TRIG_MAX = INT16_MAX,
};
/**
* @brief Sensor trigger spec.
*/
struct sensor_trigger {
/** Trigger type. */
enum sensor_trigger_type type;
/** Channel the trigger is set on. */
enum sensor_channel chan;
};
/**
* @brief Sensor attribute types.
*/
enum sensor_attribute {
/**
* Sensor sampling frequency, i.e. how many times a second the
* sensor takes a measurement.
*/
SENSOR_ATTR_SAMPLING_FREQUENCY,
/** Lower threshold for trigger. */
SENSOR_ATTR_LOWER_THRESH,
/** Upper threshold for trigger. */
SENSOR_ATTR_UPPER_THRESH,
/** Threshold for any-motion (slope) trigger. */
SENSOR_ATTR_SLOPE_TH,
/**
* Duration for which the slope values needs to be
* outside the threshold for the trigger to fire.
*/
SENSOR_ATTR_SLOPE_DUR,
/* Hysteresis for trigger thresholds. */
SENSOR_ATTR_HYSTERESIS,
/** Oversampling factor */
SENSOR_ATTR_OVERSAMPLING,
/** Sensor range, in SI units. */
SENSOR_ATTR_FULL_SCALE,
/**
* The sensor value returned will be altered by the amount indicated by
* offset: final_value = sensor_value + offset.
*/
SENSOR_ATTR_OFFSET,
/**
* Calibration target. This will be used by the internal chip's
* algorithms to calibrate itself on a certain axis, or all of them.
*/
SENSOR_ATTR_CALIB_TARGET,
/** Configure the operating modes of a sensor. */
SENSOR_ATTR_CONFIGURATION,
/** Set a calibration value needed by a sensor. */
SENSOR_ATTR_CALIBRATION,
/** Enable/disable sensor features */
SENSOR_ATTR_FEATURE_MASK,
/** Alert threshold or alert enable/disable */
SENSOR_ATTR_ALERT,
/** Free-fall duration represented in milliseconds.
* If the sampling frequency is changed during runtime,
* this attribute should be set to adjust freefall duration
* to the new sampling frequency.
*/
SENSOR_ATTR_FF_DUR,
/** Hardware batch duration in ticks */
SENSOR_ATTR_BATCH_DURATION,
/* Configure the gain of a sensor. */
SENSOR_ATTR_GAIN,
/* Configure the resolution of a sensor. */
SENSOR_ATTR_RESOLUTION,
/**
* Number of all common sensor attributes.
*/
SENSOR_ATTR_COMMON_COUNT,
/**
* This and higher values are sensor specific.
* Refer to the sensor header file.
*/
SENSOR_ATTR_PRIV_START = SENSOR_ATTR_COMMON_COUNT,
/**
* Maximum value describing a sensor attribute type.
*/
SENSOR_ATTR_MAX = INT16_MAX,
};
/**
* @typedef sensor_trigger_handler_t
* @brief Callback API upon firing of a trigger
*
* @param dev Pointer to the sensor device
* @param trigger The trigger
*/
typedef void (*sensor_trigger_handler_t)(const struct device *dev,
const struct sensor_trigger *trigger);
/**
* @typedef sensor_attr_set_t
* @brief Callback API upon setting a sensor's attributes
*
* See sensor_attr_set() for argument description
*/
typedef int (*sensor_attr_set_t)(const struct device *dev,
enum sensor_channel chan,
enum sensor_attribute attr,
const struct sensor_value *val);
/**
* @typedef sensor_attr_get_t
* @brief Callback API upon getting a sensor's attributes
*
* See sensor_attr_get() for argument description
*/
typedef int (*sensor_attr_get_t)(const struct device *dev,
enum sensor_channel chan,
enum sensor_attribute attr,
struct sensor_value *val);
/**
* @typedef sensor_trigger_set_t
* @brief Callback API for setting a sensor's trigger and handler
*
* See sensor_trigger_set() for argument description
*/
typedef int (*sensor_trigger_set_t)(const struct device *dev,
const struct sensor_trigger *trig,
sensor_trigger_handler_t handler);
/**
* @typedef sensor_sample_fetch_t
* @brief Callback API for fetching data from a sensor
*
* See sensor_sample_fetch() for argument description
*/
typedef int (*sensor_sample_fetch_t)(const struct device *dev,
enum sensor_channel chan);
/**
* @typedef sensor_channel_get_t
* @brief Callback API for getting a reading from a sensor
*
* See sensor_channel_get() for argument description
*/
typedef int (*sensor_channel_get_t)(const struct device *dev,
enum sensor_channel chan,
struct sensor_value *val);
/**
* @brief Sensor Channel Specification
*
* A sensor channel specification is a unique identifier per sensor device describing
* a measurement channel.
*
* @note Typically passed by value as the size of a sensor_chan_spec is a single word.
*/
struct sensor_chan_spec {
uint16_t chan_type; /**< A sensor channel type */
uint16_t chan_idx; /**< A sensor channel index */
};
/** @cond INTERNAL_HIDDEN */
/* Ensure sensor_chan_spec is sensibly sized to pass by value */
BUILD_ASSERT(sizeof(struct sensor_chan_spec) <= sizeof(uintptr_t),
"sensor_chan_spec size should be equal or less than the size of a machine word");
/** @endcond */
/**
* @brief Check if channel specs are equivalent
*
* @param chan_spec0 First chan spec
* @param chan_spec1 Second chan spec
* @retval true If equivalent
* @retval false If not equivalent
*/
static inline bool sensor_chan_spec_eq(struct sensor_chan_spec chan_spec0,
struct sensor_chan_spec chan_spec1)
{
return chan_spec0.chan_type == chan_spec1.chan_type &&
chan_spec0.chan_idx == chan_spec1.chan_idx;
}
/**
* @brief Decodes a single raw data buffer
*
* Data buffers are provided on the @ref rtio context that's supplied to
* @ref sensor_read.
*/
struct sensor_decoder_api {
/**
* @brief Get the number of frames in the current buffer.
*
* @param[in] buffer The buffer provided on the @ref rtio context.
* @param[in] channel The channel to get the count for
* @param[out] frame_count The number of frames on the buffer (at least 1)
* @return 0 on success
* @return -ENOTSUP if the channel/channel_idx aren't found
*/
int (*get_frame_count)(const uint8_t *buffer, struct sensor_chan_spec channel,
uint16_t *frame_count);
/**
* @brief Get the size required to decode a given channel
*
* When decoding a single frame, use @p base_size. For every additional frame, add another
* @p frame_size. As an example, to decode 3 frames use: 'base_size + 2 * frame_size'.
*
* @param[in] channel The channel to query
* @param[out] base_size The size of decoding the first frame
* @param[out] frame_size The additional size of every additional frame
* @return 0 on success
* @return -ENOTSUP if the channel is not supported
*/
int (*get_size_info)(struct sensor_chan_spec channel, size_t *base_size,
size_t *frame_size);
/**
* @brief Decode up to @p max_count samples from the buffer
*
* Decode samples of channel @ref sensor_channel across multiple frames. If there exist
* multiple instances of the same channel, @p channel_index is used to differentiate them.
* As an example, assume a sensor provides 2 distance measurements:
*
* @code{.c}
* // Decode the first channel instance of 'distance'
* decoder->decode(buffer, SENSOR_CHAN_DISTANCE, 0, &fit, 5, out);
* ...
*
* // Decode the second channel instance of 'distance'
* decoder->decode(buffer, SENSOR_CHAN_DISTANCE, 1, &fit, 5, out);
* @endcode
*
* @param[in] buffer The buffer provided on the @ref rtio context
* @param[in] channel The channel to decode
* @param[in,out] fit The current frame iterator
* @param[in] max_count The maximum number of channels to decode.
* @param[out] data_out The decoded data
* @return 0 no more samples to decode
* @return >0 the number of decoded frames
* @return <0 on error
*/
int (*decode)(const uint8_t *buffer, struct sensor_chan_spec channel, uint32_t *fit,
uint16_t max_count, void *data_out);
/**
* @brief Check if the given trigger type is present
*
* @param[in] buffer The buffer provided on the @ref rtio context
* @param[in] trigger The trigger type in question
* @return Whether the trigger is present in the buffer
*/
bool (*has_trigger)(const uint8_t *buffer, enum sensor_trigger_type trigger);
};
/**
* @brief Used for iterating over the data frames via the sensor_decoder_api.
*
* Example usage:
*
* @code(.c)
* struct sensor_decode_context ctx = SENSOR_DECODE_CONTEXT_INIT(
* decoder, buffer, SENSOR_CHAN_ACCEL_XYZ, 0);
*
* while (true) {
* struct sensor_three_axis_data accel_out_data;
*
* num_decoded_channels = sensor_decode(ctx, &accel_out_data, 1);
*
* if (num_decoded_channels <= 0) {
* printk("Done decoding buffer\n");
* break;
* }
*
* printk("Decoded (%" PRId32 ", %" PRId32 ", %" PRId32 ")\n", accel_out_data.readings[0].x,
* accel_out_data.readings[0].y, accel_out_data.readings[0].z);
* }
* @endcode
*/
struct sensor_decode_context {
const struct sensor_decoder_api *decoder;
const uint8_t *buffer;
struct sensor_chan_spec channel;
uint32_t fit;
};
/**
* @brief Initialize a sensor_decode_context
*/
#define SENSOR_DECODE_CONTEXT_INIT(decoder_, buffer_, channel_type_, channel_index_) \
{ \
.decoder = (decoder_), \
.buffer = (buffer_), \
.channel = {.chan_type = (channel_type_), .chan_idx = (channel_index_)}, \
.fit = 0, \
}
/**
* @brief Decode N frames using a sensor_decode_context
*
* @param[in,out] ctx The context to use for decoding
* @param[out] out The output buffer
* @param[in] max_count Maximum number of frames to decode
* @return The decode result from sensor_decoder_api's decode function
*/
static inline int sensor_decode(struct sensor_decode_context *ctx, void *out, uint16_t max_count)
{
return ctx->decoder->decode(ctx->buffer, ctx->channel, &ctx->fit, max_count, out);
}
int sensor_natively_supported_channel_size_info(struct sensor_chan_spec channel, size_t *base_size,
size_t *frame_size);
/**
* @typedef sensor_get_decoder_t
* @brief Get the decoder associate with the given device
*
* @see sensor_get_decoder for more details
*/
typedef int (*sensor_get_decoder_t)(const struct device *dev,
const struct sensor_decoder_api **api);
/**
* @brief Options for what to do with the associated data when a trigger is consumed
*/
enum sensor_stream_data_opt {
/** @brief Include whatever data is associated with the trigger */
SENSOR_STREAM_DATA_INCLUDE = 0,
/** @brief Do nothing with the associated trigger data, it may be consumed later */
SENSOR_STREAM_DATA_NOP = 1,
/** @brief Flush/clear whatever data is associated with the trigger */
SENSOR_STREAM_DATA_DROP = 2,
};
struct sensor_stream_trigger {
enum sensor_trigger_type trigger;
enum sensor_stream_data_opt opt;
};
#define SENSOR_STREAM_TRIGGER_PREP(_trigger, _opt) \
{ \
.trigger = (_trigger), .opt = (_opt), \
}
/*
* Internal data structure used to store information about the IODevice for async reading and
* streaming sensor data.
*/
struct sensor_read_config {
const struct device *sensor;
const bool is_streaming;
union {
struct sensor_chan_spec *const channels;
struct sensor_stream_trigger *const triggers;
};
size_t count;
const size_t max;
};
/**
* @brief Define a reading instance of a sensor
*
* Use this macro to generate a @ref rtio_iodev for reading specific channels. Example:
*
* @code(.c)
* SENSOR_DT_READ_IODEV(icm42688_accelgyro, DT_NODELABEL(icm42688),
* { SENSOR_CHAN_ACCEL_XYZ, 0 },
* { SENSOR_CHAN_GYRO_XYZ, 0 });
*
* int main(void) {
* sensor_read_async_mempool(&icm42688_accelgyro, &rtio);
* }
* @endcode
*/
#define SENSOR_DT_READ_IODEV(name, dt_node, ...) \
static struct sensor_chan_spec _CONCAT(__channel_array_, name)[] = {__VA_ARGS__}; \
static struct sensor_read_config _CONCAT(__sensor_read_config_, name) = { \
.sensor = DEVICE_DT_GET(dt_node), \
.is_streaming = false, \
.channels = _CONCAT(__channel_array_, name), \
.count = ARRAY_SIZE(_CONCAT(__channel_array_, name)), \
.max = ARRAY_SIZE(_CONCAT(__channel_array_, name)), \
}; \
RTIO_IODEV_DEFINE(name, &__sensor_iodev_api, _CONCAT(&__sensor_read_config_, name))
/**
* @brief Define a stream instance of a sensor
*
* Use this macro to generate a @ref rtio_iodev for starting a stream that's triggered by specific
* interrupts. Example:
*
* @code(.c)
* SENSOR_DT_STREAM_IODEV(imu_stream, DT_ALIAS(imu),
* {SENSOR_TRIG_FIFO_WATERMARK, SENSOR_STREAM_DATA_INCLUDE},
* {SENSOR_TRIG_FIFO_FULL, SENSOR_STREAM_DATA_NOP});
*
* int main(void) {
* struct rtio_sqe *handle;
* sensor_stream(&imu_stream, &rtio, NULL, &handle);
* k_msleep(1000);
* rtio_sqe_cancel(handle);
* }
* @endcode
*/
#define SENSOR_DT_STREAM_IODEV(name, dt_node, ...) \
static struct sensor_stream_trigger _CONCAT(__trigger_array_, name)[] = {__VA_ARGS__}; \
static struct sensor_read_config _CONCAT(__sensor_read_config_, name) = { \
.sensor = DEVICE_DT_GET(dt_node), \
.is_streaming = true, \
.triggers = _CONCAT(__trigger_array_, name), \
.count = ARRAY_SIZE(_CONCAT(__trigger_array_, name)), \
.max = ARRAY_SIZE(_CONCAT(__trigger_array_, name)), \
}; \
RTIO_IODEV_DEFINE(name, &__sensor_iodev_api, &_CONCAT(__sensor_read_config_, name))
/* Used to submit an RTIO sqe to the sensor's iodev */
typedef void (*sensor_submit_t)(const struct device *sensor, struct rtio_iodev_sqe *sqe);
/* The default decoder API */
extern const struct sensor_decoder_api __sensor_default_decoder;
/* The default sensor iodev API */
extern const struct rtio_iodev_api __sensor_iodev_api;
__subsystem struct sensor_driver_api {
sensor_attr_set_t attr_set;
sensor_attr_get_t attr_get;
sensor_trigger_set_t trigger_set;
sensor_sample_fetch_t sample_fetch;
sensor_channel_get_t channel_get;
sensor_get_decoder_t get_decoder;
sensor_submit_t submit;
};
/**
* @brief Set an attribute for a sensor
*
* @param dev Pointer to the sensor device
* @param chan The channel the attribute belongs to, if any. Some
* attributes may only be set for all channels of a device, depending on
* device capabilities.
* @param attr The attribute to set
* @param val The value to set the attribute to
*
* @return 0 if successful, negative errno code if failure.
*/
__syscall int sensor_attr_set(const struct device *dev,
enum sensor_channel chan,
enum sensor_attribute attr,
const struct sensor_value *val);
static inline int z_impl_sensor_attr_set(const struct device *dev,
enum sensor_channel chan,
enum sensor_attribute attr,
const struct sensor_value *val)
{
const struct sensor_driver_api *api =
(const struct sensor_driver_api *)dev->api;
if (api->attr_set == NULL) {
return -ENOSYS;
}
return api->attr_set(dev, chan, attr, val);
}
/**
* @brief Get an attribute for a sensor
*
* @param dev Pointer to the sensor device
* @param chan The channel the attribute belongs to, if any. Some
* attributes may only be set for all channels of a device, depending on
* device capabilities.
* @param attr The attribute to get
* @param val Pointer to where to store the attribute
*
* @return 0 if successful, negative errno code if failure.
*/
__syscall int sensor_attr_get(const struct device *dev,
enum sensor_channel chan,
enum sensor_attribute attr,
struct sensor_value *val);
static inline int z_impl_sensor_attr_get(const struct device *dev,
enum sensor_channel chan,
enum sensor_attribute attr,
struct sensor_value *val)
{
const struct sensor_driver_api *api =
(const struct sensor_driver_api *)dev->api;
if (api->attr_get == NULL) {
return -ENOSYS;
}
return api->attr_get(dev, chan, attr, val);
}
/**
* @brief Activate a sensor's trigger and set the trigger handler
*
* The handler will be called from a thread, so I2C or SPI operations are
* safe. However, the thread's stack is limited and defined by the
* driver. It is currently up to the caller to ensure that the handler
* does not overflow the stack.
*
* The user-allocated trigger will be stored by the driver as a pointer, rather
* than a copy, and passed back to the handler. This enables the handler to use
* CONTAINER_OF to retrieve a context pointer when the trigger is embedded in a
* larger struct and requires that the trigger is not allocated on the stack.
*
* @funcprops \supervisor
*
* @param dev Pointer to the sensor device
* @param trig The trigger to activate
* @param handler The function that should be called when the trigger
* fires
*
* @return 0 if successful, negative errno code if failure.
*/
static inline int sensor_trigger_set(const struct device *dev,
const struct sensor_trigger *trig,
sensor_trigger_handler_t handler)
{
const struct sensor_driver_api *api =
(const struct sensor_driver_api *)dev->api;
if (api->trigger_set == NULL) {
return -ENOSYS;
}
return api->trigger_set(dev, trig, handler);
}
/**
* @brief Fetch a sample from the sensor and store it in an internal
* driver buffer
*
* Read all of a sensor's active channels and, if necessary, perform any
* additional operations necessary to make the values useful. The user
* may then get individual channel values by calling @ref
* sensor_channel_get.
*
* The function blocks until the fetch operation is complete.
*
* Since the function communicates with the sensor device, it is unsafe
* to call it in an ISR if the device is connected via I2C or SPI.
*
* @param dev Pointer to the sensor device
*
* @return 0 if successful, negative errno code if failure.
*/
__syscall int sensor_sample_fetch(const struct device *dev);
static inline int z_impl_sensor_sample_fetch(const struct device *dev)
{
const struct sensor_driver_api *api =
(const struct sensor_driver_api *)dev->api;
return api->sample_fetch(dev, SENSOR_CHAN_ALL);
}
/**
* @brief Fetch a sample from the sensor and store it in an internal
* driver buffer
*
* Read and compute compensation for one type of sensor data (magnetometer,
* accelerometer, etc). The user may then get individual channel values by
* calling @ref sensor_channel_get.
*
* This is mostly implemented by multi function devices enabling reading at
* different sampling rates.
*
* The function blocks until the fetch operation is complete.
*
* Since the function communicates with the sensor device, it is unsafe
* to call it in an ISR if the device is connected via I2C or SPI.
*
* @param dev Pointer to the sensor device
* @param type The channel that needs updated
*
* @return 0 if successful, negative errno code if failure.
*/
__syscall int sensor_sample_fetch_chan(const struct device *dev,
enum sensor_channel type);
static inline int z_impl_sensor_sample_fetch_chan(const struct device *dev,
enum sensor_channel type)
{
const struct sensor_driver_api *api =
(const struct sensor_driver_api *)dev->api;
return api->sample_fetch(dev, type);
}
/**
* @brief Get a reading from a sensor device
*
* Return a useful value for a particular channel, from the driver's
* internal data. Before calling this function, a sample must be
* obtained by calling @ref sensor_sample_fetch or
* @ref sensor_sample_fetch_chan. It is guaranteed that two subsequent
* calls of this function for the same channels will yield the same
* value, if @ref sensor_sample_fetch or @ref sensor_sample_fetch_chan
* has not been called in the meantime.
*
* For vectorial data samples you can request all axes in just one call
* by passing the specific channel with _XYZ suffix. The sample will be
* returned at val[0], val[1] and val[2] (X, Y and Z in that order).
*
* @param dev Pointer to the sensor device
* @param chan The channel to read
* @param val Where to store the value
*
* @return 0 if successful, negative errno code if failure.
*/
__syscall int sensor_channel_get(const struct device *dev,
enum sensor_channel chan,
struct sensor_value *val);
static inline int z_impl_sensor_channel_get(const struct device *dev,
enum sensor_channel chan,
struct sensor_value *val)
{
const struct sensor_driver_api *api =
(const struct sensor_driver_api *)dev->api;
return api->channel_get(dev, chan, val);
}
#if defined(CONFIG_SENSOR_ASYNC_API) || defined(__DOXYGEN__)
/*
* Generic data structure used for encoding the sample timestamp and number of channels sampled.
*/
struct __attribute__((__packed__)) sensor_data_generic_header {
/* The timestamp at which the data was collected from the sensor */
uint64_t timestamp_ns;
/*
* The number of channels present in the frame. This will be the true number of elements in
* channel_info and in the q31 values that follow the header.
*/
uint32_t num_channels;
/* Shift value for all samples in the frame */
int8_t shift;
/* This padding is needed to make sure that the 'channels' field is aligned */
int8_t _padding[sizeof(struct sensor_chan_spec) - 1];
/* Channels present in the frame */
struct sensor_chan_spec channels[0];
};
/**
* @brief checks if a given channel is a 3-axis channel
*
* @param[in] chan The channel to check
* @retval true if @p chan is any of @ref SENSOR_CHAN_ACCEL_XYZ, @ref SENSOR_CHAN_GYRO_XYZ, or
* @ref SENSOR_CHAN_MAGN_XYZ, or @ref SENSOR_CHAN_POS_DXYZ
* @retval false otherwise
*/
#define SENSOR_CHANNEL_3_AXIS(chan) \
((chan) == SENSOR_CHAN_ACCEL_XYZ || (chan) == SENSOR_CHAN_GYRO_XYZ || \
(chan) == SENSOR_CHAN_MAGN_XYZ || (chan) == SENSOR_CHAN_POS_DXYZ)
/**
* @brief Get the sensor's decoder API
*
* @param[in] dev The sensor device
* @param[in] decoder Pointer to the decoder which will be set upon success
* @return 0 on success
* @return < 0 on error
*/
__syscall int sensor_get_decoder(const struct device *dev,
const struct sensor_decoder_api **decoder);
static inline int z_impl_sensor_get_decoder(const struct device *dev,
const struct sensor_decoder_api **decoder)
{
const struct sensor_driver_api *api = (const struct sensor_driver_api *)dev->api;
__ASSERT_NO_MSG(api != NULL);
if (api->get_decoder == NULL) {
*decoder = &__sensor_default_decoder;
return 0;
}
return api->get_decoder(dev, decoder);
}
/**
* @brief Reconfigure a reading iodev
*
* Allows a reconfiguration of the iodev associated with reading a sample from a sensor.
*
* <b>Important</b>: If the iodev is currently servicing a read operation, the data will likely be
* invalid. Please be sure the flush or wait for all pending operations to complete before using the
* data after a configuration change.
*
* It is also important that the `data` field of the iodev is a @ref sensor_read_config.
*
* @param[in] iodev The iodev to reconfigure
* @param[in] sensor The sensor to read from
* @param[in] channels One or more channels to read
* @param[in] num_channels The number of channels in @p channels
* @return 0 on success
* @return < 0 on error
*/
__syscall int sensor_reconfigure_read_iodev(struct rtio_iodev *iodev, const struct device *sensor,
const struct sensor_chan_spec *channels,
size_t num_channels);
static inline int z_impl_sensor_reconfigure_read_iodev(struct rtio_iodev *iodev,
const struct device *sensor,
const struct sensor_chan_spec *channels,
size_t num_channels)
{
struct sensor_read_config *cfg = (struct sensor_read_config *)iodev->data;
if (cfg->max < num_channels || cfg->is_streaming) {
return -ENOMEM;
}
cfg->sensor = sensor;
memcpy(cfg->channels, channels, num_channels * sizeof(struct sensor_chan_spec));
cfg->count = num_channels;
return 0;
}
static inline int sensor_stream(struct rtio_iodev *iodev, struct rtio *ctx, void *userdata,
struct rtio_sqe **handle)
{
if (IS_ENABLED(CONFIG_USERSPACE)) {
struct rtio_sqe sqe;
rtio_sqe_prep_read_multishot(&sqe, iodev, RTIO_PRIO_NORM, userdata);
rtio_sqe_copy_in_get_handles(ctx, &sqe, handle, 1);
} else {
struct rtio_sqe *sqe = rtio_sqe_acquire(ctx);
if (sqe == NULL) {
return -ENOMEM;
}
if (handle != NULL) {
*handle = sqe;
}
rtio_sqe_prep_read_multishot(sqe, iodev, RTIO_PRIO_NORM, userdata);
}
rtio_submit(ctx, 0);
return 0;
}
/**
* @brief Blocking one shot read of samples from a sensor into a buffer
*
* Using @p cfg, read data from the device by using the provided RTIO context
* @p ctx. This call will generate a @ref rtio_sqe that will be given the provided buffer. The call
* will wait for the read to complete before returning to the caller.
*
* @param[in] iodev The iodev created by @ref SENSOR_DT_READ_IODEV
* @param[in] ctx The RTIO context to service the read
* @param[in] buf Pointer to memory to read sample data into
* @param[in] buf_len Size in bytes of the given memory that are valid to read into
* @return 0 on success
* @return < 0 on error
*/
static inline int sensor_read(struct rtio_iodev *iodev, struct rtio *ctx, uint8_t *buf,
size_t buf_len)
{
if (IS_ENABLED(CONFIG_USERSPACE)) {
struct rtio_sqe sqe;
rtio_sqe_prep_read(&sqe, iodev, RTIO_PRIO_NORM, buf, buf_len, buf);
rtio_sqe_copy_in(ctx, &sqe, 1);
} else {
struct rtio_sqe *sqe = rtio_sqe_acquire(ctx);
if (sqe == NULL) {
return -ENOMEM;
}
rtio_sqe_prep_read(sqe, iodev, RTIO_PRIO_NORM, buf, buf_len, buf);
}
rtio_submit(ctx, 0);
struct rtio_cqe *cqe = rtio_cqe_consume_block(ctx);
int res = cqe->result;
__ASSERT(cqe->userdata != buf,
"consumed non-matching completion for sensor read into buffer %p\n", buf);
rtio_cqe_release(ctx, cqe);
return res;
}
/**
* @brief One shot non-blocking read with pool allocated buffer
*
* Using @p cfg, read one snapshot of data from the device by using the provided RTIO context
* @p ctx. This call will generate a @ref rtio_sqe that will leverage the RTIO's internal
* mempool when the time comes to service the read.
*
* @param[in] iodev The iodev created by @ref SENSOR_DT_READ_IODEV
* @param[in] ctx The RTIO context to service the read
* @param[in] userdata Optional userdata that will be available when the read is complete
* @return 0 on success
* @return < 0 on error
*/
static inline int sensor_read_async_mempool(struct rtio_iodev *iodev, struct rtio *ctx,
void *userdata)
{
if (IS_ENABLED(CONFIG_USERSPACE)) {
struct rtio_sqe sqe;
rtio_sqe_prep_read_with_pool(&sqe, iodev, RTIO_PRIO_NORM, userdata);
rtio_sqe_copy_in(ctx, &sqe, 1);
} else {
struct rtio_sqe *sqe = rtio_sqe_acquire(ctx);
if (sqe == NULL) {
return -ENOMEM;
}
rtio_sqe_prep_read_with_pool(sqe, iodev, RTIO_PRIO_NORM, userdata);
}
rtio_submit(ctx, 0);
return 0;
}
/**
* @typedef sensor_processing_callback_t
* @brief Callback function used with the helper processing function.
*
* @see sensor_processing_with_callback
*
* @param[in] result The result code of the read (0 being success)
* @param[in] buf The data buffer holding the sensor data
* @param[in] buf_len The length (in bytes) of the @p buf
* @param[in] userdata The optional userdata passed to sensor_read_async_mempool()
*/
typedef void (*sensor_processing_callback_t)(int result, uint8_t *buf, uint32_t buf_len,
void *userdata);
/**
* @brief Helper function for common processing of sensor data.
*
* This function can be called in a blocking manner after sensor_read() or in a standalone
* thread dedicated to processing. It will wait for a cqe from the RTIO context, once received, it
* will decode the userdata and call the @p cb. Once the @p cb returns, the buffer will be released
* back into @p ctx's mempool if available.
*
* @param[in] ctx The RTIO context to wait on
* @param[in] cb Callback to call when data is ready for processing
*/
void sensor_processing_with_callback(struct rtio *ctx, sensor_processing_callback_t cb);
#endif /* defined(CONFIG_SENSOR_ASYNC_API) || defined(__DOXYGEN__) */
/**
* @brief The value of gravitational constant in micro m/s^2.
*/
#define SENSOR_G 9806650LL
/**
* @brief The value of constant PI in micros.
*/
#define SENSOR_PI 3141592LL
/**
* @brief Helper function to convert acceleration from m/s^2 to Gs
*
* @param ms2 A pointer to a sensor_value struct holding the acceleration,
* in m/s^2.
*
* @return The converted value, in Gs.
*/
static inline int32_t sensor_ms2_to_g(const struct sensor_value *ms2)
{
int64_t micro_ms2 = ms2->val1 * 1000000LL + ms2->val2;
if (micro_ms2 > 0) {
return (micro_ms2 + SENSOR_G / 2) / SENSOR_G;
} else {
return (micro_ms2 - SENSOR_G / 2) / SENSOR_G;
}
}
/**
* @brief Helper function to convert acceleration from Gs to m/s^2
*
* @param g The G value to be converted.
* @param ms2 A pointer to a sensor_value struct, where the result is stored.
*/
static inline void sensor_g_to_ms2(int32_t g, struct sensor_value *ms2)
{
ms2->val1 = ((int64_t)g * SENSOR_G) / 1000000LL;
ms2->val2 = ((int64_t)g * SENSOR_G) % 1000000LL;
}
/**
* @brief Helper function to convert acceleration from m/s^2 to micro Gs
*
* @param ms2 A pointer to a sensor_value struct holding the acceleration,
* in m/s^2.
*
* @return The converted value, in micro Gs.
*/
static inline int32_t sensor_ms2_to_ug(const struct sensor_value *ms2)
{
int64_t micro_ms2 = (ms2->val1 * INT64_C(1000000)) + ms2->val2;
return (micro_ms2 * 1000000LL) / SENSOR_G;
}
/**
* @brief Helper function to convert acceleration from micro Gs to m/s^2
*
* @param ug The micro G value to be converted.
* @param ms2 A pointer to a sensor_value struct, where the result is stored.
*/
static inline void sensor_ug_to_ms2(int32_t ug, struct sensor_value *ms2)
{
ms2->val1 = ((int64_t)ug * SENSOR_G / 1000000LL) / 1000000LL;
ms2->val2 = ((int64_t)ug * SENSOR_G / 1000000LL) % 1000000LL;
}
/**
* @brief Helper function for converting radians to degrees.
*
* @param rad A pointer to a sensor_value struct, holding the value in radians.
*
* @return The converted value, in degrees.
*/
static inline int32_t sensor_rad_to_degrees(const struct sensor_value *rad)
{
int64_t micro_rad_s = rad->val1 * 1000000LL + rad->val2;
if (micro_rad_s > 0) {
return (micro_rad_s * 180LL + SENSOR_PI / 2) / SENSOR_PI;
} else {
return (micro_rad_s * 180LL - SENSOR_PI / 2) / SENSOR_PI;
}
}
/**
* @brief Helper function for converting degrees to radians.
*
* @param d The value (in degrees) to be converted.
* @param rad A pointer to a sensor_value struct, where the result is stored.
*/
static inline void sensor_degrees_to_rad(int32_t d, struct sensor_value *rad)
{
rad->val1 = ((int64_t)d * SENSOR_PI / 180LL) / 1000000LL;
rad->val2 = ((int64_t)d * SENSOR_PI / 180LL) % 1000000LL;
}
/**
* @brief Helper function for converting radians to 10 micro degrees.
*
* When the unit is 1 micro degree, the range that the int32_t can represent is
* +/-2147.483 degrees. In order to increase this range, here we use 10 micro
* degrees as the unit.
*
* @param rad A pointer to a sensor_value struct, holding the value in radians.
*
* @return The converted value, in 10 micro degrees.
*/
static inline int32_t sensor_rad_to_10udegrees(const struct sensor_value *rad)
{
int64_t micro_rad_s = rad->val1 * 1000000LL + rad->val2;
return (micro_rad_s * 180LL * 100000LL) / SENSOR_PI;
}
/**
* @brief Helper function for converting 10 micro degrees to radians.
*
* @param d The value (in 10 micro degrees) to be converted.
* @param rad A pointer to a sensor_value struct, where the result is stored.
*/
static inline void sensor_10udegrees_to_rad(int32_t d, struct sensor_value *rad)
{
rad->val1 = ((int64_t)d * SENSOR_PI / 180LL / 100000LL) / 1000000LL;
rad->val2 = ((int64_t)d * SENSOR_PI / 180LL / 100000LL) % 1000000LL;
}
/**
* @brief Helper function for converting struct sensor_value to double.
*
* @param val A pointer to a sensor_value struct.
* @return The converted value.
*/
static inline double sensor_value_to_double(const struct sensor_value *val)
{
return (double)val->val1 + (double)val->val2 / 1000000;
}
/**
* @brief Helper function for converting struct sensor_value to float.
*
* @param val A pointer to a sensor_value struct.
* @return The converted value.
*/
static inline float sensor_value_to_float(const struct sensor_value *val)
{
return (float)val->val1 + (float)val->val2 / 1000000;
}
/**
* @brief Helper function for converting double to struct sensor_value.
*
* @param val A pointer to a sensor_value struct.
* @param inp The converted value.
* @return 0 if successful, negative errno code if failure.
*/
static inline int sensor_value_from_double(struct sensor_value *val, double inp)
{
if (inp < INT32_MIN || inp > INT32_MAX) {
return -ERANGE;
}
double val2 = (inp - (int32_t)inp) * 1000000.0;
if (val2 < INT32_MIN || val2 > INT32_MAX) {
return -ERANGE;
}
val->val1 = (int32_t)inp;
val->val2 = (int32_t)val2;
return 0;
}
/**
* @brief Helper function for converting float to struct sensor_value.
*
* @param val A pointer to a sensor_value struct.
* @param inp The converted value.
* @return 0 if successful, negative errno code if failure.
*/
static inline int sensor_value_from_float(struct sensor_value *val, float inp)
{
float val2 = (inp - (int32_t)inp) * 1000000.0f;
if (val2 < INT32_MIN || val2 > (float)(INT32_MAX - 1)) {
return -ERANGE;
}
val->val1 = (int32_t)inp;
val->val2 = (int32_t)val2;
return 0;
}
#ifdef CONFIG_SENSOR_INFO
struct sensor_info {
const struct device *dev;
const char *vendor;
const char *model;
const char *friendly_name;
};
#define SENSOR_INFO_INITIALIZER(_dev, _vendor, _model, _friendly_name) \
{ \
.dev = _dev, \
.vendor = _vendor, \
.model = _model, \
.friendly_name = _friendly_name, \
}
#define SENSOR_INFO_DEFINE(name, ...) \
static const STRUCT_SECTION_ITERABLE(sensor_info, name) = \
SENSOR_INFO_INITIALIZER(__VA_ARGS__)
#define SENSOR_INFO_DT_NAME(node_id) \
_CONCAT(__sensor_info, DEVICE_DT_NAME_GET(node_id))
#define SENSOR_INFO_DT_DEFINE(node_id) \
SENSOR_INFO_DEFINE(SENSOR_INFO_DT_NAME(node_id), \
DEVICE_DT_GET(node_id), \
DT_NODE_VENDOR_OR(node_id, NULL), \
DT_NODE_MODEL_OR(node_id, NULL), \
DT_PROP_OR(node_id, friendly_name, NULL)) \
#else
#define SENSOR_INFO_DEFINE(name, ...)
#define SENSOR_INFO_DT_DEFINE(node_id)
#endif /* CONFIG_SENSOR_INFO */
/**
* @brief Like DEVICE_DT_DEFINE() with sensor specifics.
*
* @details Defines a device which implements the sensor API. May define an
* element in the sensor info iterable section used to enumerate all sensor
* devices.
*
* @param node_id The devicetree node identifier.
*
* @param init_fn Name of the init function of the driver.
*
* @param pm_device PM device resources reference (NULL if device does not use
* PM).
*
* @param data_ptr Pointer to the device's private data.
*
* @param cfg_ptr The address to the structure containing the configuration
* information for this instance of the driver.
*
* @param level The initialization level. See SYS_INIT() for details.
*
* @param prio Priority within the selected initialization level. See
* SYS_INIT() for details.
*
* @param api_ptr Provides an initial pointer to the API function struct used
* by the driver. Can be NULL.
*/
#define SENSOR_DEVICE_DT_DEFINE(node_id, init_fn, pm_device, \
data_ptr, cfg_ptr, level, prio, \
api_ptr, ...) \
DEVICE_DT_DEFINE(node_id, init_fn, pm_device, \
data_ptr, cfg_ptr, level, prio, \
api_ptr, __VA_ARGS__); \
\
SENSOR_INFO_DT_DEFINE(node_id);
/**
* @brief Like SENSOR_DEVICE_DT_DEFINE() for an instance of a DT_DRV_COMPAT
* compatible
*
* @param inst instance number. This is replaced by
* <tt>DT_DRV_COMPAT(inst)</tt> in the call to SENSOR_DEVICE_DT_DEFINE().
*
* @param ... other parameters as expected by SENSOR_DEVICE_DT_DEFINE().
*/
#define SENSOR_DEVICE_DT_INST_DEFINE(inst, ...) \
SENSOR_DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
/**
* @brief Helper function for converting struct sensor_value to integer milli units.
*
* @param val A pointer to a sensor_value struct.
* @return The converted value.
*/
static inline int64_t sensor_value_to_milli(const struct sensor_value *val)
{
return ((int64_t)val->val1 * 1000) + val->val2 / 1000;
}
/**
* @brief Helper function for converting struct sensor_value to integer micro units.
*
* @param val A pointer to a sensor_value struct.
* @return The converted value.
*/
static inline int64_t sensor_value_to_micro(const struct sensor_value *val)
{
return ((int64_t)val->val1 * 1000000) + val->val2;
}
/**
* @brief Helper function for converting integer milli units to struct sensor_value.
*
* @param val A pointer to a sensor_value struct.
* @param milli The converted value.
* @return 0 if successful, negative errno code if failure.
*/
static inline int sensor_value_from_milli(struct sensor_value *val, int64_t milli)
{
if (milli < ((int64_t)INT32_MIN - 1) * 1000LL ||
milli > ((int64_t)INT32_MAX + 1) * 1000LL) {
return -ERANGE;
}
val->val1 = (int32_t)(milli / 1000);
val->val2 = (int32_t)(milli % 1000) * 1000;
return 0;
}
/**
* @brief Helper function for converting integer micro units to struct sensor_value.
*
* @param val A pointer to a sensor_value struct.
* @param micro The converted value.
* @return 0 if successful, negative errno code if failure.
*/
static inline int sensor_value_from_micro(struct sensor_value *val, int64_t micro)
{
if (micro < ((int64_t)INT32_MIN - 1) * 1000000LL ||
micro > ((int64_t)INT32_MAX + 1) * 1000000LL) {
return -ERANGE;
}
val->val1 = (int32_t)(micro / 1000000LL);
val->val2 = (int32_t)(micro % 1000000LL);
return 0;
}
/**
* @}
*/
/**
* @brief Get the decoder name for the current driver
*
* This function depends on `DT_DRV_COMPAT` being defined.
*/
#define SENSOR_DECODER_NAME() UTIL_CAT(DT_DRV_COMPAT, __decoder_api)
/**
* @brief Statically get the decoder for a given node
*
* @code{.c}
* static const sensor_decoder_api *decoder = SENSOR_DECODER_DT_GET(DT_ALIAS(accel));
* @endcode
*/
#define SENSOR_DECODER_DT_GET(node_id) \
&UTIL_CAT(DT_STRING_TOKEN_BY_IDX(node_id, compatible, 0), __decoder_api)
/**
* @brief Define a decoder API
*
* This macro should be created once per compatible string of a sensor and will create a statically
* referenceable decoder API.
*
* @code{.c}
* SENSOR_DECODER_API_DT_DEFINE() = {
* .get_frame_count = my_driver_get_frame_count,
* .get_timestamp = my_driver_get_timestamp,
* .get_shift = my_driver_get_shift,
* .decode = my_driver_decode,
* };
* @endcode
*/
#define SENSOR_DECODER_API_DT_DEFINE() \
COND_CODE_1(DT_HAS_COMPAT_STATUS_OKAY(DT_DRV_COMPAT), (), (static)) \
const STRUCT_SECTION_ITERABLE(sensor_decoder_api, SENSOR_DECODER_NAME())
#define Z_MAYBE_SENSOR_DECODER_DECLARE_INTERNAL_IDX(node_id, prop, idx) \
extern const struct sensor_decoder_api UTIL_CAT( \
DT_STRING_TOKEN_BY_IDX(node_id, prop, idx), __decoder_api);
#define Z_MAYBE_SENSOR_DECODER_DECLARE_INTERNAL(node_id) \
COND_CODE_1(DT_NODE_HAS_PROP(node_id, compatible), \
(DT_FOREACH_PROP_ELEM(node_id, compatible, \
Z_MAYBE_SENSOR_DECODER_DECLARE_INTERNAL_IDX)), \
())
DT_FOREACH_STATUS_OKAY_NODE(Z_MAYBE_SENSOR_DECODER_DECLARE_INTERNAL)
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/sensor.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_SENSOR_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/sensor.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 12,162 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_HWSPINLOCK_H_
#define ZEPHYR_INCLUDE_DRIVERS_HWSPINLOCK_H_
/**
* @brief HW spinlock Interface
* @defgroup hwspinlock_interface HW spinlock Interface
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <zephyr/sys/util.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @cond INTERNAL_HIDDEN */
/**
* @brief Callback API for trying to lock HW spinlock
* @see hwspinlock_trylock().
*/
typedef int (*hwspinlock_api_trylock)(const struct device *dev, uint32_t id);
/**
* @brief Callback API to lock HW spinlock
* @see hwspinlock_lock().
*/
typedef void (*hwspinlock_api_lock)(const struct device *dev, uint32_t id);
/**
* @brief Callback API to unlock HW spinlock
* @see hwspinlock_unlock().
*/
typedef void (*hwspinlock_api_unlock)(const struct device *dev, uint32_t id);
/**
* @brief Callback API to get HW spinlock max ID
* @see hwspinlock_get_max_id().
*/
typedef uint32_t (*hwspinlock_api_get_max_id)(const struct device *dev);
__subsystem struct hwspinlock_driver_api {
hwspinlock_api_trylock trylock;
hwspinlock_api_lock lock;
hwspinlock_api_unlock unlock;
hwspinlock_api_get_max_id get_max_id;
};
/**
* @endcond
*/
/**
* @brief Try to lock HW spinlock
*
* This function is used for try to lock specific HW spinlock. It should
* be called before a critical section that we want to protect.
*
* @param dev HW spinlock device instance.
* @param id Spinlock identifier.
*
* @retval 0 If successful.
* @retval -errno In case of any failure.
*/
__syscall int hwspinlock_trylock(const struct device *dev, uint32_t id);
static inline int z_impl_hwspinlock_trylock(const struct device *dev, uint32_t id)
{
const struct hwspinlock_driver_api *api =
(const struct hwspinlock_driver_api *)dev->api;
if (api->trylock == NULL) {
return -ENOSYS;
}
return api->trylock(dev, id);
}
/**
* @brief Lock HW spinlock
*
* This function is used to lock specific HW spinlock. It should be
* called before a critical section that we want to protect.
*
* @param dev HW spinlock device instance.
* @param id Spinlock identifier.
*/
__syscall void hwspinlock_lock(const struct device *dev, uint32_t id);
static inline void z_impl_hwspinlock_lock(const struct device *dev, uint32_t id)
{
const struct hwspinlock_driver_api *api =
(const struct hwspinlock_driver_api *)dev->api;
if (api->lock != NULL) {
api->lock(dev, id);
}
}
/**
* @brief Try to unlock HW spinlock
*
* This function is used for try to unlock specific HW spinlock. It should
* be called after a critical section that we want to protect.
*
* @param dev HW spinlock device instance.
* @param id Spinlock identifier.
*/
__syscall void hwspinlock_unlock(const struct device *dev, uint32_t id);
static inline void z_impl_hwspinlock_unlock(const struct device *dev, uint32_t id)
{
const struct hwspinlock_driver_api *api =
(const struct hwspinlock_driver_api *)dev->api;
if (api->unlock != NULL) {
api->unlock(dev, id);
}
}
/**
* @brief Get HW spinlock max ID
*
* This function is used to get the HW spinlock maximum ID. It should
* be called before attempting to lock/unlock a specific HW spinlock.
*
* @param dev HW spinlock device instance.
*
* @retval HW spinlock max ID.
* @retval 0 if the function is not implemented by the driver.
*/
__syscall uint32_t hwspinlock_get_max_id(const struct device *dev);
static inline uint32_t z_impl_hwspinlock_get_max_id(const struct device *dev)
{
const struct hwspinlock_driver_api *api =
(const struct hwspinlock_driver_api *)dev->api;
if (api->get_max_id == NULL) {
return 0;
}
return api->get_max_id(dev);
}
#ifdef __cplusplus
}
#endif
/** @} */
#include <zephyr/syscalls/hwspinlock.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_HWSPINLOCK_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/hwspinlock.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,009 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public APIs for coredump pseudo-device driver
*/
#ifndef INCLUDE_ZEPHYR_DRIVERS_COREDUMP_H_
#define INCLUDE_ZEPHYR_DRIVERS_COREDUMP_H_
#include <zephyr/device.h>
#include <zephyr/sys/slist.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Coredump pseudo-device driver APIs
* @defgroup coredump_device_interface Coredump pseudo-device driver APIs
* @ingroup io_interfaces
* @{
*/
/**
* @brief Structure describing a region in memory that may be
* stored in core dump at the time it is generated
*
* Instances of this are passed to the coredump_device_register_memory() and
* coredump_device_unregister_memory() functions to indicate addition and removal
* of memory regions to be captured
*/
struct coredump_mem_region_node {
/** Node of single-linked list, do not modify */
sys_snode_t node;
/** Address of start of memory region */
uintptr_t start;
/** Size of memory region */
size_t size;
};
/**
* @brief Callback that occurs at dump time, data copied into dump_area will
* be included in the dump that is generated
*
* @param dump_area Pointer to area to copy data into for inclusion in dump
* @param dump_area_size Size of available memory at dump_area
*/
typedef void (*coredump_dump_callback_t)(uintptr_t dump_area, size_t dump_area_size);
/**
* @cond INTERNAL_HIDDEN
*
* For internal use only, skip these in public documentation.
*/
/*
* Type definition of coredump API function for adding specified
* data into coredump
*/
typedef void (*coredump_device_dump_t)(const struct device *dev);
/*
* Type definition of coredump API function for registering a memory
* region
*/
typedef bool (*coredump_device_register_memory_t)(const struct device *dev,
struct coredump_mem_region_node *region);
/*
* Type definition of coredump API function for unregistering a memory
* region
*/
typedef bool (*coredump_device_unregister_memory_t)(const struct device *dev,
struct coredump_mem_region_node *region);
/*
* Type definition of coredump API function for registering a dump
* callback
*/
typedef bool (*coredump_device_register_callback_t)(const struct device *dev,
coredump_dump_callback_t callback);
/*
* API which a coredump pseudo-device driver should expose
*/
__subsystem struct coredump_driver_api {
coredump_device_dump_t dump;
coredump_device_register_memory_t register_memory;
coredump_device_unregister_memory_t unregister_memory;
coredump_device_register_callback_t register_callback;
};
/**
* @endcond
*/
/**
* @brief Register a region of memory to be stored in core dump at the
* time it is generated
*
* @param dev Pointer to the device structure for the driver instance.
* @param region Struct describing memory to be collected
*
* @return true if registration succeeded
* @return false if registration failed
*/
static inline bool coredump_device_register_memory(const struct device *dev,
struct coredump_mem_region_node *region)
{
const struct coredump_driver_api *api =
(const struct coredump_driver_api *)dev->api;
return api->register_memory(dev, region);
}
/**
* @brief Unregister a region of memory to be stored in core dump at the
* time it is generated
*
* @param dev Pointer to the device structure for the driver instance.
* @param region Struct describing memory to be collected
*
* @return true if unregistration succeeded
* @return false if unregistration failed
*/
static inline bool coredump_device_unregister_memory(const struct device *dev,
struct coredump_mem_region_node *region)
{
const struct coredump_driver_api *api =
(const struct coredump_driver_api *)dev->api;
return api->unregister_memory(dev, region);
}
/**
* @brief Register a callback to be invoked at dump time
*
* @param dev Pointer to the device structure for the driver instance.
* @param callback Callback to be invoked at dump time
*
* @return true if registration succeeded
* @return false if registration failed
*/
static inline bool coredump_device_register_callback(const struct device *dev,
coredump_dump_callback_t callback)
{
const struct coredump_driver_api *api =
(const struct coredump_driver_api *)dev->api;
return api->register_callback(dev, callback);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* INCLUDE_ZEPHYR_DRIVERS_COREDUMP_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/coredump.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 989 |
```objective-c
/**
* @file
* @brief ADC public API header file.
*/
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_ADC_H_
#define ZEPHYR_INCLUDE_DRIVERS_ADC_H_
#include <zephyr/device.h>
#include <zephyr/dt-bindings/adc/adc.h>
#include <zephyr/kernel.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief ADC driver APIs
* @defgroup adc_interface ADC driver APIs
* @since 1.0
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
/** @brief ADC channel gain factors. */
enum adc_gain {
ADC_GAIN_1_6, /**< x 1/6. */
ADC_GAIN_1_5, /**< x 1/5. */
ADC_GAIN_1_4, /**< x 1/4. */
ADC_GAIN_1_3, /**< x 1/3. */
ADC_GAIN_2_5, /**< x 2/5. */
ADC_GAIN_1_2, /**< x 1/2. */
ADC_GAIN_2_3, /**< x 2/3. */
ADC_GAIN_4_5, /**< x 4/5. */
ADC_GAIN_1, /**< x 1. */
ADC_GAIN_2, /**< x 2. */
ADC_GAIN_3, /**< x 3. */
ADC_GAIN_4, /**< x 4. */
ADC_GAIN_6, /**< x 6. */
ADC_GAIN_8, /**< x 8. */
ADC_GAIN_12, /**< x 12. */
ADC_GAIN_16, /**< x 16. */
ADC_GAIN_24, /**< x 24. */
ADC_GAIN_32, /**< x 32. */
ADC_GAIN_64, /**< x 64. */
ADC_GAIN_128, /**< x 128. */
};
/**
* @brief Invert the application of gain to a measurement value.
*
* For example, if the gain passed in is ADC_GAIN_1_6 and the
* referenced value is 10, the value after the function returns is 60.
*
* @param gain the gain used to amplify the input signal.
*
* @param value a pointer to a value that initially has the effect of
* the applied gain but has that effect removed when this function
* successfully returns. If the gain cannot be reversed the value
* remains unchanged.
*
* @retval 0 if the gain was successfully reversed
* @retval -EINVAL if the gain could not be interpreted
*/
int adc_gain_invert(enum adc_gain gain,
int32_t *value);
/** @brief ADC references. */
enum adc_reference {
ADC_REF_VDD_1, /**< VDD. */
ADC_REF_VDD_1_2, /**< VDD/2. */
ADC_REF_VDD_1_3, /**< VDD/3. */
ADC_REF_VDD_1_4, /**< VDD/4. */
ADC_REF_INTERNAL, /**< Internal. */
ADC_REF_EXTERNAL0, /**< External, input 0. */
ADC_REF_EXTERNAL1, /**< External, input 1. */
};
/**
* @brief Structure for specifying the configuration of an ADC channel.
*/
struct adc_channel_cfg {
/** Gain selection. */
enum adc_gain gain;
/** Reference selection. */
enum adc_reference reference;
/**
* Acquisition time.
* Use the ADC_ACQ_TIME macro to compose the value for this field or
* pass ADC_ACQ_TIME_DEFAULT to use the default setting for a given
* hardware (e.g. when the hardware does not allow to configure the
* acquisition time).
* Particular drivers do not necessarily support all the possible units.
* Value range is 0-16383 for a given unit.
*/
uint16_t acquisition_time;
/**
* Channel identifier.
* This value primarily identifies the channel within the ADC API - when
* a read request is done, the corresponding bit in the "channels" field
* of the "adc_sequence" structure must be set to include this channel
* in the sampling.
* For hardware that does not allow selection of analog inputs for given
* channels, but rather have dedicated ones, this value also selects the
* physical ADC input to be used in the sampling. Otherwise, when it is
* needed to explicitly select an analog input for the channel, or two
* inputs when the channel is a differential one, the selection is done
* in "input_positive" and "input_negative" fields.
* Particular drivers indicate which one of the above two cases they
* support by selecting or not a special hidden Kconfig option named
* ADC_CONFIGURABLE_INPUTS. If this option is not selected, the macro
* CONFIG_ADC_CONFIGURABLE_INPUTS is not defined and consequently the
* mentioned two fields are not present in this structure.
* While this API allows identifiers from range 0-31, particular drivers
* may support only a limited number of channel identifiers (dependent
* on the underlying hardware capabilities or configured via a dedicated
* Kconfig option).
*/
uint8_t channel_id : 5;
/** Channel type: single-ended or differential. */
uint8_t differential : 1;
#ifdef CONFIG_ADC_CONFIGURABLE_INPUTS
/**
* Positive ADC input.
* This is a driver dependent value that identifies an ADC input to be
* associated with the channel.
*/
uint8_t input_positive;
/**
* Negative ADC input (used only for differential channels).
* This is a driver dependent value that identifies an ADC input to be
* associated with the channel.
*/
uint8_t input_negative;
#endif /* CONFIG_ADC_CONFIGURABLE_INPUTS */
#ifdef CONFIG_ADC_CONFIGURABLE_EXCITATION_CURRENT_SOURCE_PIN
uint8_t current_source_pin_set : 1;
/**
* Output pin for the current sources.
* This is only available if the driver enables this feature
* via the hidden configuration option ADC_CONFIGURABLE_EXCITATION_CURRENT_SOURCE_PIN.
* The meaning itself is then defined by the driver itself.
*/
uint8_t current_source_pin[2];
#endif /* CONFIG_ADC_CONFIGURABLE_EXCITATION_CURRENT_SOURCE_PIN */
#ifdef CONFIG_ADC_CONFIGURABLE_VBIAS_PIN
/**
* Output pins for the bias voltage.
* This is only available if the driver enables this feature
* via the hidden configuration option ADC_CONFIGURABLE_VBIAS_PIN.
* The field is interpreted as a bitmask, where each bit represents
* one of the input pins. The actual mapping to the physical pins
* depends on the driver itself.
*/
uint32_t vbias_pins;
#endif /* CONFIG_ADC_CONFIGURABLE_VBIAS_PIN */
};
/**
* @brief Get ADC channel configuration from a given devicetree node.
*
* This returns a static initializer for a <tt>struct adc_channel_cfg</tt>
* filled with data from a given devicetree node.
*
* Example devicetree fragment:
*
* @code{.dts}
* &adc {
* #address-cells = <1>;
* #size-cells = <0>;
*
* channel@0 {
* reg = <0>;
* zephyr,gain = "ADC_GAIN_1_6";
* zephyr,reference = "ADC_REF_INTERNAL";
* zephyr,acquisition-time = <ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 20)>;
* zephyr,input-positive = <NRF_SAADC_AIN6>;
* zephyr,input-negative = <NRF_SAADC_AIN7>;
* };
*
* channel@1 {
* reg = <1>;
* zephyr,gain = "ADC_GAIN_1_6";
* zephyr,reference = "ADC_REF_INTERNAL";
* zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
* zephyr,input-positive = <NRF_SAADC_AIN0>;
* };
* };
* @endcode
*
* Example usage:
*
* @code{.c}
* static const struct adc_channel_cfg ch0_cfg_dt =
* ADC_CHANNEL_CFG_DT(DT_CHILD(DT_NODELABEL(adc), channel_0));
* static const struct adc_channel_cfg ch1_cfg_dt =
* ADC_CHANNEL_CFG_DT(DT_CHILD(DT_NODELABEL(adc), channel_1));
*
* // Initializes 'ch0_cfg_dt' to:
* // {
* // .channel_id = 0,
* // .gain = ADC_GAIN_1_6,
* // .reference = ADC_REF_INTERNAL,
* // .acquisition_time = ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 20),
* // .differential = true,
* // .input_positive = NRF_SAADC_AIN6,
* // .input-negative = NRF_SAADC_AIN7,
* // }
* // and 'ch1_cfg_dt' to:
* // {
* // .channel_id = 1,
* // .gain = ADC_GAIN_1_6,
* // .reference = ADC_REF_INTERNAL,
* // .acquisition_time = ADC_ACQ_TIME_DEFAULT,
* // .input_positive = NRF_SAADC_AIN0,
* // }
* @endcode
*
* @param node_id Devicetree node identifier.
*
* @return Static initializer for an adc_channel_cfg structure.
*/
#define ADC_CHANNEL_CFG_DT(node_id) { \
.gain = DT_STRING_TOKEN(node_id, zephyr_gain), \
.reference = DT_STRING_TOKEN(node_id, zephyr_reference), \
.acquisition_time = DT_PROP(node_id, zephyr_acquisition_time), \
.channel_id = DT_REG_ADDR(node_id), \
IF_ENABLED(UTIL_OR(DT_PROP(node_id, zephyr_differential), \
UTIL_AND(CONFIG_ADC_CONFIGURABLE_INPUTS, \
DT_NODE_HAS_PROP(node_id, zephyr_input_negative))), \
(.differential = true,)) \
IF_ENABLED(CONFIG_ADC_CONFIGURABLE_INPUTS, \
(.input_positive = DT_PROP_OR(node_id, zephyr_input_positive, 0), \
.input_negative = DT_PROP_OR(node_id, zephyr_input_negative, 0),)) \
IF_ENABLED(CONFIG_ADC_CONFIGURABLE_EXCITATION_CURRENT_SOURCE_PIN, \
(.current_source_pin_set = DT_NODE_HAS_PROP(node_id, zephyr_current_source_pin), \
.current_source_pin = DT_PROP_OR(node_id, zephyr_current_source_pin, {0}),)) \
IF_ENABLED(CONFIG_ADC_CONFIGURABLE_VBIAS_PIN, \
(.vbias_pins = DT_PROP_OR(node_id, zephyr_vbias_pins, 0),)) \
}
/**
* @brief Container for ADC channel information specified in devicetree.
*
* @see ADC_DT_SPEC_GET_BY_IDX
* @see ADC_DT_SPEC_GET
*/
struct adc_dt_spec {
/**
* Pointer to the device structure for the ADC driver instance
* used by this io-channel.
*/
const struct device *dev;
/** ADC channel identifier used by this io-channel. */
uint8_t channel_id;
/**
* Flag indicating whether configuration of the associated ADC channel
* is provided as a child node of the corresponding ADC controller in
* devicetree.
*/
bool channel_cfg_dt_node_exists;
/**
* Configuration of the associated ADC channel specified in devicetree.
* This field is valid only when @a channel_cfg_dt_node_exists is set
* to @a true.
*/
struct adc_channel_cfg channel_cfg;
/**
* Voltage of the reference selected for the channel or 0 if this
* value is not provided in devicetree.
* This field is valid only when @a channel_cfg_dt_node_exists is set
* to @a true.
*/
uint16_t vref_mv;
/**
* ADC resolution to be used for that channel.
* This field is valid only when @a channel_cfg_dt_node_exists is set
* to @a true.
*/
uint8_t resolution;
/**
* Oversampling setting to be used for that channel.
* This field is valid only when @a channel_cfg_dt_node_exists is set
* to @a true.
*/
uint8_t oversampling;
};
/** @cond INTERNAL_HIDDEN */
#define ADC_DT_SPEC_STRUCT(ctlr, input) { \
.dev = DEVICE_DT_GET(ctlr), \
.channel_id = input, \
ADC_CHANNEL_CFG_FROM_DT_NODE(\
ADC_CHANNEL_DT_NODE(ctlr, input)) \
}
#define ADC_CHANNEL_DT_NODE(ctlr, input) \
DT_FOREACH_CHILD_VARGS(ctlr, ADC_FOREACH_INPUT, input)
#define ADC_FOREACH_INPUT(node, input) \
IF_ENABLED(IS_EQ(DT_REG_ADDR(node), input), (node))
#define ADC_CHANNEL_CFG_FROM_DT_NODE(node_id) \
IF_ENABLED(DT_NODE_EXISTS(node_id), \
(.channel_cfg_dt_node_exists = true, \
.channel_cfg = ADC_CHANNEL_CFG_DT(node_id), \
.vref_mv = DT_PROP_OR(node_id, zephyr_vref_mv, 0), \
.resolution = DT_PROP_OR(node_id, zephyr_resolution, 0), \
.oversampling = DT_PROP_OR(node_id, zephyr_oversampling, 0),))
/** @endcond */
/**
* @brief Get ADC io-channel information from devicetree by name.
*
* This returns a static initializer for an @p adc_dt_spec structure
* given a devicetree node and a channel name. The node must have
* the "io-channels" property defined.
*
* Example devicetree fragment:
*
* @code{.dts}
* / {
* zephyr,user {
* io-channels = <&adc0 1>, <&adc0 3>;
* io-channel-names = "A0", "A1";
* };
* };
*
* &adc0 {
* #address-cells = <1>;
* #size-cells = <0>;
*
* channel@3 {
* reg = <3>;
* zephyr,gain = "ADC_GAIN_1_5";
* zephyr,reference = "ADC_REF_VDD_1_4";
* zephyr,vref-mv = <750>;
* zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
* zephyr,resolution = <12>;
* zephyr,oversampling = <4>;
* };
* };
* @endcode
*
* Example usage:
*
* @code{.c}
* static const struct adc_dt_spec adc_chan0 =
* ADC_DT_SPEC_GET_BY_NAME(DT_PATH(zephyr_user), a0);
* static const struct adc_dt_spec adc_chan1 =
* ADC_DT_SPEC_GET_BY_NAME(DT_PATH(zephyr_user), a1);
*
* // Initializes 'adc_chan0' to:
* // {
* // .dev = DEVICE_DT_GET(DT_NODELABEL(adc0)),
* // .channel_id = 1,
* // }
* // and 'adc_chan1' to:
* // {
* // .dev = DEVICE_DT_GET(DT_NODELABEL(adc0)),
* // .channel_id = 3,
* // .channel_cfg_dt_node_exists = true,
* // .channel_cfg = {
* // .channel_id = 3,
* // .gain = ADC_GAIN_1_5,
* // .reference = ADC_REF_VDD_1_4,
* // .acquisition_time = ADC_ACQ_TIME_DEFAULT,
* // },
* // .vref_mv = 750,
* // .resolution = 12,
* // .oversampling = 4,
* // }
* @endcode
*
* @param node_id Devicetree node identifier.
* @param name Channel name.
*
* @return Static initializer for an adc_dt_spec structure.
*/
#define ADC_DT_SPEC_GET_BY_NAME(node_id, name) \
ADC_DT_SPEC_STRUCT(DT_IO_CHANNELS_CTLR_BY_NAME(node_id, name), \
DT_IO_CHANNELS_INPUT_BY_NAME(node_id, name))
/** @brief Get ADC io-channel information from a DT_DRV_COMPAT devicetree
* instance by name.
*
* @see ADC_DT_SPEC_GET_BY_NAME()
*
* @param inst DT_DRV_COMPAT instance number
* @param name Channel name.
*
* @return Static initializer for an adc_dt_spec structure.
*/
#define ADC_DT_SPEC_INST_GET_BY_NAME(inst, name) \
ADC_DT_SPEC_GET_BY_NAME(DT_DRV_INST(inst), name)
/**
* @brief Get ADC io-channel information from devicetree.
*
* This returns a static initializer for an @p adc_dt_spec structure
* given a devicetree node and a channel index. The node must have
* the "io-channels" property defined.
*
* Example devicetree fragment:
*
* @code{.dts}
* / {
* zephyr,user {
* io-channels = <&adc0 1>, <&adc0 3>;
* };
* };
*
* &adc0 {
* #address-cells = <1>;
* #size-cells = <0>;
*
* channel@3 {
* reg = <3>;
* zephyr,gain = "ADC_GAIN_1_5";
* zephyr,reference = "ADC_REF_VDD_1_4";
* zephyr,vref-mv = <750>;
* zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
* zephyr,resolution = <12>;
* zephyr,oversampling = <4>;
* };
* };
* @endcode
*
* Example usage:
*
* @code{.c}
* static const struct adc_dt_spec adc_chan0 =
* ADC_DT_SPEC_GET_BY_IDX(DT_PATH(zephyr_user), 0);
* static const struct adc_dt_spec adc_chan1 =
* ADC_DT_SPEC_GET_BY_IDX(DT_PATH(zephyr_user), 1);
*
* // Initializes 'adc_chan0' to:
* // {
* // .dev = DEVICE_DT_GET(DT_NODELABEL(adc0)),
* // .channel_id = 1,
* // }
* // and 'adc_chan1' to:
* // {
* // .dev = DEVICE_DT_GET(DT_NODELABEL(adc0)),
* // .channel_id = 3,
* // .channel_cfg_dt_node_exists = true,
* // .channel_cfg = {
* // .channel_id = 3,
* // .gain = ADC_GAIN_1_5,
* // .reference = ADC_REF_VDD_1_4,
* // .acquisition_time = ADC_ACQ_TIME_DEFAULT,
* // },
* // .vref_mv = 750,
* // .resolution = 12,
* // .oversampling = 4,
* // }
* @endcode
*
* @see ADC_DT_SPEC_GET()
*
* @param node_id Devicetree node identifier.
* @param idx Channel index.
*
* @return Static initializer for an adc_dt_spec structure.
*/
#define ADC_DT_SPEC_GET_BY_IDX(node_id, idx) \
ADC_DT_SPEC_STRUCT(DT_IO_CHANNELS_CTLR_BY_IDX(node_id, idx), \
DT_IO_CHANNELS_INPUT_BY_IDX(node_id, idx))
/** @brief Get ADC io-channel information from a DT_DRV_COMPAT devicetree
* instance.
*
* @see ADC_DT_SPEC_GET_BY_IDX()
*
* @param inst DT_DRV_COMPAT instance number
* @param idx Channel index.
*
* @return Static initializer for an adc_dt_spec structure.
*/
#define ADC_DT_SPEC_INST_GET_BY_IDX(inst, idx) \
ADC_DT_SPEC_GET_BY_IDX(DT_DRV_INST(inst), idx)
/**
* @brief Equivalent to ADC_DT_SPEC_GET_BY_IDX(node_id, 0).
*
* @see ADC_DT_SPEC_GET_BY_IDX()
*
* @param node_id Devicetree node identifier.
*
* @return Static initializer for an adc_dt_spec structure.
*/
#define ADC_DT_SPEC_GET(node_id) ADC_DT_SPEC_GET_BY_IDX(node_id, 0)
/** @brief Equivalent to ADC_DT_SPEC_INST_GET_BY_IDX(inst, 0).
*
* @see ADC_DT_SPEC_GET()
*
* @param inst DT_DRV_COMPAT instance number
*
* @return Static initializer for an adc_dt_spec structure.
*/
#define ADC_DT_SPEC_INST_GET(inst) ADC_DT_SPEC_GET(DT_DRV_INST(inst))
/* Forward declaration of the adc_sequence structure. */
struct adc_sequence;
/**
* @brief Action to be performed after a sampling is done.
*/
enum adc_action {
/** The sequence should be continued normally. */
ADC_ACTION_CONTINUE = 0,
/**
* The sampling should be repeated. New samples or sample should be
* read from the ADC and written in the same place as the recent ones.
*/
ADC_ACTION_REPEAT,
/** The sequence should be finished immediately. */
ADC_ACTION_FINISH,
};
/**
* @brief Type definition of the optional callback function to be called after
* a requested sampling is done.
*
* @param dev Pointer to the device structure for the driver
* instance.
* @param sequence Pointer to the sequence structure that triggered
* the sampling. This parameter points to a copy of
* the structure that was supplied to the call that
* started the sampling sequence, thus it cannot be
* used with the CONTAINER_OF() macro to retrieve
* some other data associated with the sequence.
* Instead, the adc_sequence_options::user_data field
* should be used for such purpose.
*
* @param sampling_index Index (0-65535) of the sampling done.
*
* @returns Action to be performed by the driver. See @ref adc_action.
*/
typedef enum adc_action (*adc_sequence_callback)(const struct device *dev,
const struct adc_sequence *sequence,
uint16_t sampling_index);
/**
* @brief Structure defining additional options for an ADC sampling sequence.
*/
struct adc_sequence_options {
/**
* Interval between consecutive samplings (in microseconds), 0 means
* sample as fast as possible, without involving any timer.
* The accuracy of this interval is dependent on the implementation of
* a given driver. The default routine that handles the intervals uses
* a kernel timer for this purpose, thus, it has the accuracy of the
* kernel's system clock. Particular drivers may use some dedicated
* hardware timers and achieve a better precision.
*/
uint32_t interval_us;
/**
* Callback function to be called after each sampling is done.
* Optional - set to NULL if it is not needed.
*/
adc_sequence_callback callback;
/**
* Pointer to user data. It can be used to associate the sequence
* with any other data that is needed in the callback function.
*/
void *user_data;
/**
* Number of extra samplings to perform (the total number of samplings
* is 1 + extra_samplings).
*/
uint16_t extra_samplings;
};
/**
* @brief Structure defining an ADC sampling sequence.
*/
struct adc_sequence {
/**
* Pointer to a structure defining additional options for the sequence.
* If NULL, the sequence consists of a single sampling.
*/
const struct adc_sequence_options *options;
/**
* Bit-mask indicating the channels to be included in each sampling
* of this sequence.
* All selected channels must be configured with adc_channel_setup()
* before they are used in a sequence.
* The least significant bit corresponds to channel 0.
*/
uint32_t channels;
/**
* Pointer to a buffer where the samples are to be written. Samples
* from subsequent samplings are written sequentially in the buffer.
* The number of samples written for each sampling is determined by
* the number of channels selected in the "channels" field.
* The values written to the buffer represent a sample from each
* selected channel starting from the one with the lowest ID.
* The buffer must be of an appropriate size, taking into account
* the number of selected channels and the ADC resolution used,
* as well as the number of samplings contained in the sequence.
*/
void *buffer;
/**
* Specifies the actual size of the buffer pointed by the "buffer"
* field (in bytes). The driver must ensure that samples are not
* written beyond the limit and it must return an error if the buffer
* turns out to be not large enough to hold all the requested samples.
*/
size_t buffer_size;
/**
* ADC resolution.
* For single-ended channels the sample values are from range:
* 0 .. 2^resolution - 1,
* for differential ones:
* - 2^(resolution-1) .. 2^(resolution-1) - 1.
*/
uint8_t resolution;
/**
* Oversampling setting.
* Each sample is averaged from 2^oversampling conversion results.
* This feature may be unsupported by a given ADC hardware, or in
* a specific mode (e.g. when sampling multiple channels).
*/
uint8_t oversampling;
/**
* Perform calibration before the reading is taken if requested.
*
* The impact of channel configuration on the calibration
* process is specific to the underlying hardware. ADC
* implementations that do not support calibration should
* ignore this flag.
*/
bool calibrate;
};
/**
* @brief Type definition of ADC API function for configuring a channel.
* See adc_channel_setup() for argument descriptions.
*/
typedef int (*adc_api_channel_setup)(const struct device *dev,
const struct adc_channel_cfg *channel_cfg);
/**
* @brief Type definition of ADC API function for setting a read request.
* See adc_read() for argument descriptions.
*/
typedef int (*adc_api_read)(const struct device *dev,
const struct adc_sequence *sequence);
/**
* @brief Type definition of ADC API function for setting an asynchronous
* read request.
* See adc_read_async() for argument descriptions.
*/
typedef int (*adc_api_read_async)(const struct device *dev,
const struct adc_sequence *sequence,
struct k_poll_signal *async);
/**
* @brief ADC driver API
*
* This is the mandatory API any ADC driver needs to expose.
*/
__subsystem struct adc_driver_api {
adc_api_channel_setup channel_setup;
adc_api_read read;
#ifdef CONFIG_ADC_ASYNC
adc_api_read_async read_async;
#endif
uint16_t ref_internal; /* mV */
};
/**
* @brief Configure an ADC channel.
*
* It is required to call this function and configure each channel before it is
* selected for a read request.
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel_cfg Channel configuration.
*
* @retval 0 On success.
* @retval -EINVAL If a parameter with an invalid value has been provided.
*/
__syscall int adc_channel_setup(const struct device *dev,
const struct adc_channel_cfg *channel_cfg);
static inline int z_impl_adc_channel_setup(const struct device *dev,
const struct adc_channel_cfg *channel_cfg)
{
const struct adc_driver_api *api =
(const struct adc_driver_api *)dev->api;
return api->channel_setup(dev, channel_cfg);
}
/**
* @brief Configure an ADC channel from a struct adc_dt_spec.
*
* @param spec ADC specification from Devicetree.
*
* @return A value from adc_channel_setup() or -ENOTSUP if information from
* Devicetree is not valid.
* @see adc_channel_setup()
*/
static inline int adc_channel_setup_dt(const struct adc_dt_spec *spec)
{
if (!spec->channel_cfg_dt_node_exists) {
return -ENOTSUP;
}
return adc_channel_setup(spec->dev, &spec->channel_cfg);
}
/**
* @brief Set a read request.
*
* @param dev Pointer to the device structure for the driver instance.
* @param sequence Structure specifying requested sequence of samplings.
*
* If invoked from user mode, any sequence struct options for callback must
* be NULL.
*
* @retval 0 On success.
* @retval -EINVAL If a parameter with an invalid value has been provided.
* @retval -ENOMEM If the provided buffer is to small to hold the results
* of all requested samplings.
* @retval -ENOTSUP If the requested mode of operation is not supported.
* @retval -EBUSY If another sampling was triggered while the previous one
* was still in progress. This may occur only when samplings
* are done with intervals, and it indicates that the selected
* interval was too small. All requested samples are written
* in the buffer, but at least some of them were taken with
* an extra delay compared to what was scheduled.
*/
__syscall int adc_read(const struct device *dev,
const struct adc_sequence *sequence);
static inline int z_impl_adc_read(const struct device *dev,
const struct adc_sequence *sequence)
{
const struct adc_driver_api *api =
(const struct adc_driver_api *)dev->api;
return api->read(dev, sequence);
}
/**
* @brief Set a read request from a struct adc_dt_spec.
*
* @param spec ADC specification from Devicetree.
* @param sequence Structure specifying requested sequence of samplings.
*
* @return A value from adc_read().
* @see adc_read()
*/
static inline int adc_read_dt(const struct adc_dt_spec *spec,
const struct adc_sequence *sequence)
{
return adc_read(spec->dev, sequence);
}
/**
* @brief Set an asynchronous read request.
*
* @note This function is available only if @kconfig{CONFIG_ADC_ASYNC}
* is selected.
*
* If invoked from user mode, any sequence struct options for callback must
* be NULL.
*
* @param dev Pointer to the device structure for the driver instance.
* @param sequence Structure specifying requested sequence of samplings.
* @param async Pointer to a valid and ready to be signaled struct
* k_poll_signal. (Note: if NULL this function will not notify
* the end of the transaction, and whether it went successfully
* or not).
*
* @returns 0 on success, negative error code otherwise.
* See adc_read() for a list of possible error codes.
*
*/
__syscall int adc_read_async(const struct device *dev,
const struct adc_sequence *sequence,
struct k_poll_signal *async);
#ifdef CONFIG_ADC_ASYNC
static inline int z_impl_adc_read_async(const struct device *dev,
const struct adc_sequence *sequence,
struct k_poll_signal *async)
{
const struct adc_driver_api *api =
(const struct adc_driver_api *)dev->api;
return api->read_async(dev, sequence, async);
}
#endif /* CONFIG_ADC_ASYNC */
/**
* @brief Get the internal reference voltage.
*
* Returns the voltage corresponding to @ref ADC_REF_INTERNAL,
* measured in millivolts.
*
* @return a positive value is the reference voltage value. Returns
* zero if reference voltage information is not available.
*/
static inline uint16_t adc_ref_internal(const struct device *dev)
{
const struct adc_driver_api *api =
(const struct adc_driver_api *)dev->api;
return api->ref_internal;
}
/**
* @brief Convert a raw ADC value to millivolts.
*
* This function performs the necessary conversion to transform a raw
* ADC measurement to a voltage in millivolts.
*
* @param ref_mv the reference voltage used for the measurement, in
* millivolts. This may be from adc_ref_internal() or a known
* external reference.
*
* @param gain the ADC gain configuration used to sample the input
*
* @param resolution the number of bits in the absolute value of the
* sample. For differential sampling this needs to be one less than the
* resolution in struct adc_sequence.
*
* @param valp pointer to the raw measurement value on input, and the
* corresponding millivolt value on successful conversion. If
* conversion fails the stored value is left unchanged.
*
* @retval 0 on successful conversion
* @retval -EINVAL if the gain is not reversible
*/
static inline int adc_raw_to_millivolts(int32_t ref_mv,
enum adc_gain gain,
uint8_t resolution,
int32_t *valp)
{
int32_t adc_mv = *valp * ref_mv;
int ret = adc_gain_invert(gain, &adc_mv);
if (ret == 0) {
*valp = (adc_mv >> resolution);
}
return ret;
}
/**
* @brief Convert a raw ADC value to millivolts using information stored
* in a struct adc_dt_spec.
*
* @param[in] spec ADC specification from Devicetree.
* @param[in,out] valp Pointer to the raw measurement value on input, and the
* corresponding millivolt value on successful conversion. If conversion fails
* the stored value is left unchanged.
*
* @return A value from adc_raw_to_millivolts() or -ENOTSUP if information from
* Devicetree is not valid.
* @see adc_raw_to_millivolts()
*/
static inline int adc_raw_to_millivolts_dt(const struct adc_dt_spec *spec,
int32_t *valp)
{
int32_t vref_mv;
uint8_t resolution;
if (!spec->channel_cfg_dt_node_exists) {
return -ENOTSUP;
}
if (spec->channel_cfg.reference == ADC_REF_INTERNAL) {
vref_mv = (int32_t)adc_ref_internal(spec->dev);
} else {
vref_mv = spec->vref_mv;
}
resolution = spec->resolution;
/*
* For differential channels, one bit less needs to be specified
* for resolution to achieve correct conversion.
*/
if (spec->channel_cfg.differential) {
resolution -= 1U;
}
return adc_raw_to_millivolts(vref_mv, spec->channel_cfg.gain,
resolution, valp);
}
/**
* @brief Initialize a struct adc_sequence from information stored in
* struct adc_dt_spec.
*
* Note that this function only initializes the following fields:
*
* - @ref adc_sequence.channels
* - @ref adc_sequence.resolution
* - @ref adc_sequence.oversampling
*
* Other fields should be initialized by the caller.
*
* @param[in] spec ADC specification from Devicetree.
* @param[out] seq Sequence to initialize.
*
* @retval 0 On success
* @retval -ENOTSUP If @p spec does not have valid channel configuration
*/
static inline int adc_sequence_init_dt(const struct adc_dt_spec *spec,
struct adc_sequence *seq)
{
if (!spec->channel_cfg_dt_node_exists) {
return -ENOTSUP;
}
seq->channels = BIT(spec->channel_id);
seq->resolution = spec->resolution;
seq->oversampling = spec->oversampling;
return 0;
}
/**
* @brief Validate that the ADC device is ready.
*
* @param spec ADC specification from devicetree
*
* @retval true if the ADC device is ready for use and false otherwise.
*/
static inline bool adc_is_ready_dt(const struct adc_dt_spec *spec)
{
return device_is_ready(spec->dev);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/adc.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_ADC_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/adc.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 7,712 |
```objective-c
/*
*
*/
/**
* @file
* @brief Controller Area Network (CAN) driver API.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CAN_H_
#define ZEPHYR_INCLUDE_DRIVERS_CAN_H_
#include <errno.h>
#include <zephyr/types.h>
#include <zephyr/device.h>
#include <zephyr/kernel.h>
#include <string.h>
#include <zephyr/sys_clock.h>
#include <zephyr/sys/util.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief CAN Interface
* @defgroup can_interface CAN Interface
* @since 1.12
* @version 1.1.0
* @ingroup io_interfaces
* @{
*/
/**
* @name CAN frame definitions
* @{
*/
/**
* @brief Bit mask for a standard (11-bit) CAN identifier.
*/
#define CAN_STD_ID_MASK 0x7FFU
/**
* @brief Maximum value for a standard (11-bit) CAN identifier.
*
* @deprecated Use ``CAN_STD_ID_MASK`` instead.
*/
#define CAN_MAX_STD_ID CAN_STD_ID_MASK __DEPRECATED_MACRO
/**
* @brief Bit mask for an extended (29-bit) CAN identifier.
*/
#define CAN_EXT_ID_MASK 0x1FFFFFFFU
/**
* @brief Maximum value for an extended (29-bit) CAN identifier.
*
* @deprecated Use ``CAN_EXT_ID_MASK`` instead.
*/
#define CAN_MAX_EXT_ID CAN_EXT_ID_MASK __DEPRECATED_MACRO
/**
* @brief Maximum data length code for CAN 2.0A/2.0B.
*/
#define CAN_MAX_DLC 8U
/**
* @brief Maximum data length code for CAN FD.
*/
#define CANFD_MAX_DLC 15U
/**
* @cond INTERNAL_HIDDEN
* Internally calculated maximum data length
*/
#ifndef CONFIG_CAN_FD_MODE
#define CAN_MAX_DLEN 8U
#else
#define CAN_MAX_DLEN 64U
#endif /* CONFIG_CAN_FD_MODE */
/** @endcond */
/** @} */
/**
* @name CAN controller mode flags
* @anchor CAN_MODE_FLAGS
*
* @{
*/
/** Normal mode. */
#define CAN_MODE_NORMAL 0
/** Controller is in loopback mode (receives own frames). */
#define CAN_MODE_LOOPBACK BIT(0)
/** Controller is not allowed to send dominant bits. */
#define CAN_MODE_LISTENONLY BIT(1)
/** Controller allows transmitting/receiving CAN FD frames. */
#define CAN_MODE_FD BIT(2)
/** Controller does not retransmit in case of lost arbitration or missing ACK */
#define CAN_MODE_ONE_SHOT BIT(3)
/** Controller uses triple sampling mode */
#define CAN_MODE_3_SAMPLES BIT(4)
/** Controller requires manual recovery after entering bus-off state */
#define CAN_MODE_MANUAL_RECOVERY BIT(5)
/** @} */
/**
* @brief Provides a type to hold CAN controller configuration flags.
*
* The lower 24 bits are reserved for common CAN controller mode flags. The upper 8 bits are
* reserved for CAN controller/driver specific flags.
*
* @see @ref CAN_MODE_FLAGS.
*/
typedef uint32_t can_mode_t;
/**
* @brief Defines the state of the CAN controller
*/
enum can_state {
/** Error-active state (RX/TX error count < 96). */
CAN_STATE_ERROR_ACTIVE,
/** Error-warning state (RX/TX error count < 128). */
CAN_STATE_ERROR_WARNING,
/** Error-passive state (RX/TX error count < 256). */
CAN_STATE_ERROR_PASSIVE,
/** Bus-off state (RX/TX error count >= 256). */
CAN_STATE_BUS_OFF,
/** CAN controller is stopped and does not participate in CAN communication. */
CAN_STATE_STOPPED,
};
/**
* @name CAN frame flags
* @anchor CAN_FRAME_FLAGS
*
* @{
*/
/** Frame uses extended (29-bit) CAN ID */
#define CAN_FRAME_IDE BIT(0)
/** Frame is a Remote Transmission Request (RTR) */
#define CAN_FRAME_RTR BIT(1)
/** Frame uses CAN FD format (FDF) */
#define CAN_FRAME_FDF BIT(2)
/** Frame uses CAN FD Baud Rate Switch (BRS). Only valid in combination with ``CAN_FRAME_FDF``. */
#define CAN_FRAME_BRS BIT(3)
/** CAN FD Error State Indicator (ESI). Indicates that the transmitting node is in error-passive
* state. Only valid in combination with ``CAN_FRAME_FDF``.
*/
#define CAN_FRAME_ESI BIT(4)
/** @} */
/**
* @brief CAN frame structure
*/
struct can_frame {
/** Standard (11-bit) or extended (29-bit) CAN identifier. */
uint32_t id;
/** Data Length Code (DLC) indicating data length in bytes. */
uint8_t dlc;
/** Flags. @see @ref CAN_FRAME_FLAGS. */
uint8_t flags;
#if defined(CONFIG_CAN_RX_TIMESTAMP) || defined(__DOXYGEN__)
/** Captured value of the free-running timer in the CAN controller when
* this frame was received. The timer is incremented every bit time and
* captured at the start of frame bit (SOF).
*
* @note @kconfig{CONFIG_CAN_RX_TIMESTAMP} must be selected for this
* field to be available.
*/
uint16_t timestamp;
#else
/** @cond INTERNAL_HIDDEN */
/** Padding. */
uint16_t reserved;
/** @endcond */
#endif
/** The frame payload data. */
union {
/** Payload data accessed as unsigned 8 bit values. */
uint8_t data[CAN_MAX_DLEN];
/** Payload data accessed as unsigned 32 bit values. */
uint32_t data_32[DIV_ROUND_UP(CAN_MAX_DLEN, sizeof(uint32_t))];
};
};
/**
* @name CAN filter flags
* @anchor CAN_FILTER_FLAGS
*
* @{
*/
/** Filter matches frames with extended (29-bit) CAN IDs */
#define CAN_FILTER_IDE BIT(0)
/** @} */
/**
* @brief CAN filter structure
*/
struct can_filter {
/** CAN identifier to match. */
uint32_t id;
/** CAN identifier matching mask. If a bit in this mask is 0, the value
* of the corresponding bit in the ``id`` field is ignored by the filter.
*/
uint32_t mask;
/** Flags. @see @ref CAN_FILTER_FLAGS. */
uint8_t flags;
};
/**
* @brief CAN controller error counters
*/
struct can_bus_err_cnt {
/** Value of the CAN controller transmit error counter. */
uint8_t tx_err_cnt;
/** Value of the CAN controller receive error counter. */
uint8_t rx_err_cnt;
};
/**
* @brief CAN bus timing structure
*
* This struct is used to pass bus timing values to the configuration and
* bitrate calculation functions.
*
* The propagation segment represents the time of the signal propagation. Phase
* segment 1 and phase segment 2 define the sampling point. The ``prop_seg`` and
* ``phase_seg1`` values affect the sampling point in the same way and some
* controllers only have a register for the sum of those two. The sync segment
* always has a length of 1 time quantum (see below).
*
* @code{.text}
*
* +---------+----------+------------+------------+
* |sync_seg | prop_seg | phase_seg1 | phase_seg2 |
* +---------+----------+------------+------------+
* ^
* Sampling-Point
*
* @endcode
*
* 1 time quantum (tq) has the length of 1/(core_clock / prescaler). The bitrate
* is defined by the core clock divided by the prescaler and the sum of the
* segments:
*
* br = (core_clock / prescaler) / (1 + prop_seg + phase_seg1 + phase_seg2)
*
* The Synchronization Jump Width (SJW) defines the amount of time quanta the
* sample point can be moved. The sample point is moved when resynchronization
* is needed.
*/
struct can_timing {
/** Synchronisation jump width. */
uint16_t sjw;
/** Propagation segment. */
uint16_t prop_seg;
/** Phase segment 1. */
uint16_t phase_seg1;
/** Phase segment 2. */
uint16_t phase_seg2;
/** Prescaler value. */
uint16_t prescaler;
};
/**
* @brief Defines the application callback handler function signature
*
* @param dev Pointer to the device structure for the driver instance.
* @param error Status of the performed send operation. See the list of
* return values for @a can_send() for value descriptions.
* @param user_data User data provided when the frame was sent.
*/
typedef void (*can_tx_callback_t)(const struct device *dev, int error, void *user_data);
/**
* @brief Defines the application callback handler function signature for receiving.
*
* @param dev Pointer to the device structure for the driver instance.
* @param frame Received frame.
* @param user_data User data provided when the filter was added.
*/
typedef void (*can_rx_callback_t)(const struct device *dev, struct can_frame *frame,
void *user_data);
/**
* @brief Defines the state change callback handler function signature
*
* @param dev Pointer to the device structure for the driver instance.
* @param state State of the CAN controller.
* @param err_cnt CAN controller error counter values.
* @param user_data User data provided the callback was set.
*/
typedef void (*can_state_change_callback_t)(const struct device *dev,
enum can_state state,
struct can_bus_err_cnt err_cnt,
void *user_data);
/**
* @cond INTERNAL_HIDDEN
*
* For internal driver use only, skip these in public documentation.
*/
/**
* @brief Calculate Transmitter Delay Compensation Offset from data phase timing parameters.
*
* Calculates the TDC Offset in minimum time quanta (mtq) using the sample point and CAN core clock
* prescaler specified by a set of data phase timing parameters.
*
* The result is clamped to the minimum/maximum supported TDC Offset values provided.
*
* @param _timing_data Pointer to data phase timing parameters.
* @param _tdco_min Minimum supported TDC Offset value in mtq.
* @param _tdco_max Maximum supported TDC Offset value in mtq.
* @return Calculated TDC Offset value in mtq.
*/
#define CAN_CALC_TDCO(_timing_data, _tdco_min, _tdco_max) \
CLAMP((1U + _timing_data->prop_seg + _timing_data->phase_seg1) * _timing_data->prescaler, \
_tdco_min, _tdco_max)
/**
* @brief Common CAN controller driver configuration.
*
* This structure is common to all CAN controller drivers and is expected to be the first element in
* the object pointed to by the config field in the device structure.
*/
struct can_driver_config {
/** Pointer to the device structure for the associated CAN transceiver device or NULL. */
const struct device *phy;
/** The minimum bitrate supported by the CAN controller/transceiver combination. */
uint32_t min_bitrate;
/** The maximum bitrate supported by the CAN controller/transceiver combination. */
uint32_t max_bitrate;
/** Initial CAN classic/CAN FD arbitration phase bitrate. */
uint32_t bitrate;
/** Initial CAN classic/CAN FD arbitration phase sample point in permille. */
uint16_t sample_point;
#ifdef CONFIG_CAN_FD_MODE
/** Initial CAN FD data phase sample point in permille. */
uint16_t sample_point_data;
/** Initial CAN FD data phase bitrate. */
uint32_t bitrate_data;
#endif /* CONFIG_CAN_FD_MODE */
};
/**
* @brief Static initializer for @p can_driver_config struct
*
* @param node_id Devicetree node identifier
* @param _min_bitrate minimum bitrate supported by the CAN controller
* @param _max_bitrate maximum bitrate supported by the CAN controller
*/
#define CAN_DT_DRIVER_CONFIG_GET(node_id, _min_bitrate, _max_bitrate) \
{ \
.phy = DEVICE_DT_GET_OR_NULL(DT_PHANDLE(node_id, phys)), \
.min_bitrate = DT_CAN_TRANSCEIVER_MIN_BITRATE(node_id, _min_bitrate), \
.max_bitrate = DT_CAN_TRANSCEIVER_MAX_BITRATE(node_id, _max_bitrate), \
.bitrate = DT_PROP_OR(node_id, bitrate, \
DT_PROP_OR(node_id, bus_speed, CONFIG_CAN_DEFAULT_BITRATE)), \
.sample_point = DT_PROP_OR(node_id, sample_point, 0), \
IF_ENABLED(CONFIG_CAN_FD_MODE, \
(.bitrate_data = DT_PROP_OR(node_id, bitrate_data, \
DT_PROP_OR(node_id, bus_speed_data, CONFIG_CAN_DEFAULT_BITRATE_DATA)), \
.sample_point_data = DT_PROP_OR(node_id, sample_point_data, 0),)) \
}
/**
* @brief Static initializer for @p can_driver_config struct from DT_DRV_COMPAT instance
*
* @param inst DT_DRV_COMPAT instance number
* @param _min_bitrate minimum bitrate supported by the CAN controller
* @param _max_bitrate maximum bitrate supported by the CAN controller
* @see CAN_DT_DRIVER_CONFIG_GET()
*/
#define CAN_DT_DRIVER_CONFIG_INST_GET(inst, _min_bitrate, _max_bitrate) \
CAN_DT_DRIVER_CONFIG_GET(DT_DRV_INST(inst), _min_bitrate, _max_bitrate)
/**
* @brief Common CAN controller driver data.
*
* This structure is common to all CAN controller drivers and is expected to be the first element in
* the driver's struct driver_data declaration.
*/
struct can_driver_data {
/** Current CAN controller mode. */
can_mode_t mode;
/** True if the CAN controller is started, false otherwise. */
bool started;
/** State change callback function pointer or NULL. */
can_state_change_callback_t state_change_cb;
/** State change callback user data pointer or NULL. */
void *state_change_cb_user_data;
};
/**
* @brief Callback API upon setting CAN bus timing
* See @a can_set_timing() for argument description
*/
typedef int (*can_set_timing_t)(const struct device *dev,
const struct can_timing *timing);
/**
* @brief Optional callback API upon setting CAN FD bus timing for the data phase.
* See @a can_set_timing_data() for argument description
*/
typedef int (*can_set_timing_data_t)(const struct device *dev,
const struct can_timing *timing_data);
/**
* @brief Callback API upon getting CAN controller capabilities
* See @a can_get_capabilities() for argument description
*/
typedef int (*can_get_capabilities_t)(const struct device *dev, can_mode_t *cap);
/**
* @brief Callback API upon starting CAN controller
* See @a can_start() for argument description
*/
typedef int (*can_start_t)(const struct device *dev);
/**
* @brief Callback API upon stopping CAN controller
* See @a can_stop() for argument description
*/
typedef int (*can_stop_t)(const struct device *dev);
/**
* @brief Callback API upon setting CAN controller mode
* See @a can_set_mode() for argument description
*/
typedef int (*can_set_mode_t)(const struct device *dev, can_mode_t mode);
/**
* @brief Callback API upon sending a CAN frame
* See @a can_send() for argument description
*
* @note From a driver perspective `callback` will never be `NULL` as a default callback will be
* provided if none is provided by the caller. This allows for simplifying the driver handling.
*/
typedef int (*can_send_t)(const struct device *dev,
const struct can_frame *frame,
k_timeout_t timeout, can_tx_callback_t callback,
void *user_data);
/**
* @brief Callback API upon adding an RX filter
* See @a can_add_rx_callback() for argument description
*/
typedef int (*can_add_rx_filter_t)(const struct device *dev,
can_rx_callback_t callback,
void *user_data,
const struct can_filter *filter);
/**
* @brief Callback API upon removing an RX filter
* See @a can_remove_rx_filter() for argument description
*/
typedef void (*can_remove_rx_filter_t)(const struct device *dev, int filter_id);
/**
* @brief Optional callback API upon manually recovering the CAN controller from bus-off state
* See @a can_recover() for argument description
*/
typedef int (*can_recover_t)(const struct device *dev, k_timeout_t timeout);
/**
* @brief Callback API upon getting the CAN controller state
* See @a can_get_state() for argument description
*/
typedef int (*can_get_state_t)(const struct device *dev, enum can_state *state,
struct can_bus_err_cnt *err_cnt);
/**
* @brief Callback API upon setting a state change callback
* See @a can_set_state_change_callback() for argument description
*/
typedef void(*can_set_state_change_callback_t)(const struct device *dev,
can_state_change_callback_t callback,
void *user_data);
/**
* @brief Callback API upon getting the CAN core clock rate
* See @a can_get_core_clock() for argument description
*/
typedef int (*can_get_core_clock_t)(const struct device *dev, uint32_t *rate);
/**
* @brief Optional callback API upon getting the maximum number of concurrent CAN RX filters
* See @a can_get_max_filters() for argument description
*/
typedef int (*can_get_max_filters_t)(const struct device *dev, bool ide);
__subsystem struct can_driver_api {
can_get_capabilities_t get_capabilities;
can_start_t start;
can_stop_t stop;
can_set_mode_t set_mode;
can_set_timing_t set_timing;
can_send_t send;
can_add_rx_filter_t add_rx_filter;
can_remove_rx_filter_t remove_rx_filter;
#if defined(CONFIG_CAN_MANUAL_RECOVERY_MODE) || defined(__DOXYGEN__)
can_recover_t recover;
#endif /* CONFIG_CAN_MANUAL_RECOVERY_MODE */
can_get_state_t get_state;
can_set_state_change_callback_t set_state_change_callback;
can_get_core_clock_t get_core_clock;
can_get_max_filters_t get_max_filters;
/* Min values for the timing registers */
struct can_timing timing_min;
/* Max values for the timing registers */
struct can_timing timing_max;
#if defined(CONFIG_CAN_FD_MODE) || defined(__DOXYGEN__)
can_set_timing_data_t set_timing_data;
/* Min values for the timing registers during the data phase */
struct can_timing timing_data_min;
/* Max values for the timing registers during the data phase */
struct can_timing timing_data_max;
#endif /* CONFIG_CAN_FD_MODE */
};
/** @endcond */
#if defined(CONFIG_CAN_STATS) || defined(__DOXYGEN__)
#include <zephyr/stats/stats.h>
/** @cond INTERNAL_HIDDEN */
STATS_SECT_START(can)
STATS_SECT_ENTRY32(bit_error)
STATS_SECT_ENTRY32(bit0_error)
STATS_SECT_ENTRY32(bit1_error)
STATS_SECT_ENTRY32(stuff_error)
STATS_SECT_ENTRY32(crc_error)
STATS_SECT_ENTRY32(form_error)
STATS_SECT_ENTRY32(ack_error)
STATS_SECT_ENTRY32(rx_overrun)
STATS_SECT_END;
STATS_NAME_START(can)
STATS_NAME(can, bit_error)
STATS_NAME(can, bit0_error)
STATS_NAME(can, bit1_error)
STATS_NAME(can, stuff_error)
STATS_NAME(can, crc_error)
STATS_NAME(can, form_error)
STATS_NAME(can, ack_error)
STATS_NAME(can, rx_overrun)
STATS_NAME_END(can);
/** @endcond */
/**
* @brief CAN specific device state which allows for CAN device class specific
* additions
*/
struct can_device_state {
/** Common device state. */
struct device_state devstate;
/** CAN device statistics */
struct stats_can stats;
};
/** @cond INTERNAL_HIDDEN */
/**
* @brief Get pointer to CAN statistics structure
*/
#define Z_CAN_GET_STATS(dev_) \
CONTAINER_OF(dev_->state, struct can_device_state, devstate)->stats
/** @endcond */
/**
* @brief Increment the bit error counter for a CAN device
*
* The bit error counter is incremented when the CAN controller is unable to
* transmit either a dominant or a recessive bit.
*
* @note This error counter should only be incremented if the CAN controller is unable to
* distinguish between failure to transmit a dominant versus failure to transmit a recessive bit. If
* the CAN controller supports distinguishing between the two, the `bit0` or `bit1` error counter
* shall be incremented instead.
*
* @see CAN_STATS_BIT0_ERROR_INC()
* @see CAN_STATS_BIT1_ERROR_INC()
*
* @param dev_ Pointer to the device structure for the driver instance.
*/
#define CAN_STATS_BIT_ERROR_INC(dev_) \
STATS_INC(Z_CAN_GET_STATS(dev_), bit_error)
/**
* @brief Increment the bit0 error counter for a CAN device
*
* The bit0 error counter is incremented when the CAN controller is unable to
* transmit a dominant bit.
*
* Incrementing this counter will automatically increment the bit error counter.
* @see CAN_STATS_BIT_ERROR_INC()
*
* @param dev_ Pointer to the device structure for the driver instance.
*/
#define CAN_STATS_BIT0_ERROR_INC(dev_) \
do { \
STATS_INC(Z_CAN_GET_STATS(dev_), bit0_error); \
CAN_STATS_BIT_ERROR_INC(dev_); \
} while (0)
/**
* @brief Increment the bit1 (recessive) error counter for a CAN device
*
* The bit1 error counter is incremented when the CAN controller is unable to
* transmit a recessive bit.
*
* Incrementing this counter will automatically increment the bit error counter.
* @see CAN_STATS_BIT_ERROR_INC()
*
* @param dev_ Pointer to the device structure for the driver instance.
*/
#define CAN_STATS_BIT1_ERROR_INC(dev_) \
do { \
STATS_INC(Z_CAN_GET_STATS(dev_), bit1_error); \
CAN_STATS_BIT_ERROR_INC(dev_); \
} while (0)
/**
* @brief Increment the stuffing error counter for a CAN device
*
* The stuffing error counter is incremented when the CAN controller detects a
* bit stuffing error.
*
* @param dev_ Pointer to the device structure for the driver instance.
*/
#define CAN_STATS_STUFF_ERROR_INC(dev_) \
STATS_INC(Z_CAN_GET_STATS(dev_), stuff_error)
/**
* @brief Increment the CRC error counter for a CAN device
*
* The CRC error counter is incremented when the CAN controller detects a frame
* with an invalid CRC.
*
* @param dev_ Pointer to the device structure for the driver instance.
*/
#define CAN_STATS_CRC_ERROR_INC(dev_) \
STATS_INC(Z_CAN_GET_STATS(dev_), crc_error)
/**
* @brief Increment the form error counter for a CAN device
*
* The form error counter is incremented when the CAN controller detects a
* fixed-form bit field containing illegal bits.
*
* @param dev_ Pointer to the device structure for the driver instance.
*/
#define CAN_STATS_FORM_ERROR_INC(dev_) \
STATS_INC(Z_CAN_GET_STATS(dev_), form_error)
/**
* @brief Increment the acknowledge error counter for a CAN device
*
* The acknowledge error counter is incremented when the CAN controller does not
* monitor a dominant bit in the ACK slot.
*
* @param dev_ Pointer to the device structure for the driver instance.
*/
#define CAN_STATS_ACK_ERROR_INC(dev_) \
STATS_INC(Z_CAN_GET_STATS(dev_), ack_error)
/**
* @brief Increment the RX overrun counter for a CAN device
*
* The RX overrun counter is incremented when the CAN controller receives a CAN
* frame matching an installed filter but lacks the capacity to store it (either
* due to an already full RX mailbox or a full RX FIFO).
*
* @param dev_ Pointer to the device structure for the driver instance.
*/
#define CAN_STATS_RX_OVERRUN_INC(dev_) \
STATS_INC(Z_CAN_GET_STATS(dev_), rx_overrun)
/**
* @brief Zero all statistics for a CAN device
*
* The driver is responsible for resetting the statistics before starting the CAN
* controller.
*
* @param dev_ Pointer to the device structure for the driver instance.
*/
#define CAN_STATS_RESET(dev_) \
stats_reset(&(Z_CAN_GET_STATS(dev_).s_hdr))
/** @cond INTERNAL_HIDDEN */
/**
* @brief Define a statically allocated and section assigned CAN device state
*/
#define Z_CAN_DEVICE_STATE_DEFINE(dev_id) \
static struct can_device_state Z_DEVICE_STATE_NAME(dev_id) \
__attribute__((__section__(".z_devstate")))
/**
* @brief Define a CAN device init wrapper function
*
* This does device instance specific initialization of common data (such as stats)
* and calls the given init_fn
*/
#define Z_CAN_INIT_FN(dev_id, init_fn) \
static inline int UTIL_CAT(dev_id, _init)(const struct device *dev) \
{ \
struct can_device_state *state = \
CONTAINER_OF(dev->state, struct can_device_state, devstate); \
stats_init(&state->stats.s_hdr, STATS_SIZE_32, 8, \
STATS_NAME_INIT_PARMS(can)); \
stats_register(dev->name, &(state->stats.s_hdr)); \
if (!is_null_no_warn(init_fn)) { \
return init_fn(dev); \
} \
\
return 0; \
}
/** @endcond */
/**
* @brief Like DEVICE_DT_DEFINE() with CAN device specifics.
*
* @details Defines a device which implements the CAN API. May generate a custom
* device_state container struct and init_fn wrapper when needed depending on
* @kconfig{CONFIG_CAN_STATS}.
*
* @param node_id The devicetree node identifier.
* @param init_fn Name of the init function of the driver.
* @param pm PM device resources reference (NULL if device does not use PM).
* @param data Pointer to the device's private data.
* @param config The address to the structure containing the configuration
* information for this instance of the driver.
* @param level The initialization level. See SYS_INIT() for
* details.
* @param prio Priority within the selected initialization level. See
* SYS_INIT() for details.
* @param api Provides an initial pointer to the API function struct
* used by the driver. Can be NULL.
*/
#define CAN_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
prio, api, ...) \
Z_CAN_DEVICE_STATE_DEFINE(Z_DEVICE_DT_DEV_ID(node_id)); \
Z_CAN_INIT_FN(Z_DEVICE_DT_DEV_ID(node_id), init_fn) \
Z_DEVICE_DEFINE(node_id, Z_DEVICE_DT_DEV_ID(node_id), \
DEVICE_DT_NAME(node_id), \
&UTIL_CAT(Z_DEVICE_DT_DEV_ID(node_id), _init), \
pm, data, config, level, prio, api, \
&(Z_DEVICE_STATE_NAME(Z_DEVICE_DT_DEV_ID(node_id)).devstate), \
__VA_ARGS__)
#else /* CONFIG_CAN_STATS */
#define CAN_STATS_BIT_ERROR_INC(dev_)
#define CAN_STATS_BIT0_ERROR_INC(dev_)
#define CAN_STATS_BIT1_ERROR_INC(dev_)
#define CAN_STATS_STUFF_ERROR_INC(dev_)
#define CAN_STATS_CRC_ERROR_INC(dev_)
#define CAN_STATS_FORM_ERROR_INC(dev_)
#define CAN_STATS_ACK_ERROR_INC(dev_)
#define CAN_STATS_RX_OVERRUN_INC(dev_)
#define CAN_STATS_RESET(dev_)
#define CAN_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
prio, api, ...) \
DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
prio, api, __VA_ARGS__)
#endif /* CONFIG_CAN_STATS */
/**
* @brief Like CAN_DEVICE_DT_DEFINE() for an instance of a DT_DRV_COMPAT compatible
*
* @param inst Instance number. This is replaced by <tt>DT_DRV_COMPAT(inst)</tt>
* in the call to CAN_DEVICE_DT_DEFINE().
* @param ... Other parameters as expected by CAN_DEVICE_DT_DEFINE().
*/
#define CAN_DEVICE_DT_INST_DEFINE(inst, ...) \
CAN_DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
/**
* @name CAN controller configuration
*
* @{
*/
/**
* @brief Get the CAN core clock rate
*
* Returns the CAN core clock rate. One minimum time quantum (mtq) is 1/(core clock rate). The CAN
* core clock can be further divided by the CAN clock prescaler (see the @a can_timing struct),
* providing the time quantum (tq).
*
* @param dev Pointer to the device structure for the driver instance.
* @param[out] rate CAN core clock rate in Hz.
*
* @return 0 on success, or a negative error code on error
*/
__syscall int can_get_core_clock(const struct device *dev, uint32_t *rate);
static inline int z_impl_can_get_core_clock(const struct device *dev, uint32_t *rate)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return api->get_core_clock(dev, rate);
}
/**
* @brief Get minimum supported bitrate
*
* Get the minimum supported bitrate for the CAN controller/transceiver combination.
*
* @param dev Pointer to the device structure for the driver instance.
* @return Minimum supported bitrate in bits/s
*/
__syscall uint32_t can_get_bitrate_min(const struct device *dev);
static inline uint32_t z_impl_can_get_bitrate_min(const struct device *dev)
{
const struct can_driver_config *common = (const struct can_driver_config *)dev->config;
return common->min_bitrate;
}
/**
* @brief Get minimum supported bitrate
*
* Get the minimum supported bitrate for the CAN controller/transceiver combination.
*
* @deprecated Use @a can_get_bitrate_min() instead.
*
* @param dev Pointer to the device structure for the driver instance.
* @param[out] min_bitrate Minimum supported bitrate in bits/s
*
* @retval -EIO General input/output error.
* @retval -ENOSYS If this function is not implemented by the driver.
*/
__deprecated static inline int can_get_min_bitrate(const struct device *dev, uint32_t *min_bitrate)
{
*min_bitrate = can_get_bitrate_min(dev);
return 0;
}
/**
* @brief Get maximum supported bitrate
*
* Get the maximum supported bitrate for the CAN controller/transceiver combination.
*
* @param dev Pointer to the device structure for the driver instance.
* @return Maximum supported bitrate in bits/s
*/
__syscall uint32_t can_get_bitrate_max(const struct device *dev);
static inline uint32_t z_impl_can_get_bitrate_max(const struct device *dev)
{
const struct can_driver_config *common = (const struct can_driver_config *)dev->config;
return common->max_bitrate;
}
/**
* @brief Get maximum supported bitrate
*
* Get the maximum supported bitrate for the CAN controller/transceiver combination.
*
* @deprecated Use @a can_get_bitrate_max() instead.
*
* @param dev Pointer to the device structure for the driver instance.
* @param[out] max_bitrate Maximum supported bitrate in bits/s
*
* @retval 0 If successful.
* @retval -EIO General input/output error.
* @retval -ENOSYS If this function is not implemented by the driver.
*/
__deprecated static inline int can_get_max_bitrate(const struct device *dev, uint32_t *max_bitrate)
{
*max_bitrate = can_get_bitrate_max(dev);
return 0;
}
/**
* @brief Get the minimum supported timing parameter values.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @return Pointer to the minimum supported timing parameter values.
*/
__syscall const struct can_timing *can_get_timing_min(const struct device *dev);
static inline const struct can_timing *z_impl_can_get_timing_min(const struct device *dev)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return &api->timing_min;
}
/**
* @brief Get the maximum supported timing parameter values.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @return Pointer to the maximum supported timing parameter values.
*/
__syscall const struct can_timing *can_get_timing_max(const struct device *dev);
static inline const struct can_timing *z_impl_can_get_timing_max(const struct device *dev)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return &api->timing_max;
}
/**
* @brief Calculate timing parameters from bitrate and sample point
*
* Calculate the timing parameters from a given bitrate in bits/s and the
* sampling point in permill (1/1000) of the entire bit time. The bitrate must
* always match perfectly. If no result can be reached for the given parameters,
* -EINVAL is returned.
*
* If the sample point is set to 0, this function defaults to a sample point of 75.0%
* for bitrates over 800 kbit/s, 80.0% for bitrates over 500 kbit/s, and 87.5% for
* all other bitrates.
*
* @note The requested ``sample_pnt`` will not always be matched perfectly. The
* algorithm calculates the best possible match.
*
* @param dev Pointer to the device structure for the driver instance.
* @param[out] res Result is written into the @a can_timing struct provided.
* @param bitrate Target bitrate in bits/s.
* @param sample_pnt Sample point in permille of the entire bit time or 0 for
* automatic sample point location.
*
* @retval 0 or positive sample point error on success.
* @retval -EINVAL if the requested bitrate or sample point is out of range.
* @retval -ENOTSUP if the requested bitrate is not supported.
* @retval -EIO if @a can_get_core_clock() is not available.
*/
__syscall int can_calc_timing(const struct device *dev, struct can_timing *res,
uint32_t bitrate, uint16_t sample_pnt);
/**
* @brief Get the minimum supported timing parameter values for the data phase.
*
* Same as @a can_get_timing_min() but for the minimum values for the data phase.
*
* @note @kconfig{CONFIG_CAN_FD_MODE} must be selected for this function to be
* available.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @return Pointer to the minimum supported timing parameter values, or NULL if
* CAN FD support is not implemented by the driver.
*/
__syscall const struct can_timing *can_get_timing_data_min(const struct device *dev);
#ifdef CONFIG_CAN_FD_MODE
static inline const struct can_timing *z_impl_can_get_timing_data_min(const struct device *dev)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return &api->timing_data_min;
}
#endif /* CONFIG_CAN_FD_MODE */
/**
* @brief Get the maximum supported timing parameter values for the data phase.
*
* Same as @a can_get_timing_max() but for the maximum values for the data phase.
*
* @note @kconfig{CONFIG_CAN_FD_MODE} must be selected for this function to be
* available.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @return Pointer to the maximum supported timing parameter values, or NULL if
* CAN FD support is not implemented by the driver.
*/
__syscall const struct can_timing *can_get_timing_data_max(const struct device *dev);
#ifdef CONFIG_CAN_FD_MODE
static inline const struct can_timing *z_impl_can_get_timing_data_max(const struct device *dev)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return &api->timing_data_max;
}
#endif /* CONFIG_CAN_FD_MODE */
/**
* @brief Calculate timing parameters for the data phase
*
* Same as @a can_calc_timing() but with the maximum and minimum values from the
* data phase.
*
* @note @kconfig{CONFIG_CAN_FD_MODE} must be selected for this function to be
* available.
*
* @param dev Pointer to the device structure for the driver instance.
* @param[out] res Result is written into the @a can_timing struct provided.
* @param bitrate Target bitrate for the data phase in bits/s
* @param sample_pnt Sample point for the data phase in permille of the entire bit
* time or 0 for automatic sample point location.
*
* @retval 0 or positive sample point error on success.
* @retval -EINVAL if the requested bitrate or sample point is out of range.
* @retval -ENOTSUP if the requested bitrate is not supported.
* @retval -EIO if @a can_get_core_clock() is not available.
*/
__syscall int can_calc_timing_data(const struct device *dev, struct can_timing *res,
uint32_t bitrate, uint16_t sample_pnt);
/**
* @brief Configure the bus timing for the data phase of a CAN FD controller.
*
* @note @kconfig{CONFIG_CAN_FD_MODE} must be selected for this function to be
* available.
*
* @see can_set_timing()
*
* @param dev Pointer to the device structure for the driver instance.
* @param timing_data Bus timings for data phase
*
* @retval 0 If successful.
* @retval -EBUSY if the CAN controller is not in stopped state.
* @retval -EIO General input/output error, failed to configure device.
* @retval -ENOTSUP if the timing parameters are not supported by the driver.
* @retval -ENOSYS if CAN FD support is not implemented by the driver.
*/
__syscall int can_set_timing_data(const struct device *dev,
const struct can_timing *timing_data);
/**
* @brief Set the bitrate for the data phase of the CAN FD controller
*
* CAN in Automation (CiA) 301 v4.2.0 recommends a sample point location of
* 87.5% percent for all bitrates. However, some CAN controllers have
* difficulties meeting this for higher bitrates.
*
* This function defaults to using a sample point of 75.0% for bitrates over 800
* kbit/s, 80.0% for bitrates over 500 kbit/s, and 87.5% for all other
* bitrates. This is in line with the sample point locations used by the Linux
* kernel.
*
* @note @kconfig{CONFIG_CAN_FD_MODE} must be selected for this function to be
* available.
*
* @see can_set_bitrate()
* @param dev Pointer to the device structure for the driver instance.
* @param bitrate_data Desired data phase bitrate.
*
* @retval 0 If successful.
* @retval -EBUSY if the CAN controller is not in stopped state.
* @retval -EINVAL if the requested bitrate is out of range.
* @retval -ENOTSUP if the requested bitrate not supported by the CAN controller/transceiver
* combination.
* @retval -ERANGE if the resulting sample point is off by more than +/- 5%.
* @retval -EIO General input/output error, failed to set bitrate.
*/
__syscall int can_set_bitrate_data(const struct device *dev, uint32_t bitrate_data);
/**
* @brief Fill in the prescaler value for a given bitrate and timing
*
* Fill the prescaler value in the timing struct. The sjw, prop_seg, phase_seg1
* and phase_seg2 must be given.
*
* The returned bitrate error is remainder of the division of the clock rate by
* the bitrate times the timing segments.
*
* @deprecated This function allows for bitrate errors, but bitrate errors between nodes on the same
* network leads to them drifting apart after the start-of-frame (SOF) synchronization
* has taken place.
*
* @param dev Pointer to the device structure for the driver instance.
* @param timing Result is written into the can_timing struct provided.
* @param bitrate Target bitrate.
*
* @retval 0 or positive bitrate error.
* @retval Negative error code on error.
*/
__deprecated int can_calc_prescaler(const struct device *dev, struct can_timing *timing,
uint32_t bitrate);
/**
* @brief Configure the bus timing of a CAN controller.
*
* @see can_set_timing_data()
*
* @param dev Pointer to the device structure for the driver instance.
* @param timing Bus timings.
*
* @retval 0 If successful.
* @retval -EBUSY if the CAN controller is not in stopped state.
* @retval -ENOTSUP if the timing parameters are not supported by the driver.
* @retval -EIO General input/output error, failed to configure device.
*/
__syscall int can_set_timing(const struct device *dev,
const struct can_timing *timing);
/**
* @brief Get the supported modes of the CAN controller
*
* The returned capabilities may not necessarily be supported at the same time (e.g. some CAN
* controllers support both ``CAN_MODE_LOOPBACK`` and ``CAN_MODE_LISTENONLY``, but not at the same
* time).
*
* @param dev Pointer to the device structure for the driver instance.
* @param[out] cap Supported capabilities.
*
* @retval 0 If successful.
* @retval -EIO General input/output error, failed to get capabilities.
*/
__syscall int can_get_capabilities(const struct device *dev, can_mode_t *cap);
static inline int z_impl_can_get_capabilities(const struct device *dev, can_mode_t *cap)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return api->get_capabilities(dev, cap);
}
/**
* @brief Get the CAN transceiver associated with the CAN controller
*
* Get a pointer to the device structure for the CAN transceiver associated with the CAN controller.
*
* @param dev Pointer to the device structure for the driver instance.
* @return Pointer to the device structure for the associated CAN transceiver driver instance, or
* NULL if no transceiver is associated.
*/
__syscall const struct device *can_get_transceiver(const struct device *dev);
static const struct device *z_impl_can_get_transceiver(const struct device *dev)
{
const struct can_driver_config *common = (const struct can_driver_config *)dev->config;
return common->phy;
}
/**
* @brief Start the CAN controller
*
* Bring the CAN controller out of `CAN_STATE_STOPPED`. This will reset the RX/TX error counters,
* enable the CAN controller to participate in CAN communication, and enable the CAN transceiver, if
* supported.
*
* Starting the CAN controller resets all the CAN controller statistics.
*
* @see can_stop()
* @see can_transceiver_enable()
*
* @param dev Pointer to the device structure for the driver instance.
* @retval 0 if successful.
* @retval -EALREADY if the device is already started.
* @retval -EIO General input/output error, failed to start device.
*/
__syscall int can_start(const struct device *dev);
static inline int z_impl_can_start(const struct device *dev)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return api->start(dev);
}
/**
* @brief Stop the CAN controller
*
* Bring the CAN controller into `CAN_STATE_STOPPED`. This will disallow the CAN controller from
* participating in CAN communication, abort any pending CAN frame transmissions, and disable the
* CAN transceiver, if supported.
*
* @see can_start()
* @see can_transceiver_disable()
*
* @param dev Pointer to the device structure for the driver instance.
* @retval 0 if successful.
* @retval -EALREADY if the device is already stopped.
* @retval -EIO General input/output error, failed to stop device.
*/
__syscall int can_stop(const struct device *dev);
static inline int z_impl_can_stop(const struct device *dev)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return api->stop(dev);
}
/**
* @brief Set the CAN controller to the given operation mode
*
* @param dev Pointer to the device structure for the driver instance.
* @param mode Operation mode.
*
* @retval 0 If successful.
* @retval -EBUSY if the CAN controller is not in stopped state.
* @retval -EIO General input/output error, failed to configure device.
*/
__syscall int can_set_mode(const struct device *dev, can_mode_t mode);
static inline int z_impl_can_set_mode(const struct device *dev, can_mode_t mode)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return api->set_mode(dev, mode);
}
/**
* @brief Get the operation mode of the CAN controller
*
* @param dev Pointer to the device structure for the driver instance.
*
* @return Current operation mode.
*/
__syscall can_mode_t can_get_mode(const struct device *dev);
static inline can_mode_t z_impl_can_get_mode(const struct device *dev)
{
const struct can_driver_data *common = (const struct can_driver_data *)dev->data;
return common->mode;
}
/**
* @brief Set the bitrate of the CAN controller
*
* CAN in Automation (CiA) 301 v4.2.0 recommends a sample point location of
* 87.5% percent for all bitrates. However, some CAN controllers have
* difficulties meeting this for higher bitrates.
*
* This function defaults to using a sample point of 75.0% for bitrates over 800
* kbit/s, 80.0% for bitrates over 500 kbit/s, and 87.5% for all other
* bitrates. This is in line with the sample point locations used by the Linux
* kernel.
*
* @see can_set_bitrate_data()
*
* @param dev Pointer to the device structure for the driver instance.
* @param bitrate Desired arbitration phase bitrate.
*
* @retval 0 If successful.
* @retval -EBUSY if the CAN controller is not in stopped state.
* @retval -EINVAL if the requested bitrate is out of range.
* @retval -ENOTSUP if the requested bitrate not supported by the CAN controller/transceiver
* combination.
* @retval -ERANGE if the resulting sample point is off by more than +/- 5%.
* @retval -EIO General input/output error, failed to set bitrate.
*/
__syscall int can_set_bitrate(const struct device *dev, uint32_t bitrate);
/** @} */
/**
* @name Transmitting CAN frames
*
* @{
*/
/**
* @brief Queue a CAN frame for transmission on the CAN bus
*
* Queue a CAN frame for transmission on the CAN bus with optional timeout and
* completion callback function.
*
* Queued CAN frames are transmitted in order according to the their priority:
* - The lower the CAN-ID, the higher the priority.
* - Data frames have higher priority than Remote Transmission Request (RTR)
* frames with identical CAN-IDs.
* - Frames with standard (11-bit) identifiers have higher priority than frames
* with extended (29-bit) identifiers with identical base IDs (the higher 11
* bits of the extended identifier).
* - Transmission order for queued frames with the same priority is hardware
* dependent.
*
* @note If transmitting segmented messages spanning multiple CAN frames with
* identical CAN-IDs, the sender must ensure to only queue one frame at a time
* if FIFO order is required.
*
* By default, the CAN controller will automatically retry transmission in case
* of lost bus arbitration or missing acknowledge. Some CAN controllers support
* disabling automatic retransmissions via ``CAN_MODE_ONE_SHOT``.
*
* @param dev Pointer to the device structure for the driver instance.
* @param frame CAN frame to transmit.
* @param timeout Timeout waiting for a empty TX mailbox or ``K_FOREVER``.
* @param callback Optional callback for when the frame was sent or a
* transmission error occurred. If ``NULL``, this function is
* blocking until frame is sent. The callback must be ``NULL``
* if called from user mode.
* @param user_data User data to pass to callback function.
*
* @retval 0 if successful.
* @retval -EINVAL if an invalid parameter was passed to the function.
* @retval -ENOTSUP if an unsupported parameter was passed to the function.
* @retval -ENETDOWN if the CAN controller is in stopped state.
* @retval -ENETUNREACH if the CAN controller is in bus-off state.
* @retval -EBUSY if CAN bus arbitration was lost (only applicable if automatic
* retransmissions are disabled).
* @retval -EIO if a general transmit error occurred (e.g. missing ACK if
* automatic retransmissions are disabled).
* @retval -EAGAIN on timeout.
*/
__syscall int can_send(const struct device *dev, const struct can_frame *frame,
k_timeout_t timeout, can_tx_callback_t callback,
void *user_data);
/** @} */
/**
* @name Receiving CAN frames
*
* @{
*/
/**
* @brief Add a callback function for a given CAN filter
*
* Add a callback to CAN identifiers specified by a filter. When a received CAN
* frame matching the filter is received by the CAN controller, the callback
* function is called in interrupt context.
*
* If a received frame matches more than one filter (i.e., the filter IDs/masks or
* flags overlap), the priority of the match is hardware dependent.
*
* The same callback function can be used for multiple filters.
*
* @param dev Pointer to the device structure for the driver instance.
* @param callback This function is called by the CAN controller driver whenever
* a frame matching the filter is received.
* @param user_data User data to pass to callback function.
* @param filter Pointer to a @a can_filter structure defining the filter.
*
* @retval filter_id on success.
* @retval -ENOSPC if there are no free filters.
* @retval -EINVAL if the requested filter type is invalid.
* @retval -ENOTSUP if the requested filter type is not supported.
*/
int can_add_rx_filter(const struct device *dev, can_rx_callback_t callback,
void *user_data, const struct can_filter *filter);
/**
* @brief Statically define and initialize a CAN RX message queue.
*
* The message queue's ring buffer contains space for @a max_frames CAN frames.
*
* @see can_add_rx_filter_msgq()
*
* @param name Name of the message queue.
* @param max_frames Maximum number of CAN frames that can be queued.
*/
#define CAN_MSGQ_DEFINE(name, max_frames) \
K_MSGQ_DEFINE(name, sizeof(struct can_frame), max_frames, 4)
/**
* @brief Simple wrapper function for adding a message queue for a given filter
*
* Wrapper function for @a can_add_rx_filter() which puts received CAN frames
* matching the filter in a message queue instead of calling a callback.
*
* If a received frame matches more than one filter (i.e., the filter IDs/masks or
* flags overlap), the priority of the match is hardware dependent.
*
* The same message queue can be used for multiple filters.
*
* @note The message queue must be initialized before calling this function and
* the caller must have appropriate permissions on it.
*
* @warning Message queue overruns are silently ignored and overrun frames
* discarded. Custom error handling can be implemented by using
* @a can_add_rx_filter() and @a k_msgq_put() directly.
*
* @param dev Pointer to the device structure for the driver instance.
* @param msgq Pointer to the already initialized @a k_msgq struct.
* @param filter Pointer to a @a can_filter structure defining the filter.
*
* @retval filter_id on success.
* @retval -ENOSPC if there are no free filters.
* @retval -ENOTSUP if the requested filter type is not supported.
*/
__syscall int can_add_rx_filter_msgq(const struct device *dev, struct k_msgq *msgq,
const struct can_filter *filter);
/**
* @brief Remove a CAN RX filter
*
* This routine removes a CAN RX filter based on the filter ID returned by @a
* can_add_rx_filter() or @a can_add_rx_filter_msgq().
*
* @param dev Pointer to the device structure for the driver instance.
* @param filter_id Filter ID
*/
__syscall void can_remove_rx_filter(const struct device *dev, int filter_id);
static inline void z_impl_can_remove_rx_filter(const struct device *dev, int filter_id)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return api->remove_rx_filter(dev, filter_id);
}
/**
* @brief Get maximum number of RX filters
*
* Get the maximum number of concurrent RX filters for the CAN controller.
*
* @param dev Pointer to the device structure for the driver instance.
* @param ide Get the maximum standard (11-bit) CAN ID filters if false, or extended (29-bit) CAN ID
* filters if true.
*
* @retval Positive number of maximum concurrent filters.
* @retval -EIO General input/output error.
* @retval -ENOSYS If this function is not implemented by the driver.
*/
__syscall int can_get_max_filters(const struct device *dev, bool ide);
static inline int z_impl_can_get_max_filters(const struct device *dev, bool ide)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
if (api->get_max_filters == NULL) {
return -ENOSYS;
}
return api->get_max_filters(dev, ide);
}
/** @} */
/**
* @name CAN bus error reporting and handling
*
* @{
*/
/**
* @brief Get current CAN controller state
*
* Returns the current state and optionally the error counter values of the CAN
* controller.
*
* @param dev Pointer to the device structure for the driver instance.
* @param[out] state Pointer to the state destination enum or NULL.
* @param[out] err_cnt Pointer to the err_cnt destination structure or NULL.
*
* @retval 0 If successful.
* @retval -EIO General input/output error, failed to get state.
*/
__syscall int can_get_state(const struct device *dev, enum can_state *state,
struct can_bus_err_cnt *err_cnt);
static inline int z_impl_can_get_state(const struct device *dev, enum can_state *state,
struct can_bus_err_cnt *err_cnt)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
return api->get_state(dev, state, err_cnt);
}
/**
* @brief Recover from bus-off state
*
* Recover the CAN controller from bus-off state to error-active state.
*
* @note @kconfig{CONFIG_CAN_MANUAL_RECOVERY_MODE} must be enabled for this
* function to be available.
*
* @param dev Pointer to the device structure for the driver instance.
* @param timeout Timeout for waiting for the recovery or ``K_FOREVER``.
*
* @retval 0 on success.
* @retval -ENOTSUP if the CAN controller is not in manual recovery mode.
* @retval -ENETDOWN if the CAN controller is in stopped state.
* @retval -EAGAIN on timeout.
* @retval -ENOSYS If this function is not implemented by the driver.
*/
__syscall int can_recover(const struct device *dev, k_timeout_t timeout);
#ifdef CONFIG_CAN_MANUAL_RECOVERY_MODE
static inline int z_impl_can_recover(const struct device *dev, k_timeout_t timeout)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
if (api->recover == NULL) {
return -ENOSYS;
}
return api->recover(dev, timeout);
}
#endif /* CONFIG_CAN_MANUAL_RECOVERY_MODE */
/**
* @brief Set a callback for CAN controller state change events
*
* Set the callback for CAN controller state change events. The callback
* function will be called in interrupt context.
*
* Only one callback can be registered per controller. Calling this function
* again overrides any previously registered callback.
*
* @param dev Pointer to the device structure for the driver instance.
* @param callback Callback function.
* @param user_data User data to pass to callback function.
*/
static inline void can_set_state_change_callback(const struct device *dev,
can_state_change_callback_t callback,
void *user_data)
{
const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
api->set_state_change_callback(dev, callback, user_data);
}
/** @} */
/**
* @name CAN statistics
*
* @{
*/
/**
* @brief Get the bit error counter for a CAN device
*
* The bit error counter is incremented when the CAN controller is unable to
* transmit either a dominant or a recessive bit.
*
* @note @kconfig{CONFIG_CAN_STATS} must be selected for this function to be
* available.
*
* @param dev Pointer to the device structure for the driver instance.
* @return bit error counter
*/
__syscall uint32_t can_stats_get_bit_errors(const struct device *dev);
#ifdef CONFIG_CAN_STATS
static inline uint32_t z_impl_can_stats_get_bit_errors(const struct device *dev)
{
return Z_CAN_GET_STATS(dev).bit_error;
}
#endif /* CONFIG_CAN_STATS */
/**
* @brief Get the bit0 error counter for a CAN device
*
* The bit0 error counter is incremented when the CAN controller is unable to
* transmit a dominant bit.
*
* @note @kconfig{CONFIG_CAN_STATS} must be selected for this function to be
* available.
*
* @see can_stats_get_bit_errors()
*
* @param dev Pointer to the device structure for the driver instance.
* @return bit0 error counter
*/
__syscall uint32_t can_stats_get_bit0_errors(const struct device *dev);
#ifdef CONFIG_CAN_STATS
static inline uint32_t z_impl_can_stats_get_bit0_errors(const struct device *dev)
{
return Z_CAN_GET_STATS(dev).bit0_error;
}
#endif /* CONFIG_CAN_STATS */
/**
* @brief Get the bit1 error counter for a CAN device
*
* The bit1 error counter is incremented when the CAN controller is unable to
* transmit a recessive bit.
*
* @note @kconfig{CONFIG_CAN_STATS} must be selected for this function to be
* available.
*
* @see can_stats_get_bit_errors()
*
* @param dev Pointer to the device structure for the driver instance.
* @return bit1 error counter
*/
__syscall uint32_t can_stats_get_bit1_errors(const struct device *dev);
#ifdef CONFIG_CAN_STATS
static inline uint32_t z_impl_can_stats_get_bit1_errors(const struct device *dev)
{
return Z_CAN_GET_STATS(dev).bit1_error;
}
#endif /* CONFIG_CAN_STATS */
/**
* @brief Get the stuffing error counter for a CAN device
*
* The stuffing error counter is incremented when the CAN controller detects a
* bit stuffing error.
*
* @note @kconfig{CONFIG_CAN_STATS} must be selected for this function to be
* available.
*
* @param dev Pointer to the device structure for the driver instance.
* @return stuffing error counter
*/
__syscall uint32_t can_stats_get_stuff_errors(const struct device *dev);
#ifdef CONFIG_CAN_STATS
static inline uint32_t z_impl_can_stats_get_stuff_errors(const struct device *dev)
{
return Z_CAN_GET_STATS(dev).stuff_error;
}
#endif /* CONFIG_CAN_STATS */
/**
* @brief Get the CRC error counter for a CAN device
*
* The CRC error counter is incremented when the CAN controller detects a frame
* with an invalid CRC.
*
* @note @kconfig{CONFIG_CAN_STATS} must be selected for this function to be
* available.
*
* @param dev Pointer to the device structure for the driver instance.
* @return CRC error counter
*/
__syscall uint32_t can_stats_get_crc_errors(const struct device *dev);
#ifdef CONFIG_CAN_STATS
static inline uint32_t z_impl_can_stats_get_crc_errors(const struct device *dev)
{
return Z_CAN_GET_STATS(dev).crc_error;
}
#endif /* CONFIG_CAN_STATS */
/**
* @brief Get the form error counter for a CAN device
*
* The form error counter is incremented when the CAN controller detects a
* fixed-form bit field containing illegal bits.
*
* @note @kconfig{CONFIG_CAN_STATS} must be selected for this function to be
* available.
*
* @param dev Pointer to the device structure for the driver instance.
* @return form error counter
*/
__syscall uint32_t can_stats_get_form_errors(const struct device *dev);
#ifdef CONFIG_CAN_STATS
static inline uint32_t z_impl_can_stats_get_form_errors(const struct device *dev)
{
return Z_CAN_GET_STATS(dev).form_error;
}
#endif /* CONFIG_CAN_STATS */
/**
* @brief Get the acknowledge error counter for a CAN device
*
* The acknowledge error counter is incremented when the CAN controller does not
* monitor a dominant bit in the ACK slot.
*
* @note @kconfig{CONFIG_CAN_STATS} must be selected for this function to be
* available.
*
* @param dev Pointer to the device structure for the driver instance.
* @return acknowledge error counter
*/
__syscall uint32_t can_stats_get_ack_errors(const struct device *dev);
#ifdef CONFIG_CAN_STATS
static inline uint32_t z_impl_can_stats_get_ack_errors(const struct device *dev)
{
return Z_CAN_GET_STATS(dev).ack_error;
}
#endif /* CONFIG_CAN_STATS */
/**
* @brief Get the RX overrun counter for a CAN device
*
* The RX overrun counter is incremented when the CAN controller receives a CAN
* frame matching an installed filter but lacks the capacity to store it (either
* due to an already full RX mailbox or a full RX FIFO).
*
* @note @kconfig{CONFIG_CAN_STATS} must be selected for this function to be
* available.
*
* @param dev Pointer to the device structure for the driver instance.
* @return RX overrun counter
*/
__syscall uint32_t can_stats_get_rx_overruns(const struct device *dev);
#ifdef CONFIG_CAN_STATS
static inline uint32_t z_impl_can_stats_get_rx_overruns(const struct device *dev)
{
return Z_CAN_GET_STATS(dev).rx_overrun;
}
#endif /* CONFIG_CAN_STATS */
/** @} */
/**
* @name CAN utility functions
*
* @{
*/
/**
* @brief Convert from Data Length Code (DLC) to the number of data bytes
*
* @param dlc Data Length Code (DLC).
*
* @retval Number of bytes.
*/
static inline uint8_t can_dlc_to_bytes(uint8_t dlc)
{
static const uint8_t dlc_table[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 12,
16, 20, 24, 32, 48, 64};
return dlc_table[MIN(dlc, ARRAY_SIZE(dlc_table) - 1)];
}
/**
* @brief Convert from number of bytes to Data Length Code (DLC)
*
* @param num_bytes Number of bytes.
*
* @retval Data Length Code (DLC).
*/
static inline uint8_t can_bytes_to_dlc(uint8_t num_bytes)
{
return num_bytes <= 8 ? num_bytes :
num_bytes <= 12 ? 9 :
num_bytes <= 16 ? 10 :
num_bytes <= 20 ? 11 :
num_bytes <= 24 ? 12 :
num_bytes <= 32 ? 13 :
num_bytes <= 48 ? 14 :
15;
}
/**
* @brief Check if a CAN frame matches a CAN filter
*
* @param frame CAN frame.
* @param filter CAN filter.
* @return true if the CAN frame matches the CAN filter, false otherwise
*/
static inline bool can_frame_matches_filter(const struct can_frame *frame,
const struct can_filter *filter)
{
if ((frame->flags & CAN_FRAME_IDE) != 0 && (filter->flags & CAN_FILTER_IDE) == 0) {
/* Extended (29-bit) ID frame, standard (11-bit) filter */
return false;
}
if ((frame->flags & CAN_FRAME_IDE) == 0 && (filter->flags & CAN_FILTER_IDE) != 0) {
/* Standard (11-bit) ID frame, extended (29-bit) filter */
return false;
}
if ((frame->id ^ filter->id) & filter->mask) {
/* Masked ID mismatch */
return false;
}
return true;
}
/** @} */
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/can.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_CAN_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/can.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 13,900 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public API for FLASH drivers
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_FLASH_H_
#define ZEPHYR_INCLUDE_DRIVERS_FLASH_H_
/**
* @brief FLASH internal Interface
* @defgroup flash_internal_interface FLASH internal Interface
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <stddef.h>
#include <sys/types.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
#if defined(CONFIG_FLASH_PAGE_LAYOUT)
struct flash_pages_layout {
size_t pages_count; /* count of pages sequence of the same size */
size_t pages_size;
};
#endif /* CONFIG_FLASH_PAGE_LAYOUT */
/**
* @}
*/
/**
* @brief FLASH Interface
* @defgroup flash_interface FLASH Interface
* @since 1.2
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
/**
* Flash memory parameters. Contents of this structure suppose to be
* filled in during flash device initialization and stay constant
* through a runtime.
*/
struct flash_parameters {
/** Minimal write alignment and size */
const size_t write_block_size;
/** @cond INTERNAL_HIDDEN */
/* User code should call flash_params_get_ functions on flash_parameters
* to get capabilities, rather than accessing object contents directly.
*/
struct {
/* Device has no explicit erase, so it either erases on
* write or does not require it at all.
* This also includes devices that support erase but
* do not require it.
*/
bool no_explicit_erase: 1;
} caps;
/** @endcond */
/** Value the device is filled in erased areas */
uint8_t erase_value;
};
/** Set for ordinary Flash where erase is needed before write of random data */
#define FLASH_ERASE_C_EXPLICIT 0x01
/** Reserved for users as initializer for variables that will later store
* capabilities.
*/
#define FLASH_ERASE_CAPS_UNSET (int)-1
/* The values below are now reserved but not used */
#define FLASH_ERASE_C_SUPPORTED 0x02
#define FLASH_ERASE_C_VAL_BIT 0x04
#define FLASH_ERASE_UNIFORM_PAGE 0x08
/* @brief Parser for flash_parameters for retrieving erase capabilities
*
* The functions parses flash_parameters type object and returns combination
* of erase capabilities of 0 if device does not have any.
* Not that in some cases availability of erase may be dependent on driver
* options, so even if by hardware design a device provides some erase
* capabilities, the function may return 0 if these been disabled or not
* implemented by driver.
*
* @param p pointer to flash_parameters type object
*
* @return 0 or combination of FLASH_ERASE_C_ capabilities.
*/
static inline
int flash_params_get_erase_cap(const struct flash_parameters *p)
{
#if defined(CONFIG_FLASH_HAS_EXPLICIT_ERASE)
#if defined(CONFIG_FLASH_HAS_NO_EXPLICIT_ERASE)
return (p->caps.no_explicit_erase) ? 0 : FLASH_ERASE_C_EXPLICIT;
#else
ARG_UNUSED(p);
return FLASH_ERASE_C_EXPLICIT;
#endif
#endif
return 0;
}
/**
* @}
*/
/**
* @addtogroup flash_internal_interface
* @{
*/
typedef int (*flash_api_read)(const struct device *dev, off_t offset,
void *data,
size_t len);
/**
* @brief Flash write implementation handler type
*
* @note Any necessary write protection management must be performed by
* the driver, with the driver responsible for ensuring the "write-protect"
* after the operation completes (successfully or not) matches the write-protect
* state when the operation was started.
*/
typedef int (*flash_api_write)(const struct device *dev, off_t offset,
const void *data, size_t len);
/**
* @brief Flash erase implementation handler type
*
* @note Any necessary erase protection management must be performed by
* the driver, with the driver responsible for ensuring the "erase-protect"
* after the operation completes (successfully or not) matches the erase-protect
* state when the operation was started.
*
* The callback is optional for RAM non-volatile devices, which do not
* require erase by design, but may be provided if it allows device to
* work more effectively, or if device has a support for internal fill
* operation the erase in driver uses.
*/
typedef int (*flash_api_erase)(const struct device *dev, off_t offset,
size_t size);
typedef const struct flash_parameters* (*flash_api_get_parameters)(const struct device *dev);
#if defined(CONFIG_FLASH_PAGE_LAYOUT)
/**
* @brief Retrieve a flash device's layout.
*
* A flash device layout is a run-length encoded description of the
* pages on the device. (Here, "page" means the smallest erasable
* area on the flash device.)
*
* For flash memories which have uniform page sizes, this routine
* returns an array of length 1, which specifies the page size and
* number of pages in the memory.
*
* Layouts for flash memories with nonuniform page sizes will be
* returned as an array with multiple elements, each of which
* describes a group of pages that all have the same size. In this
* case, the sequence of array elements specifies the order in which
* these groups occur on the device.
*
* @param dev Flash device whose layout to retrieve.
* @param layout The flash layout will be returned in this argument.
* @param layout_size The number of elements in the returned layout.
*/
typedef void (*flash_api_pages_layout)(const struct device *dev,
const struct flash_pages_layout **layout,
size_t *layout_size);
#endif /* CONFIG_FLASH_PAGE_LAYOUT */
typedef int (*flash_api_sfdp_read)(const struct device *dev, off_t offset,
void *data, size_t len);
typedef int (*flash_api_read_jedec_id)(const struct device *dev, uint8_t *id);
typedef int (*flash_api_ex_op)(const struct device *dev, uint16_t code,
const uintptr_t in, void *out);
__subsystem struct flash_driver_api {
flash_api_read read;
flash_api_write write;
flash_api_erase erase;
flash_api_get_parameters get_parameters;
#if defined(CONFIG_FLASH_PAGE_LAYOUT)
flash_api_pages_layout page_layout;
#endif /* CONFIG_FLASH_PAGE_LAYOUT */
#if defined(CONFIG_FLASH_JESD216_API)
flash_api_sfdp_read sfdp_read;
flash_api_read_jedec_id read_jedec_id;
#endif /* CONFIG_FLASH_JESD216_API */
#if defined(CONFIG_FLASH_EX_OP_ENABLED)
flash_api_ex_op ex_op;
#endif /* CONFIG_FLASH_EX_OP_ENABLED */
};
/**
* @}
*/
/**
* @addtogroup flash_interface
* @{
*/
/**
* @brief Read data from flash
*
* All flash drivers support reads without alignment restrictions on
* the read offset, the read size, or the destination address.
*
* @param dev : flash dev
* @param offset : Offset (byte aligned) to read
* @param data : Buffer to store read data
* @param len : Number of bytes to read.
*
* @return 0 on success, negative errno code on fail.
*/
__syscall int flash_read(const struct device *dev, off_t offset, void *data,
size_t len);
static inline int z_impl_flash_read(const struct device *dev, off_t offset,
void *data,
size_t len)
{
const struct flash_driver_api *api =
(const struct flash_driver_api *)dev->api;
return api->read(dev, offset, data, len);
}
/**
* @brief Write buffer into flash memory.
*
* All flash drivers support a source buffer located either in RAM or
* SoC flash, without alignment restrictions on the source address.
* Write size and offset must be multiples of the minimum write block size
* supported by the driver.
*
* Any necessary write protection management is performed by the driver
* write implementation itself.
*
* @param dev : flash device
* @param offset : starting offset for the write
* @param data : data to write
* @param len : Number of bytes to write
*
* @return 0 on success, negative errno code on fail.
*/
__syscall int flash_write(const struct device *dev, off_t offset,
const void *data,
size_t len);
static inline int z_impl_flash_write(const struct device *dev, off_t offset,
const void *data, size_t len)
{
const struct flash_driver_api *api =
(const struct flash_driver_api *)dev->api;
int rc;
rc = api->write(dev, offset, data, len);
return rc;
}
/**
* @brief Erase part or all of a flash memory
*
* Acceptable values of erase size and offset are subject to
* hardware-specific multiples of page size and offset. Please check
* the API implemented by the underlying sub driver, for example by
* using flash_get_page_info_by_offs() if that is supported by your
* flash driver.
*
* Any necessary erase protection management is performed by the driver
* erase implementation itself.
*
* The function should be used only for devices that are really
* explicit erase devices; in case when code relies on erasing
* device, i.e. setting it to erase-value, prior to some operations,
* but should work with explicit erase and RAM non-volatile devices,
* then flash_flatten should rather be used.
*
* @param dev : flash device
* @param offset : erase area starting offset
* @param size : size of area to be erased
*
* @return 0 on success, negative errno code on fail.
*
* @see flash_flatten()
* @see flash_get_page_info_by_offs()
* @see flash_get_page_info_by_idx()
*/
__syscall int flash_erase(const struct device *dev, off_t offset, size_t size);
static inline int z_impl_flash_erase(const struct device *dev, off_t offset,
size_t size)
{
int rc = -ENOSYS;
const struct flash_driver_api *api =
(const struct flash_driver_api *)dev->api;
if (api->erase != NULL) {
rc = api->erase(dev, offset, size);
}
return rc;
}
/**
* @brief Fill selected range of device with specified value
*
* Utility function that allows to fill specified range on a device with
* provided value. The @p offset and @p size of range need to be aligned to
* a write block size of a device.
*
* @param dev : flash device
* @param val : value to use for filling the range
* @param offset : offset of the range to fill
* @param size : size of the range
*
* @return 0 on success, negative errno code on fail.
*
*/
__syscall int flash_fill(const struct device *dev, uint8_t val, off_t offset, size_t size);
/**
* @brief Erase part or all of a flash memory or level it
*
* If device is explicit erase type device or device driver provides erase
* callback, the callback of the device is called, in which it behaves
* the same way as flash_erase.
* If a device does not require explicit erase, either because
* it has no erase at all or has auto-erase/erase-on-write,
* and does not provide erase callback then erase is emulated by
* leveling selected device memory area with erase_value assigned to
* device.
*
* Erase page offset and size are constrains of paged, explicit erase devices,
* but can be relaxed with devices without such requirement, which means that
* it is up to user code to make sure they are correct as the function
* will return on, if these constrains are not met, -EINVAL for
* paged device, but may succeed on non-explicit erase devices.
* For RAM non-volatile devices the erase pages are emulated,
* at this point, to allow smooth transition for code relying on
* device being paged to function properly; but this is completely
* software constrain.
*
* Generally: if your code previously required device to be erase
* prior to some actions to work, replace flash_erase calls with this
* function; but if your code can work with non-volatile RAM type devices,
* without emulating erase, you should rather have different path
* of execution for page-erase, i.e. Flash, devices and call
* flash_erase for them.
*
* @param dev : flash device
* @param offset : erase area starting offset
* @param size : size of area to be erased
*
* @return 0 on success, negative errno code on fail.
*
* @see flash_erase()
*/
__syscall int flash_flatten(const struct device *dev, off_t offset, size_t size);
struct flash_pages_info {
off_t start_offset; /* offset from the base of flash address */
size_t size;
uint32_t index;
};
#if defined(CONFIG_FLASH_PAGE_LAYOUT)
/**
* @brief Get the size and start offset of flash page at certain flash offset.
*
* @param dev flash device
* @param offset Offset within the page
* @param info Page Info structure to be filled
*
* @return 0 on success, -EINVAL if page of the offset doesn't exist.
*/
__syscall int flash_get_page_info_by_offs(const struct device *dev,
off_t offset,
struct flash_pages_info *info);
/**
* @brief Get the size and start offset of flash page of certain index.
*
* @param dev flash device
* @param page_index Index of the page. Index are counted from 0.
* @param info Page Info structure to be filled
*
* @return 0 on success, -EINVAL if page of the index doesn't exist.
*/
__syscall int flash_get_page_info_by_idx(const struct device *dev,
uint32_t page_index,
struct flash_pages_info *info);
/**
* @brief Get the total number of flash pages.
*
* @param dev flash device
*
* @return Number of flash pages.
*/
__syscall size_t flash_get_page_count(const struct device *dev);
/**
* @brief Callback type for iterating over flash pages present on a device.
*
* The callback should return true to continue iterating, and false to halt.
*
* @param info Information for current page
* @param data Private data for callback
* @return True to continue iteration, false to halt iteration.
* @see flash_page_foreach()
*/
typedef bool (*flash_page_cb)(const struct flash_pages_info *info, void *data);
/**
* @brief Iterate over all flash pages on a device
*
* This routine iterates over all flash pages on the given device,
* ordered by increasing start offset. For each page, it invokes the
* given callback, passing it the page's information and a private
* data object.
*
* @param dev Device whose pages to iterate over
* @param cb Callback to invoke for each flash page
* @param data Private data for callback function
*/
void flash_page_foreach(const struct device *dev, flash_page_cb cb,
void *data);
#endif /* CONFIG_FLASH_PAGE_LAYOUT */
#if defined(CONFIG_FLASH_JESD216_API)
/**
* @brief Read data from Serial Flash Discoverable Parameters
*
* This routine reads data from a serial flash device compatible with
* the JEDEC JESD216 standard for encoding flash memory
* characteristics.
*
* Availability of this API is conditional on selecting
* @c CONFIG_FLASH_JESD216_API and support of that functionality in
* the driver underlying @p dev.
*
* @param dev device from which parameters will be read
* @param offset address within the SFDP region containing data of interest
* @param data where the data to be read will be placed
* @param len the number of bytes of data to be read
*
* @retval 0 on success
* @retval -ENOTSUP if the flash driver does not support SFDP access
* @retval negative values for other errors.
*/
__syscall int flash_sfdp_read(const struct device *dev, off_t offset,
void *data, size_t len);
static inline int z_impl_flash_sfdp_read(const struct device *dev,
off_t offset,
void *data, size_t len)
{
int rv = -ENOTSUP;
const struct flash_driver_api *api =
(const struct flash_driver_api *)dev->api;
if (api->sfdp_read != NULL) {
rv = api->sfdp_read(dev, offset, data, len);
}
return rv;
}
/**
* @brief Read the JEDEC ID from a compatible flash device.
*
* @param dev device from which id will be read
* @param id pointer to a buffer of at least 3 bytes into which id
* will be stored
*
* @retval 0 on successful store of 3-byte JEDEC id
* @retval -ENOTSUP if flash driver doesn't support this function
* @retval negative values for other errors
*/
__syscall int flash_read_jedec_id(const struct device *dev, uint8_t *id);
static inline int z_impl_flash_read_jedec_id(const struct device *dev,
uint8_t *id)
{
int rv = -ENOTSUP;
const struct flash_driver_api *api =
(const struct flash_driver_api *)dev->api;
if (api->read_jedec_id != NULL) {
rv = api->read_jedec_id(dev, id);
}
return rv;
}
#endif /* CONFIG_FLASH_JESD216_API */
/**
* @brief Get the minimum write block size supported by the driver
*
* The write block size supported by the driver might differ from the write
* block size of memory used because the driver might implements write-modify
* algorithm.
*
* @param dev flash device
*
* @return write block size in bytes.
*/
__syscall size_t flash_get_write_block_size(const struct device *dev);
static inline size_t z_impl_flash_get_write_block_size(const struct device *dev)
{
const struct flash_driver_api *api =
(const struct flash_driver_api *)dev->api;
return api->get_parameters(dev)->write_block_size;
}
/**
* @brief Get pointer to flash_parameters structure
*
* Returned pointer points to a structure that should be considered
* constant through a runtime, regardless if it is defined in RAM or
* Flash.
* Developer is free to cache the structure pointer or copy its contents.
*
* @return pointer to flash_parameters structure characteristic for
* the device.
*/
__syscall const struct flash_parameters *flash_get_parameters(const struct device *dev);
static inline const struct flash_parameters *z_impl_flash_get_parameters(const struct device *dev)
{
const struct flash_driver_api *api =
(const struct flash_driver_api *)dev->api;
return api->get_parameters(dev);
}
/**
* @brief Execute flash extended operation on given device
*
* Besides of standard flash operations like write or erase, flash controllers
* also support additional features like write protection or readout
* protection. These features are not available in every flash controller,
* what's more controllers can implement it in a different way.
*
* It doesn't make sense to add a separate flash API function for every flash
* controller feature, because it could be unique (supported on small number of
* flash controllers) or the API won't be able to represent the same feature on
* every flash controller.
*
* @param dev Flash device
* @param code Operation which will be executed on the device.
* @param in Pointer to input data used by operation. If operation doesn't
* need any input data it could be NULL.
* @param out Pointer to operation output data. If operation doesn't produce
* any output it could be NULL.
*
* @retval 0 on success.
* @retval -ENOTSUP if given device doesn't support extended operation.
* @retval -ENOSYS if support for extended operations is not enabled in Kconfig
* @retval negative value on extended operation errors.
*/
__syscall int flash_ex_op(const struct device *dev, uint16_t code,
const uintptr_t in, void *out);
/*
* Extended operation interface provides flexible way for supporting flash
* controller features. Code space is divided equally into Zephyr codes
* (MSb == 0) and vendor codes (MSb == 1). This way we can easily add extended
* operations to the drivers without cluttering the API or problems with API
* incompatibility. Extended operation can be promoted from vendor codes to
* Zephyr codes if the feature is available in most flash controllers and
* can be represented in the same way.
*
* It's not forbidden to have operation in Zephyr codes and vendor codes for
* the same functionality. In this case, vendor operation could provide more
* specific access when abstraction in Zephyr counterpart is insufficient.
*/
#define FLASH_EX_OP_VENDOR_BASE 0x8000
#define FLASH_EX_OP_IS_VENDOR(c) ((c) & FLASH_EX_OP_VENDOR_BASE)
/**
* @brief Enumeration for extra flash operations
*/
enum flash_ex_op_types {
/*
* Reset flash device.
*/
FLASH_EX_OP_RESET = 0,
};
static inline int z_impl_flash_ex_op(const struct device *dev, uint16_t code,
const uintptr_t in, void *out)
{
#if defined(CONFIG_FLASH_EX_OP_ENABLED)
const struct flash_driver_api *api =
(const struct flash_driver_api *)dev->api;
if (api->ex_op == NULL) {
return -ENOTSUP;
}
return api->ex_op(dev, code, in, out);
#else
ARG_UNUSED(dev);
ARG_UNUSED(code);
ARG_UNUSED(in);
ARG_UNUSED(out);
return -ENOSYS;
#endif /* CONFIG_FLASH_EX_OP_ENABLED */
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/flash.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_FLASH_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/flash.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 4,852 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_PM_CPU_OPS_H_
#define ZEPHYR_INCLUDE_DRIVERS_PM_CPU_OPS_H_
/**
* @file
* @brief Public API for CPU Power Management
*/
#include <zephyr/types.h>
#include <stddef.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/* System reset types. */
#define SYS_WARM_RESET 0
#define SYS_COLD_RESET 1
/**
* @defgroup power_management_cpu_api CPU Power Management
* @ingroup subsys_pm
* @{
*/
/**
* @brief Power down the calling core
*
* This call is intended for use in hotplug. A core that is powered down by
* cpu_off can only be powered up again in response to a cpu_on
*
* @retval The call does not return when successful
* @retval -ENOTSUP If the operation is not supported
*/
int pm_cpu_off(void);
/**
* @brief Power up a core
*
* This call is used to power up cores that either have not yet been booted
* into the calling supervisory software or have been previously powered down
* with a cpu_off call
*
* @param cpuid CPU id to power on
* @param entry_point Address at which the core must commence execution
*
* @retval 0 on success, a negative errno otherwise
* @retval -ENOTSUP If the operation is not supported
*/
int pm_cpu_on(unsigned long cpuid, uintptr_t entry_point);
/**
* @brief System reset
*
* This function provides a method for performing a system cold or warm reset.
*
* @param reset system reset type, cold or warm.
*
* @retval 0 on success, a negative errno otherwise
*/
int pm_system_reset(unsigned char reset);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_PM_CPU_OPS_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/pm_cpu_ops.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 408 |
```objective-c
/*
*/
#include <zephyr/drivers/emul.h>
#include <zephyr/drivers/sensor.h>
#include <zephyr/drivers/sensor_attribute_types.h>
#include <stdint.h>
/**
* @brief Sensor emulator backend API
* @defgroup sensor_emulator_backend Sensor emulator backend API
* @ingroup io_interfaces
* @{
*/
/**
* @cond INTERNAL_HIDDEN
*
* These are for internal use only, so skip these in public documentation.
*/
/**
* @brief Collection of function pointers implementing a common backend API for sensor emulators
*/
__subsystem struct emul_sensor_driver_api {
/** Sets a given fractional value for a given sensor channel. */
int (*set_channel)(const struct emul *target, struct sensor_chan_spec ch,
const q31_t *value, int8_t shift);
/** Retrieve a range of sensor values to use with test. */
int (*get_sample_range)(const struct emul *target, struct sensor_chan_spec ch, q31_t *lower,
q31_t *upper, q31_t *epsilon, int8_t *shift);
/** Set the attribute value(s) of a given channel. */
int (*set_attribute)(const struct emul *target, struct sensor_chan_spec ch,
enum sensor_attribute attribute, const void *value);
/** Get metadata about an attribute. */
int (*get_attribute_metadata)(const struct emul *target, struct sensor_chan_spec ch,
enum sensor_attribute attribute, q31_t *min, q31_t *max,
q31_t *increment, int8_t *shift);
};
/**
* @endcond
*/
/**
* @brief Check if a given sensor emulator supports the backend API
*
* @param target Pointer to emulator instance to query
*
* @return True if supported, false if unsupported or if \p target is NULL.
*/
static inline bool emul_sensor_backend_is_supported(const struct emul *target)
{
return target && target->backend_api;
}
/**
* @brief Set an expected value for a given channel on a given sensor emulator
*
* @param target Pointer to emulator instance to operate on
* @param ch Sensor channel to set expected value for
* @param value Expected value in fixed-point format using standard SI unit for sensor type
* @param shift Shift value (scaling factor) applied to \p value
*
* @return 0 if successful
* @return -ENOTSUP if no backend API or if channel not supported by emul
* @return -ERANGE if provided value is not in the sensor's supported range
*/
static inline int emul_sensor_backend_set_channel(const struct emul *target,
struct sensor_chan_spec ch, const q31_t *value,
int8_t shift)
{
if (!target || !target->backend_api) {
return -ENOTSUP;
}
struct emul_sensor_driver_api *api = (struct emul_sensor_driver_api *)target->backend_api;
if (api->set_channel) {
return api->set_channel(target, ch, value, shift);
}
return -ENOTSUP;
}
/**
* @brief Query an emulator for a channel's supported sample value range and tolerance
*
* @param target Pointer to emulator instance to operate on
* @param ch The channel to request info for. If \p ch is unsupported, return `-ENOTSUP`
* @param[out] lower Minimum supported sample value in SI units, fixed-point format
* @param[out] upper Maximum supported sample value in SI units, fixed-point format
* @param[out] epsilon Tolerance to use comparing expected and actual values to account for rounding
* and sensor precision issues. This can usually be set to the minimum sample value step
* size. Uses SI units and fixed-point format.
* @param[out] shift The shift value (scaling factor) associated with \p lower, \p upper, and
* \p epsilon.
*
* @return 0 if successful
* @return -ENOTSUP if no backend API or if channel not supported by emul
*
*/
static inline int emul_sensor_backend_get_sample_range(const struct emul *target,
struct sensor_chan_spec ch, q31_t *lower,
q31_t *upper, q31_t *epsilon, int8_t *shift)
{
if (!target || !target->backend_api) {
return -ENOTSUP;
}
struct emul_sensor_driver_api *api = (struct emul_sensor_driver_api *)target->backend_api;
if (api->get_sample_range) {
return api->get_sample_range(target, ch, lower, upper, epsilon, shift);
}
return -ENOTSUP;
}
/**
* @brief Set the emulator's attribute values
*
* @param[in] target Pointer to emulator instance to operate on
* @param[in] ch The channel to request info for. If \p ch is unsupported, return `-ENOTSUP`
* @param[in] attribute The attribute to set
* @param[in] value the value to use (cast according to the channel/attribute pair)
* @return 0 is successful
* @return < 0 on error
*/
static inline int emul_sensor_backend_set_attribute(const struct emul *target,
struct sensor_chan_spec ch,
enum sensor_attribute attribute,
const void *value)
{
if (!target || !target->backend_api) {
return -ENOTSUP;
}
struct emul_sensor_driver_api *api = (struct emul_sensor_driver_api *)target->backend_api;
if (api->set_attribute == NULL) {
return -ENOTSUP;
}
return api->set_attribute(target, ch, attribute, value);
}
/**
* @brief Get metadata about an attribute.
*
* Information provided by this function includes the minimum/maximum values of the attribute as
* well as the increment (value per LSB) which can be used as an epsilon when comparing results.
*
* @param[in] target Pointer to emulator instance to operate on
* @param[in] ch The channel to request info for. If \p ch is unsupported, return '-ENOTSUP'
* @param[in] attribute The attribute to request info for. If \p attribute is unsupported, return
* '-ENOTSUP'
* @param[out] min The minimum value the attribute can be set to
* @param[out] max The maximum value the attribute can be set to
* @param[out] increment The value that the attribute increases by for every LSB
* @param[out] shift The shift for \p min, \p max, and \p increment
* @return 0 on SUCCESS
* @return < 0 on error
*/
static inline int emul_sensor_backend_get_attribute_metadata(const struct emul *target,
struct sensor_chan_spec ch,
enum sensor_attribute attribute,
q31_t *min, q31_t *max,
q31_t *increment, int8_t *shift)
{
if (!target || !target->backend_api) {
return -ENOTSUP;
}
struct emul_sensor_driver_api *api = (struct emul_sensor_driver_api *)target->backend_api;
if (api->get_attribute_metadata == NULL) {
return -ENOTSUP;
}
return api->get_attribute_metadata(target, ch, attribute, min, max, increment, shift);
}
/**
* @}
*/
``` | /content/code_sandbox/include/zephyr/drivers/emul_sensor.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,548 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public APIs for the DAI (Digital Audio Interface) bus drivers.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_DAI_H_
#define ZEPHYR_INCLUDE_DRIVERS_DAI_H_
/**
* @defgroup dai_interface DAI Interface
* @since 3.1
* @version 0.1.0
* @ingroup io_interfaces
* @brief DAI Interface
*
* The DAI API provides support for the standard I2S (SSP) and its common variants.
* It supports also DMIC, HDA and SDW backends. The API has a config function
* with bespoke data argument for device/vendor specific config. There are also
* optional timestamping functions to get device specific audio clock time.
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Used to extract the clock configuration from the format attribute of struct dai_config */
#define DAI_FORMAT_CLOCK_PROVIDER_MASK 0xf000
/** Used to extract the protocol from the format attribute of struct dai_config */
#define DAI_FORMAT_PROTOCOL_MASK 0x000f
/** Used to extract the clock inversion from the format attribute of struct dai_config */
#define DAI_FORMAT_CLOCK_INVERSION_MASK 0x0f00
/** @brief DAI clock configurations
*
* This is used to describe all of the possible
* clock-related configurations w.r.t the DAI
* and the codec.
*/
enum dai_clock_provider {
/**< codec BLCK provider, codec FSYNC provider */
DAI_CBP_CFP = (0 << 12),
/**< codec BCLK consumer, codec FSYNC provider */
DAI_CBC_CFP = (2 << 12),
/**< codec BCLK provider, codec FSYNC consumer */
DAI_CBP_CFC = (3 << 12),
/**< codec BCLK consumer, codec FSYNC consumer */
DAI_CBC_CFC = (4 << 12),
};
/** @brief DAI protocol
*
* The communication between the DAI and the CODEC
* may use different protocols depending on the scenario.
*/
enum dai_protocol {
DAI_PROTO_I2S = 1, /**< I2S */
DAI_PROTO_RIGHT_J, /**< Right Justified */
DAI_PROTO_LEFT_J, /**< Left Justified */
DAI_PROTO_DSP_A, /**< TDM, FSYNC asserted 1 BCLK early */
DAI_PROTO_DSP_B, /**< TDM, FSYNC asserted at the same time as MSB */
DAI_PROTO_PDM, /**< Pulse Density Modulation */
};
/** @brief DAI clock inversion
*
* Some applications may require a different
* clock polarity (FSYNC/BCLK) compared to
* the default one chosen based on the protocol.
*/
enum dai_clock_inversion {
/**< no BCLK inversion, no FSYNC inversion */
DAI_INVERSION_NB_NF = 0,
/**< no BCLK inversion, FSYNC inversion */
DAI_INVERSION_NB_IF = (2 << 8),
/**< BCLK inversion, no FSYNC inversion */
DAI_INVERSION_IB_NF = (3 << 8),
/**< BCLK inversion, FSYNC inversion */
DAI_INVERSION_IB_IF = (4 << 8),
};
/** @brief Types of DAI
*
* The type of the DAI. This ID type is used to configure bespoke DAI HW
* settings.
*
* DAIs have a lot of physical link feature variability and therefore need
* different configuration data to cater for different use cases. We
* usually need to pass extra bespoke configuration prior to DAI start.
*/
enum dai_type {
DAI_LEGACY_I2S = 0, /**< Legacy I2S compatible with i2s.h */
DAI_INTEL_SSP, /**< Intel SSP */
DAI_INTEL_DMIC, /**< Intel DMIC */
DAI_INTEL_HDA, /**< Intel HD/A */
DAI_INTEL_ALH, /**< Intel ALH */
DAI_IMX_SAI, /**< i.MX SAI */
DAI_IMX_ESAI, /**< i.MX ESAI */
DAI_AMD_BT, /**< Amd BT */
DAI_AMD_SP, /**< Amd SP */
DAI_AMD_DMIC, /**< Amd DMIC */
DAI_MEDIATEK_AFE, /**< Mtk AFE */
DAI_INTEL_SSP_NHLT, /**< nhlt ssp */
DAI_INTEL_DMIC_NHLT, /**< nhlt ssp */
DAI_INTEL_HDA_NHLT, /**< nhlt Intel HD/A */
DAI_INTEL_ALH_NHLT, /**< nhlt Intel ALH */
};
/**
* @brief DAI Direction
*/
enum dai_dir {
/** Transmit data */
DAI_DIR_TX = 0,
/** Receive data */
DAI_DIR_RX,
/** Both receive and transmit data */
DAI_DIR_BOTH,
};
/** Interface state */
enum dai_state {
/** @brief The interface is not ready.
*
* The interface was initialized but is not yet ready to receive /
* transmit data. Call dai_config_set() to configure interface and change
* its state to READY.
*/
DAI_STATE_NOT_READY = 0,
/** The interface is ready to receive / transmit data. */
DAI_STATE_READY,
/** The interface is receiving / transmitting data. */
DAI_STATE_RUNNING,
/** The interface is clocking but not receiving / transmitting data. */
DAI_STATE_PRE_RUNNING,
/** The interface paused */
DAI_STATE_PAUSED,
/** The interface is draining its transmit queue. */
DAI_STATE_STOPPING,
/** TX buffer underrun or RX buffer overrun has occurred. */
DAI_STATE_ERROR,
};
/** Trigger command */
enum dai_trigger_cmd {
/** @brief Start the transmission / reception of data.
*
* If DAI_DIR_TX is set some data has to be queued for transmission by
* the dai_write() function. This trigger can be used in READY state
* only and changes the interface state to RUNNING.
*/
DAI_TRIGGER_START = 0,
/** @brief Optional - Pre Start the transmission / reception of data.
*
* Allows the DAI and downstream codecs to prepare for audio Tx/Rx by
* starting any required clocks for downstream PLL/FLL locking.
*/
DAI_TRIGGER_PRE_START,
/** @brief Stop the transmission / reception of data.
*
* Stop the transmission / reception of data at the end of the current
* memory block. This trigger can be used in RUNNING state only and at
* first changes the interface state to STOPPING. When the current TX /
* RX block is transmitted / received the state is changed to READY.
* Subsequent START trigger will resume transmission / reception where
* it stopped.
*/
DAI_TRIGGER_STOP,
/** @brief Pause the transmission / reception of data.
*
* Pause the transmission / reception of data at the end of the current
* memory block. Behavior is implementation specific but usually this
* state doesn't completely stop the clocks or transmission. The DAI could
* be transmitting 0's (silence), but it is not consuming data from outside.
*/
DAI_TRIGGER_PAUSE,
/** @brief Optional - Post Stop the transmission / reception of data.
*
* Allows the DAI and downstream codecs to shutdown cleanly after audio
* Tx/Rx by stopping any required clocks for downstream audio completion.
*/
DAI_TRIGGER_POST_STOP,
/** @brief Empty the transmit queue.
*
* Send all data in the transmit queue and stop the transmission.
* If the trigger is applied to the RX queue it has the same effect as
* DAI_TRIGGER_STOP. This trigger can be used in RUNNING state only and
* at first changes the interface state to STOPPING. When all TX blocks
* are transmitted the state is changed to READY.
*/
DAI_TRIGGER_DRAIN,
/** @brief Discard the transmit / receive queue.
*
* Stop the transmission / reception immediately and discard the
* contents of the respective queue. This trigger can be used in any
* state other than NOT_READY and changes the interface state to READY.
*/
DAI_TRIGGER_DROP,
/** @brief Prepare the queues after underrun/overrun error has occurred.
*
* This trigger can be used in ERROR state only and changes the
* interface state to READY.
*/
DAI_TRIGGER_PREPARE,
/** @brief Reset
*
* This trigger frees resources and moves the driver back to initial
* state.
*/
DAI_TRIGGER_RESET,
/** @brief Copy
*
* This trigger prepares for data copying.
*/
DAI_TRIGGER_COPY,
};
/** @brief DAI properties
*
* This struct is used with APIs get_properties function to query DAI
* properties like fifo address and dma handshake. These are needed
* for example to setup dma outside the driver code.
*/
struct dai_properties {
/** Fifo hw address for e.g. when connecting to dma. */
uint32_t fifo_address;
/** Fifo depth. */
uint32_t fifo_depth;
/** DMA handshake id. */
uint32_t dma_hs_id;
/** Delay for initializing registers. */
uint32_t reg_init_delay;
/** Stream ID. */
int stream_id;
};
/** @brief Main DAI config structure
*
* Generic DAI interface configuration options.
*/
struct dai_config {
/** Type of the DAI. */
enum dai_type type;
/** Index of the DAI. */
uint32_t dai_index;
/** Number of audio channels, words in frame. */
uint8_t channels;
/** Frame clock (WS) frequency, sampling rate. */
uint32_t rate;
/** DAI specific data stream format. */
uint16_t format;
/** DAI specific configuration options. */
uint8_t options;
/** Number of bits representing one data word. */
uint8_t word_size;
/** Size of one RX/TX memory block (buffer) in bytes. */
size_t block_size;
/** DAI specific link configuration. */
uint16_t link_config;
/**< tdm slot group number*/
uint32_t tdm_slot_group;
};
/**
* @brief DAI timestamp configuration
*/
struct dai_ts_cfg {
/** Rate in Hz, e.g. 19200000 */
uint32_t walclk_rate;
/** Type of the DAI (SSP, DMIC, HDA, etc.). */
int type;
/** Direction (playback/capture) */
int direction;
/** Index for SSPx to select correct timestamp register */
int index;
/** DMA instance id */
int dma_id;
/** Used DMA channel index */
int dma_chan_index;
/** Number of channels in single DMA */
int dma_chan_count;
};
/**
* @brief DAI timestamp data
*/
struct dai_ts_data {
/** Wall clock */
uint64_t walclk;
/** Sample count */
uint64_t sample;
/** Rate in Hz, e.g. 19200000 */
uint32_t walclk_rate;
};
/**
* @cond INTERNAL_HIDDEN
*
* For internal use only, skip these in public documentation.
*/
__subsystem struct dai_driver_api {
int (*probe)(const struct device *dev);
int (*remove)(const struct device *dev);
int (*config_set)(const struct device *dev, const struct dai_config *cfg,
const void *bespoke_cfg);
int (*config_get)(const struct device *dev, struct dai_config *cfg,
enum dai_dir dir);
const struct dai_properties *(*get_properties)(const struct device *dev,
enum dai_dir dir,
int stream_id);
int (*trigger)(const struct device *dev, enum dai_dir dir,
enum dai_trigger_cmd cmd);
/* optional methods */
int (*ts_config)(const struct device *dev, struct dai_ts_cfg *cfg);
int (*ts_start)(const struct device *dev, struct dai_ts_cfg *cfg);
int (*ts_stop)(const struct device *dev, struct dai_ts_cfg *cfg);
int (*ts_get)(const struct device *dev, struct dai_ts_cfg *cfg,
struct dai_ts_data *tsd);
int (*config_update)(const struct device *dev, const void *bespoke_cfg,
size_t size);
};
/**
* @endcond
*/
/**
* @brief Probe operation of DAI driver.
*
* The function will be called to power up the device and update for example
* possible reference count of the users. It can be used also to initialize
* internal variables and memory allocation.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
*/
static inline int dai_probe(const struct device *dev)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
return api->probe(dev);
}
/**
* @brief Remove operation of DAI driver.
*
* The function will be called to unregister/unbind the device, for example to
* power down the device or decrease the usage reference count.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
*/
static inline int dai_remove(const struct device *dev)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
return api->remove(dev);
}
/**
* @brief Configure operation of a DAI driver.
*
* The dir parameter specifies if Transmit (TX) or Receive (RX) direction
* will be configured by data provided via cfg parameter.
*
* The function can be called in NOT_READY or READY state only. If executed
* successfully the function will change the interface state to READY.
*
* If the function is called with the parameter cfg->frame_clk_freq set to 0
* the interface state will be changed to NOT_READY.
*
* @param dev Pointer to the device structure for the driver instance.
* @param cfg Pointer to the structure containing configuration parameters.
* @param bespoke_cfg Pointer to the structure containing bespoke config.
*
* @retval 0 If successful.
* @retval -EINVAL Invalid argument.
* @retval -ENOSYS DAI_DIR_BOTH value is not supported.
*/
static inline int dai_config_set(const struct device *dev,
const struct dai_config *cfg,
const void *bespoke_cfg)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
return api->config_set(dev, cfg, bespoke_cfg);
}
/**
* @brief Fetch configuration information of a DAI driver
*
* @param dev Pointer to the device structure for the driver instance
* @param cfg Pointer to the config structure to be filled by the instance
* @param dir Stream direction: RX or TX as defined by DAI_DIR_*
* @retval 0 if success, negative if invalid parameters or DAI un-configured
*/
static inline int dai_config_get(const struct device *dev,
struct dai_config *cfg,
enum dai_dir dir)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
return api->config_get(dev, cfg, dir);
}
/**
* @brief Fetch properties of a DAI driver
*
* @param dev Pointer to the device structure for the driver instance
* @param dir Stream direction: RX or TX as defined by DAI_DIR_*
* @param stream_id Stream id: some drivers may have stream specific
* properties, this id specifies the stream.
* @retval Pointer to the structure containing properties,
* or NULL if error or no properties
*/
static inline const struct dai_properties *dai_get_properties(const struct device *dev,
enum dai_dir dir,
int stream_id)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
return api->get_properties(dev, dir, stream_id);
}
/**
* @brief Send a trigger command.
*
* @param dev Pointer to the device structure for the driver instance.
* @param dir Stream direction: RX, TX, or both, as defined by DAI_DIR_*.
* The DAI_DIR_BOTH value may not be supported by some drivers.
* For those, triggering need to be done separately for the RX
* and TX streams.
* @param cmd Trigger command.
*
* @retval 0 If successful.
* @retval -EINVAL Invalid argument.
* @retval -EIO The trigger cannot be executed in the current state or a DMA
* channel cannot be allocated.
* @retval -ENOMEM RX/TX memory block not available.
* @retval -ENOSYS DAI_DIR_BOTH value is not supported.
*/
static inline int dai_trigger(const struct device *dev,
enum dai_dir dir,
enum dai_trigger_cmd cmd)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
return api->trigger(dev, dir, cmd);
}
/**
* Configures timestamping in attached DAI.
* @param dev Component device.
* @param cfg Timestamp config.
*
* Optional method.
*
* @retval 0 If successful.
*/
static inline int dai_ts_config(const struct device *dev, struct dai_ts_cfg *cfg)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
if (!api->ts_config) {
return -EINVAL;
}
return api->ts_config(dev, cfg);
}
/**
* Starts timestamping.
* @param dev Component device.
* @param cfg Timestamp config.
*
* Optional method
*
* @retval 0 If successful.
*/
static inline int dai_ts_start(const struct device *dev, struct dai_ts_cfg *cfg)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
if (!api->ts_start) {
return -EINVAL;
}
return api->ts_start(dev, cfg);
}
/**
* Stops timestamping.
* @param dev Component device.
* @param cfg Timestamp config.
*
* Optional method.
*
* @retval 0 If successful.
*/
static inline int dai_ts_stop(const struct device *dev, struct dai_ts_cfg *cfg)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
if (!api->ts_stop) {
return -EINVAL;
}
return api->ts_stop(dev, cfg);
}
/**
* Gets timestamp.
* @param dev Component device.
* @param cfg Timestamp config.
* @param tsd Receives timestamp data.
*
* Optional method.
*
* @retval 0 If successful.
*/
static inline int dai_ts_get(const struct device *dev, struct dai_ts_cfg *cfg,
struct dai_ts_data *tsd)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
if (!api->ts_get) {
return -EINVAL;
}
return api->ts_get(dev, cfg, tsd);
}
/**
* @brief Update DAI configuration at runtime.
*
* This function updates the configuration of a DAI interface at runtime.
* It allows setting bespoke configuration parameters that are specific to
* the DAI implementation, enabling updates outside of the regular flow with
* the full configuration blob. The details of the bespoke configuration are
* specific to each DAI implementation. This function should only be called
* when the DAI is in the READY state, ensuring that the configuration updates
* are applied before data transmission or reception begins.
*
* @param dev Pointer to the device structure for the driver instance.
* @param bespoke_cfg Pointer to the buffer containing bespoke configuration parameters.
* @param size Size of the bespoke_cfg buffer in bytes.
*
* @retval 0 If successful.
* @retval -ENOSYS If the configuration update operation is not implemented.
* @retval Negative errno code if failure.
*/
static inline int dai_config_update(const struct device *dev,
const void *bespoke_cfg,
size_t size)
{
const struct dai_driver_api *api = (const struct dai_driver_api *)dev->api;
if (!api->config_update) {
return -ENOSYS;
}
return api->config_update(dev, bespoke_cfg, size);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_DAI_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/dai.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 4,363 |
```objective-c
/**
* @file
*
* @brief Public APIs for MDIO drivers.
*/
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_MDIO_H_
#define ZEPHYR_INCLUDE_DRIVERS_MDIO_H_
/**
* @brief MDIO Interface
* @defgroup mdio_interface MDIO Interface
* @ingroup io_interfaces
* @{
*/
#include <zephyr/types.h>
#include <zephyr/device.h>
#include <errno.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @cond INTERNAL_HIDDEN
*
* These are for internal use only, so skip these in
* public documentation.
*/
__subsystem struct mdio_driver_api {
/** Enable the MDIO bus device */
void (*bus_enable)(const struct device *dev);
/** Disable the MDIO bus device */
void (*bus_disable)(const struct device *dev);
/** Read data from MDIO bus */
int (*read)(const struct device *dev, uint8_t prtad, uint8_t regad,
uint16_t *data);
/** Write data to MDIO bus */
int (*write)(const struct device *dev, uint8_t prtad, uint8_t regad,
uint16_t data);
/** Read data from MDIO bus using Clause 45 access */
int (*read_c45)(const struct device *dev, uint8_t prtad, uint8_t devad,
uint16_t regad, uint16_t *data);
/** Write data to MDIO bus using Clause 45 access */
int (*write_c45)(const struct device *dev, uint8_t prtad, uint8_t devad,
uint16_t regad, uint16_t data);
};
/**
* @endcond
*/
/**
* @brief Enable MDIO bus
*
* @param[in] dev Pointer to the device structure for the controller
*
*/
__syscall void mdio_bus_enable(const struct device *dev);
static inline void z_impl_mdio_bus_enable(const struct device *dev)
{
const struct mdio_driver_api *api =
(const struct mdio_driver_api *)dev->api;
if (api->bus_enable != NULL) {
api->bus_enable(dev);
}
}
/**
* @brief Disable MDIO bus and tri-state drivers
*
* @param[in] dev Pointer to the device structure for the controller
*
*/
__syscall void mdio_bus_disable(const struct device *dev);
static inline void z_impl_mdio_bus_disable(const struct device *dev)
{
const struct mdio_driver_api *api =
(const struct mdio_driver_api *)dev->api;
if (api->bus_disable != NULL) {
api->bus_disable(dev);
}
}
/**
* @brief Read from MDIO Bus
*
* This routine provides a generic interface to perform a read on the
* MDIO bus.
*
* @param[in] dev Pointer to the device structure for the controller
* @param[in] prtad Port address
* @param[in] regad Register address
* @param data Pointer to receive read data
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ETIMEDOUT If transaction timedout on the bus
* @retval -ENOSYS if read is not supported
*/
__syscall int mdio_read(const struct device *dev, uint8_t prtad, uint8_t regad,
uint16_t *data);
static inline int z_impl_mdio_read(const struct device *dev, uint8_t prtad,
uint8_t regad, uint16_t *data)
{
const struct mdio_driver_api *api =
(const struct mdio_driver_api *)dev->api;
if (api->read == NULL) {
return -ENOSYS;
}
return api->read(dev, prtad, regad, data);
}
/**
* @brief Write to MDIO bus
*
* This routine provides a generic interface to perform a write on the
* MDIO bus.
*
* @param[in] dev Pointer to the device structure for the controller
* @param[in] prtad Port address
* @param[in] regad Register address
* @param[in] data Data to write
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ETIMEDOUT If transaction timedout on the bus
* @retval -ENOSYS if write is not supported
*/
__syscall int mdio_write(const struct device *dev, uint8_t prtad, uint8_t regad,
uint16_t data);
static inline int z_impl_mdio_write(const struct device *dev, uint8_t prtad,
uint8_t regad, uint16_t data)
{
const struct mdio_driver_api *api =
(const struct mdio_driver_api *)dev->api;
if (api->write == NULL) {
return -ENOSYS;
}
return api->write(dev, prtad, regad, data);
}
/**
* @brief Read from MDIO Bus using Clause 45 access
*
* This routine provides an interface to perform a read on the MDIO bus using
* IEEE 802.3 Clause 45 access.
*
* @param[in] dev Pointer to the device structure for the controller
* @param[in] prtad Port address
* @param[in] devad Device address
* @param[in] regad Register address
* @param data Pointer to receive read data
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ETIMEDOUT If transaction timedout on the bus
* @retval -ENOSYS if write using Clause 45 access is not supported
*/
__syscall int mdio_read_c45(const struct device *dev, uint8_t prtad,
uint8_t devad, uint16_t regad, uint16_t *data);
static inline int z_impl_mdio_read_c45(const struct device *dev, uint8_t prtad,
uint8_t devad, uint16_t regad,
uint16_t *data)
{
const struct mdio_driver_api *api =
(const struct mdio_driver_api *)dev->api;
if (api->read_c45 == NULL) {
return -ENOSYS;
}
return api->read_c45(dev, prtad, devad, regad, data);
}
/**
* @brief Write to MDIO bus using Clause 45 access
*
* This routine provides an interface to perform a write on the MDIO bus using
* IEEE 802.3 Clause 45 access.
*
* @param[in] dev Pointer to the device structure for the controller
* @param[in] prtad Port address
* @param[in] devad Device address
* @param[in] regad Register address
* @param[in] data Data to write
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ETIMEDOUT If transaction timedout on the bus
* @retval -ENOSYS if write using Clause 45 access is not supported
*/
__syscall int mdio_write_c45(const struct device *dev, uint8_t prtad,
uint8_t devad, uint16_t regad, uint16_t data);
static inline int z_impl_mdio_write_c45(const struct device *dev, uint8_t prtad,
uint8_t devad, uint16_t regad,
uint16_t data)
{
const struct mdio_driver_api *api =
(const struct mdio_driver_api *)dev->api;
if (api->write_c45 == NULL) {
return -ENOSYS;
}
return api->write_c45(dev, prtad, devad, regad, data);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/mdio.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_MDIO_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/mdio.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,736 |
```objective-c
/*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_MBOX_H_
#define ZEPHYR_INCLUDE_DRIVERS_MBOX_H_
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief MBOX Interface
* @defgroup mbox_interface MBOX Interface
* @since 1.0
* @version 0.1.0
* @ingroup io_interfaces
* @{
*
* @code{.unparsed}
*
* CPU #1 |
* +----------+ | +----------+
* | +---TX9----+ +--------+--RX8---+ |
* | dev A | | | | | CPU #2 |
* | <---RX8--+ | | +------+--TX9---> |
* +----------+ | | | | | +----------+
* +--+-v---v-+--+ |
* | | |
* | MBOX dev | |
* | | |
* +--+-^---^--+-+ |
* +----------+ | | | | | +----------+
* | <---RX2--+ | | +-----+--TX3---> |
* | dev B | | | | | CPU #3 |
* | +---TX3----+ +--------+--RX2---+ |
* +----------+ | +----------+
* |
*
* @endcode
*
* An MBOX device is a peripheral capable of passing signals (and data depending
* on the peripheral) between CPUs and clusters in the system. Each MBOX
* instance is providing one or more channels, each one targeting one other CPU
* cluster (multiple channels can target the same cluster).
*
* For example in the plot the device 'dev A' is using the TX channel 9 to
* signal (or send data to) the CPU #2 and it's expecting data or signals on
* the RX channel 8. Thus it can send the message through the channel 9, and it
* can register a callback on the channel 8 of the MBOX device.
*
* This API supports two modes: signalling mode and data transfer mode.
*
* In signalling mode:
* - mbox_mtu_get() must return 0
* - mbox_send() must have (msg == NULL)
* - the callback must be called with (data == NULL)
*
* In data transfer mode:
* - mbox_mtu_get() must return a (value != 0)
* - mbox_send() must have (msg != NULL)
* - the callback must be called with (data != NULL)
* - The msg content must be the same between sender and receiver
*
*/
/** @brief Type for MBOX channel identifiers */
typedef uint32_t mbox_channel_id_t;
/** @brief Message struct (to hold data and its size). */
struct mbox_msg {
/** Pointer to the data sent in the message. */
const void *data;
/** Size of the data. */
size_t size;
};
/** @brief MBOX specification from DT */
struct mbox_dt_spec {
/** MBOX device pointer. */
const struct device *dev;
/** Channel ID. */
mbox_channel_id_t channel_id;
};
/**
* @brief Structure initializer for struct mbox_dt_spec from devicetree
*
* This helper macro expands to a static initializer for a struct mbox_dt_spec
* by reading the relevant device controller and channel number from the
* devicetree.
*
* Example devicetree fragment:
*
* @code{.devicetree}
* n: node {
* mboxes = <&mbox1 8>,
* <&mbox1 9>;
* mbox-names = "tx", "rx";
* };
* @endcode
*
* Example usage:
*
* @code{.c}
* const struct mbox_dt_spec spec = MBOX_DT_SPEC_GET(DT_NODELABEL(n), tx);
* @endcode
*
* @param node_id Devicetree node identifier for the MBOX device
* @param name lowercase-and-underscores name of the mboxes element
*
* @return static initializer for a struct mbox_dt_spec
*/
#define MBOX_DT_SPEC_GET(node_id, name) \
{ \
.dev = DEVICE_DT_GET(DT_MBOX_CTLR_BY_NAME(node_id, name)), \
.channel_id = DT_MBOX_CHANNEL_BY_NAME(node_id, name), \
}
/**
* @brief Instance version of MBOX_DT_CHANNEL_GET()
*
* @param inst DT_DRV_COMPAT instance number
* @param name lowercase-and-underscores name of the mboxes element
*
* @return static initializer for a struct mbox_dt_spec
*/
#define MBOX_DT_SPEC_INST_GET(inst, name) \
MBOX_DT_SPEC_GET(DT_DRV_INST(inst), name)
/** @cond INTERNAL_HIDDEN */
/**
* @brief Callback API for incoming MBOX messages
*
* These callbacks execute in interrupt context. Therefore, use only
* interrupt-safe APIs. Registration of callbacks is done via
* mbox_register_callback()
*
* The data parameter must be NULL in signalling mode.
*
* @param dev MBOX device instance
* @param channel_id Channel ID
* @param user_data Pointer to some private data provided at registration time
* @param data Message struct
*/
typedef void (*mbox_callback_t)(const struct device *dev,
mbox_channel_id_t channel_id, void *user_data,
struct mbox_msg *data);
/**
* @brief Callback API to send MBOX messages
*
* @param dev MBOX device instance
* @param channel_id Channel ID
* @param msg Message struct
*
* @return See the return values for mbox_send()
* @see mbox_send()
*/
typedef int (*mbox_send_t)(const struct device *dev,
mbox_channel_id_t channel_id,
const struct mbox_msg *msg);
/**
* @brief Callback API to get maximum data size
*
* @param dev MBOX device instance
*
* @return See the return values for mbox_mtu_get()
* @see mbox_mtu_get()
*/
typedef int (*mbox_mtu_get_t)(const struct device *dev);
/**
* @brief Callback API upon registration
*
* @param dev MBOX device instance
* @param channel_id Channel ID
* @param cb Callback function to execute on incoming message interrupts.
* @param user_data Application-specific data pointer which will be passed to
* the callback function when executed.
*
* @return See return values for mbox_register_callback()
* @see mbox_register_callback()
*/
typedef int (*mbox_register_callback_t)(const struct device *dev,
mbox_channel_id_t channel_id,
mbox_callback_t cb, void *user_data);
/**
* @brief Callback API upon enablement of interrupts
*
* @param dev MBOX device instance
* @param channel_id Channel ID
* @param enables Set to 0 to disable and to nonzero to enable.
*
* @return See return values for mbox_set_enabled()
* @see mbox_set_enabled()
*/
typedef int (*mbox_set_enabled_t)(const struct device *dev,
mbox_channel_id_t channel_id, bool enabled);
/**
* @brief Callback API to get maximum number of channels
*
* @param dev MBOX device instance
*
* @return See return values for mbox_max_channels_get()
* @see mbox_max_channels_get()
*/
typedef uint32_t (*mbox_max_channels_get_t)(const struct device *dev);
__subsystem struct mbox_driver_api {
mbox_send_t send;
mbox_register_callback_t register_callback;
mbox_mtu_get_t mtu_get;
mbox_max_channels_get_t max_channels_get;
mbox_set_enabled_t set_enabled;
};
/** @endcond */
/**
* @brief Validate if MBOX device instance from a struct mbox_dt_spec is ready.
*
* @param spec MBOX specification from devicetree
*
* @return See return values for mbox_send()
*/
static inline bool mbox_is_ready_dt(const struct mbox_dt_spec *spec)
{
return device_is_ready(spec->dev);
}
/**
* @brief Try to send a message over the MBOX device.
*
* Send a message over an struct mbox_channel. The msg parameter must be NULL
* when the driver is used for signalling.
*
* If the msg parameter is not NULL, this data is expected to be delivered on
* the receiving side using the data parameter of the receiving callback.
*
* @param dev MBOX device instance
* @param channel_id MBOX channel identifier
* @param msg Message
*
* @retval 0 On success.
* @retval -EBUSY If the remote hasn't yet read the last data sent.
* @retval -EMSGSIZE If the supplied data size is unsupported by the driver.
* @retval -EINVAL If there was a bad parameter, such as: too-large channel
* descriptor or the device isn't an outbound MBOX channel.
*/
__syscall int mbox_send(const struct device *dev, mbox_channel_id_t channel_id,
const struct mbox_msg *msg);
static inline int z_impl_mbox_send(const struct device *dev,
mbox_channel_id_t channel_id,
const struct mbox_msg *msg)
{
const struct mbox_driver_api *api =
(const struct mbox_driver_api *)dev->api;
if (api->send == NULL) {
return -ENOSYS;
}
return api->send(dev, channel_id, msg);
}
/**
* @brief Try to send a message over the MBOX device from a struct mbox_dt_spec.
*
* @param spec MBOX specification from devicetree
* @param msg Message
*
* @return See return values for mbox_send()
*/
static inline int mbox_send_dt(const struct mbox_dt_spec *spec,
const struct mbox_msg *msg)
{
return mbox_send(spec->dev, spec->channel_id, msg);
}
/**
* @brief Register a callback function on a channel for incoming messages.
*
* This function doesn't assume anything concerning the status of the
* interrupts. Use mbox_set_enabled() to enable or to disable the interrupts
* if needed.
*
* @param dev MBOX device instance
* @param channel_id MBOX channel identifier
* @param cb Callback function to execute on incoming message interrupts.
* @param user_data Application-specific data pointer which will be passed
* to the callback function when executed.
*
* @retval 0 On success.
* @retval -errno Negative errno on error.
*/
static inline int mbox_register_callback(const struct device *dev,
mbox_channel_id_t channel_id,
mbox_callback_t cb,
void *user_data)
{
const struct mbox_driver_api *api =
(const struct mbox_driver_api *)dev->api;
if (api->register_callback == NULL) {
return -ENOSYS;
}
return api->register_callback(dev, channel_id, cb, user_data);
}
/**
* @brief Register a callback function on a channel for incoming messages from a
* struct mbox_dt_spec.
*
* @param spec MBOX specification from devicetree
* @param cb Callback function to execute on incoming message interrupts.
* @param user_data Application-specific data pointer which will be passed
* to the callback function when executed.
*
* @return See return values for mbox_register_callback()
*/
static inline int mbox_register_callback_dt(const struct mbox_dt_spec *spec,
mbox_callback_t cb, void *user_data)
{
return mbox_register_callback(spec->dev, spec->channel_id, cb,
user_data);
}
/**
* @brief Return the maximum number of bytes possible in an outbound message.
*
* Returns the actual number of bytes that it is possible to send through an
* outgoing channel.
*
* This number can be 0 when the driver only supports signalling or when on the
* receiving side the content and size of the message must be retrieved in an
* indirect way (i.e. probing some other peripheral, reading memory regions,
* etc...).
*
* If this function returns 0, the msg parameter in mbox_send() is expected
* to be NULL.
*
* @param dev MBOX device instance.
*
* @retval >0 Maximum possible size of a message in bytes
* @retval 0 Indicates signalling
* @retval -errno Negative errno on error.
*/
__syscall int mbox_mtu_get(const struct device *dev);
static inline int z_impl_mbox_mtu_get(const struct device *dev)
{
const struct mbox_driver_api *api =
(const struct mbox_driver_api *)dev->api;
if (api->mtu_get == NULL) {
return -ENOSYS;
}
return api->mtu_get(dev);
}
/**
* @brief Return the maximum number of bytes possible in an outbound message
* from struct mbox_dt_spec.
*
* @param spec MBOX specification from devicetree
*
* @return See return values for mbox_register_callback()
*/
static inline int mbox_mtu_get_dt(const struct mbox_dt_spec *spec)
{
return mbox_mtu_get(spec->dev);
}
/**
* @brief Enable (disable) interrupts and callbacks for inbound channels.
*
* Enable interrupt for the channel when the parameter 'enable' is set to true.
* Disable it otherwise.
*
* Immediately after calling this function with 'enable' set to true, the
* channel is considered enabled and ready to receive signal and messages (even
* already pending), so the user must take care of installing a proper callback
* (if needed) using mbox_register_callback() on the channel before enabling
* it. For this reason it is recommended that all the channels are disabled at
* probe time.
*
* Enabling a channel for which there is no installed callback is considered
* undefined behavior (in general the driver must take care of gracefully
* handling spurious interrupts with no installed callback).
*
* @param dev MBOX device instance
* @param channel_id MBOX channel identifier
* @param enabled Enable (true) or disable (false) the channel.
*
* @retval 0 On success.
* @retval -EINVAL If it isn't an inbound channel.
* @retval -EALREADY If channel is already @p enabled.
*/
__syscall int mbox_set_enabled(const struct device *dev,
mbox_channel_id_t channel_id, bool enabled);
static inline int z_impl_mbox_set_enabled(const struct device *dev,
mbox_channel_id_t channel_id,
bool enabled)
{
const struct mbox_driver_api *api =
(const struct mbox_driver_api *)dev->api;
if (api->set_enabled == NULL) {
return -ENOSYS;
}
return api->set_enabled(dev, channel_id, enabled);
}
/**
* @brief Enable (disable) interrupts and callbacks for inbound channels from a
* struct mbox_dt_spec.
*
* @param spec MBOX specification from devicetree
* @param enabled Enable (true) or disable (false) the channel.
*
* @return See return values for mbox_set_enabled()
*/
static inline int mbox_set_enabled_dt(const struct mbox_dt_spec *spec,
bool enabled)
{
return mbox_set_enabled(spec->dev, spec->channel_id, enabled);
}
/**
* @brief Return the maximum number of channels.
*
* Return the maximum number of channels supported by the hardware.
*
* @param dev MBOX device instance.
*
* @return >0 Maximum possible number of supported channels on success
* @return -errno Negative errno on error.
*/
__syscall uint32_t mbox_max_channels_get(const struct device *dev);
static inline uint32_t z_impl_mbox_max_channels_get(const struct device *dev)
{
const struct mbox_driver_api *api =
(const struct mbox_driver_api *)dev->api;
if (api->max_channels_get == NULL) {
return -ENOSYS;
}
return api->max_channels_get(dev);
}
/**
* @brief Return the maximum number of channels from a struct mbox_dt_spec.
*
* @param spec MBOX specification from devicetree
*
* @return See return values for mbox_max_channels_get()
*/
static inline int mbox_max_channels_get_dt(const struct mbox_dt_spec *spec)
{
return mbox_max_channels_get(spec->dev);
}
/** @} */
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/mbox.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_MBOX_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/mbox.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 3,524 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public API for PS/2 devices such as keyboard and mouse.
* Callers of this API are responsible for setting the typematic rate
* and decode keys using their desired scan code tables.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_PS2_H_
#define ZEPHYR_INCLUDE_DRIVERS_PS2_H_
#include <errno.h>
#include <zephyr/types.h>
#include <stddef.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief PS/2 Driver APIs
* @defgroup ps2_interface PS/2 Driver APIs
* @ingroup io_interfaces
* @{
*/
/**
* @brief PS/2 callback called when user types or click a mouse.
*
* @param dev Pointer to the device structure for the driver instance.
* @param data Data byte passed pack to the user.
*/
typedef void (*ps2_callback_t)(const struct device *dev, uint8_t data);
/**
* @cond INTERNAL_HIDDEN
*
* PS2 driver API definition and system call entry points
*
* (Internal use only.)
*/
typedef int (*ps2_config_t)(const struct device *dev,
ps2_callback_t callback_isr);
typedef int (*ps2_read_t)(const struct device *dev, uint8_t *value);
typedef int (*ps2_write_t)(const struct device *dev, uint8_t value);
typedef int (*ps2_disable_callback_t)(const struct device *dev);
typedef int (*ps2_enable_callback_t)(const struct device *dev);
__subsystem struct ps2_driver_api {
ps2_config_t config;
ps2_read_t read;
ps2_write_t write;
ps2_disable_callback_t disable_callback;
ps2_enable_callback_t enable_callback;
};
/**
* @endcond
*/
/**
* @brief Configure a ps2 instance.
*
* @param dev Pointer to the device structure for the driver instance.
* @param callback_isr called when PS/2 devices reply to a configuration
* command or when a mouse/keyboard send data to the client application.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int ps2_config(const struct device *dev,
ps2_callback_t callback_isr);
static inline int z_impl_ps2_config(const struct device *dev,
ps2_callback_t callback_isr)
{
const struct ps2_driver_api *api =
(struct ps2_driver_api *)dev->api;
return api->config(dev, callback_isr);
}
/**
* @brief Write to PS/2 device.
*
* @param dev Pointer to the device structure for the driver instance.
* @param value Data for the PS2 device.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int ps2_write(const struct device *dev, uint8_t value);
static inline int z_impl_ps2_write(const struct device *dev, uint8_t value)
{
const struct ps2_driver_api *api =
(const struct ps2_driver_api *)dev->api;
return api->write(dev, value);
}
/**
* @brief Read slave-to-host values from PS/2 device.
* @param dev Pointer to the device structure for the driver instance.
* @param value Pointer used for reading the PS/2 device.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int ps2_read(const struct device *dev, uint8_t *value);
static inline int z_impl_ps2_read(const struct device *dev, uint8_t *value)
{
const struct ps2_driver_api *api =
(const struct ps2_driver_api *)dev->api;
return api->read(dev, value);
}
/**
* @brief Enables callback.
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int ps2_enable_callback(const struct device *dev);
static inline int z_impl_ps2_enable_callback(const struct device *dev)
{
const struct ps2_driver_api *api =
(const struct ps2_driver_api *)dev->api;
if (api->enable_callback == NULL) {
return -ENOSYS;
}
return api->enable_callback(dev);
}
/**
* @brief Disables callback.
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int ps2_disable_callback(const struct device *dev);
static inline int z_impl_ps2_disable_callback(const struct device *dev)
{
const struct ps2_driver_api *api =
(const struct ps2_driver_api *)dev->api;
if (api->disable_callback == NULL) {
return -ENOSYS;
}
return api->disable_callback(dev);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/ps2.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_PS2_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/ps2.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,061 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public Platform Environment Control Interface driver APIs
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_PECI_H_
#define ZEPHYR_INCLUDE_DRIVERS_PECI_H_
/**
* @brief PECI Interface 3.0
* @defgroup peci_interface PECI Interface
* @since 2.1
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <stddef.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief PECI error codes.
*/
enum peci_error_code {
PECI_GENERAL_SENSOR_ERROR = 0x8000,
PECI_UNDERFLOW_SENSOR_ERROR = 0x8002,
PECI_OVERFLOW_SENSOR_ERROR = 0x8003,
};
/**
* @brief PECI commands.
*/
enum peci_command_code {
PECI_CMD_PING = 0x00,
PECI_CMD_GET_TEMP0 = 0x01,
PECI_CMD_GET_TEMP1 = 0x02,
PECI_CMD_RD_PCI_CFG0 = 0x61,
PECI_CMD_RD_PCI_CFG1 = 0x62,
PECI_CMD_WR_PCI_CFG0 = 0x65,
PECI_CMD_WR_PCI_CFG1 = 0x66,
PECI_CMD_RD_PKG_CFG0 = 0xA1,
PECI_CMD_RD_PKG_CFG1 = 0xA,
PECI_CMD_WR_PKG_CFG0 = 0xA5,
PECI_CMD_WR_PKG_CFG1 = 0xA6,
PECI_CMD_RD_IAMSR0 = 0xB1,
PECI_CMD_RD_IAMSR1 = 0xB2,
PECI_CMD_WR_IAMSR0 = 0xB5,
PECI_CMD_WR_IAMSR1 = 0xB6,
PECI_CMD_RD_PCI_CFG_LOCAL0 = 0xE1,
PECI_CMD_RD_PCI_CFG_LOCAL1 = 0xE2,
PECI_CMD_WR_PCI_CFG_LOCAL0 = 0xE5,
PECI_CMD_WR_PCI_CFG_LOCAL1 = 0xE6,
PECI_CMD_GET_DIB = 0xF7,
};
/**
* @name PECI read/write supported responses.
* @{
*/
#define PECI_CC_RSP_SUCCESS (0x40U)
#define PECI_CC_RSP_TIMEOUT (0x80U)
#define PECI_CC_OUT_OF_RESOURCES_TIMEOUT (0x81U)
#define PECI_CC_RESOURCES_LOWPWR_TIMEOUT (0x82U)
#define PECI_CC_ILLEGAL_REQUEST (0x90U)
/** @} */
/**
* @name Ping command format.
* @{
*/
#define PECI_PING_WR_LEN (0U)
#define PECI_PING_RD_LEN (0U)
#define PECI_PING_LEN (3U)
/** @} */
/**
* @name GetDIB command format.
* @{
*/
#define PECI_GET_DIB_WR_LEN (1U)
#define PECI_GET_DIB_RD_LEN (8U)
#define PECI_GET_DIB_CMD_LEN (4U)
#define PECI_GET_DIB_DEVINFO (0U)
#define PECI_GET_DIB_REVNUM (1U)
#define PECI_GET_DIB_DOMAIN_BIT_MASK (0x4U)
#define PECI_GET_DIB_MAJOR_REV_MASK 0xF0
#define PECI_GET_DIB_MINOR_REV_MASK 0x0F
/** @} */
/**
* @name GetTemp command format.
* @{
*/
#define PECI_GET_TEMP_WR_LEN (1U)
#define PECI_GET_TEMP_RD_LEN (2U)
#define PECI_GET_TEMP_CMD_LEN (4U)
#define PECI_GET_TEMP_LSB (0U)
#define PECI_GET_TEMP_MSB (1U)
#define PECI_GET_TEMP_ERR_MSB (0x80U)
#define PECI_GET_TEMP_ERR_LSB_GENERAL (0x0U)
#define PECI_GET_TEMP_ERR_LSB_RES (0x1U)
#define PECI_GET_TEMP_ERR_LSB_TEMP_LO (0x2U)
#define PECI_GET_TEMP_ERR_LSB_TEMP_HI (0x3U)
/** @} */
/**
* @name RdPkgConfig command format.
* @{
*/
#define PECI_RD_PKG_WR_LEN (5U)
#define PECI_RD_PKG_LEN_BYTE (2U)
#define PECI_RD_PKG_LEN_WORD (3U)
#define PECI_RD_PKG_LEN_DWORD (5U)
#define PECI_RD_PKG_CMD_LEN (8U)
/** @} */
/**
* @name WrPkgConfig command format.
* @{
*/
#define PECI_WR_PKG_RD_LEN (1U)
#define PECI_WR_PKG_LEN_BYTE (7U)
#define PECI_WR_PKG_LEN_WORD (8U)
#define PECI_WR_PKG_LEN_DWORD (10U)
#define PECI_WR_PKG_CMD_LEN (9U)
/** @} */
/**
* @name RdIAMSR command format.
* @{
*/
#define PECI_RD_IAMSR_WR_LEN (5U)
#define PECI_RD_IAMSR_LEN_BYTE (2U)
#define PECI_RD_IAMSR_LEN_WORD (3U)
#define PECI_RD_IAMSR_LEN_DWORD (5U)
#define PECI_RD_IAMSR_LEN_QWORD (9U)
#define PECI_RD_IAMSR_CMD_LEN (8U)
/** @} */
/**
* @name WrIAMSR command format.
* @{
*/
#define PECI_WR_IAMSR_RD_LEN (1U)
#define PECI_WR_IAMSR_LEN_BYTE (7U)
#define PECI_WR_IAMSR_LEN_WORD (8U)
#define PECI_WR_IAMSR_LEN_DWORD (10U)
#define PECI_WR_IAMSR_LEN_QWORD (14U)
#define PECI_WR_IAMSR_CMD_LEN (9U)
/** @} */
/**
* @name RdPCIConfig command format.
* @{
*/
#define PECI_RD_PCICFG_WR_LEN (6U)
#define PECI_RD_PCICFG_LEN_BYTE (2U)
#define PECI_RD_PCICFG_LEN_WORD (3U)
#define PECI_RD_PCICFG_LEN_DWORD (5U)
#define PECI_RD_PCICFG_CMD_LEN (9U)
/** @} */
/**
* @name WrPCIConfig command format.
* @{
*/
#define PECI_WR_PCICFG_RD_LEN (1U)
#define PECI_WR_PCICFG_LEN_BYTE (8U)
#define PECI_WR_PCICFG_LEN_WORD (9U)
#define PECI_WR_PCICFG_LEN_DWORD (11U)
#define PECI_WR_PCICFG_CMD_LEN (10U)
/** @} */
/**
* @name RdPCIConfigLocal command format.
* @{
*/
#define PECI_RD_PCICFGL_WR_LEN (5U)
#define PECI_RD_PCICFGL_RD_LEN_BYTE (2U)
#define PECI_RD_PCICFGL_RD_LEN_WORD (3U)
#define PECI_RD_PCICFGL_RD_LEN_DWORD (5U)
#define PECI_RD_PCICFGL_CMD_LEN (8U)
/** @} */
/**
* @name WrPCIConfigLocal command format.
* @{
*/
#define PECI_WR_PCICFGL_RD_LEN (1U)
#define PECI_WR_PCICFGL_WR_LEN_BYTE (7U)
#define PECI_WR_PCICFGL_WR_LEN_WORD (8U)
#define PECI_WR_PCICFGL_WR_LEN_DWORD (10U)
#define PECI_WR_PCICFGL_CMD_LEN (9U)
/** @} */
/**
* @brief PECI buffer structure
*/
struct peci_buf {
/**
* Valid pointer on a data buffer, or NULL otherwise.
*/
uint8_t *buf;
/**
* Length of the data buffer expected to be received without considering
* the frame check sequence byte.
*
* @note Frame check sequence byte is added into rx buffer: need to allocate
* an additional byte for this in rx buffer.
*/
size_t len;
};
/**
* @brief PECI transaction packet format.
*/
struct peci_msg {
/** Client address */
uint8_t addr;
/** Command code */
enum peci_command_code cmd_code;
/** Pointer to buffer of write data */
struct peci_buf tx_buffer;
/** Pointer to buffer of read data */
struct peci_buf rx_buffer;
/** PECI msg flags */
uint8_t flags;
};
/**
* @cond INTERNAL_HIDDEN
*
* PECI driver API definition and system call entry points
*
* (Internal use only.)
*/
typedef int (*peci_config_t)(const struct device *dev, uint32_t bitrate);
typedef int (*peci_transfer_t)(const struct device *dev, struct peci_msg *msg);
typedef int (*peci_disable_t)(const struct device *dev);
typedef int (*peci_enable_t)(const struct device *dev);
__subsystem struct peci_driver_api {
peci_config_t config;
peci_disable_t disable;
peci_enable_t enable;
peci_transfer_t transfer;
};
/**
* @endcond
*/
/**
* @brief Configures the PECI interface.
*
* @param dev Pointer to the device structure for the driver instance.
* @param bitrate the selected bitrate expressed in Kbps.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int peci_config(const struct device *dev, uint32_t bitrate);
static inline int z_impl_peci_config(const struct device *dev,
uint32_t bitrate)
{
struct peci_driver_api *api;
api = (struct peci_driver_api *)dev->api;
return api->config(dev, bitrate);
}
/**
* @brief Enable PECI interface.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int peci_enable(const struct device *dev);
static inline int z_impl_peci_enable(const struct device *dev)
{
struct peci_driver_api *api;
api = (struct peci_driver_api *)dev->api;
return api->enable(dev);
}
/**
* @brief Disable PECI interface.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int peci_disable(const struct device *dev);
static inline int z_impl_peci_disable(const struct device *dev)
{
struct peci_driver_api *api;
api = (struct peci_driver_api *)dev->api;
return api->disable(dev);
}
/**
* @brief Performs a PECI transaction.
*
* @param dev Pointer to the device structure for the driver instance.
* @param msg Structure representing a PECI transaction.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int peci_transfer(const struct device *dev, struct peci_msg *msg);
static inline int z_impl_peci_transfer(const struct device *dev,
struct peci_msg *msg)
{
struct peci_driver_api *api;
api = (struct peci_driver_api *)dev->api;
return api->transfer(dev, msg);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/peci.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_PECI_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/peci.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,547 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public Reset Controller driver APIs
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_RESET_H_
#define ZEPHYR_INCLUDE_DRIVERS_RESET_H_
/**
* @brief Reset Controller Interface
* @defgroup reset_controller_interface Reset Controller Interface
* @since 3.1
* @version 0.2.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Reset controller device configuration. */
struct reset_dt_spec {
/** Reset controller device. */
const struct device *dev;
/** Reset line. */
uint32_t id;
};
/**
* @brief Static initializer for a @p reset_dt_spec
*
* This returns a static initializer for a @p reset_dt_spec structure given a
* devicetree node identifier, a property specifying a Reset Controller and an index.
*
* Example devicetree fragment:
*
* n: node {
* resets = <&reset 10>;
* }
*
* Example usage:
*
* const struct reset_dt_spec spec = RESET_DT_SPEC_GET_BY_IDX(DT_NODELABEL(n), 0);
* // Initializes 'spec' to:
* // {
* // .dev = DEVICE_DT_GET(DT_NODELABEL(reset)),
* // .id = 10
* // }
*
* The 'reset' field must still be checked for readiness, e.g. using
* device_is_ready(). It is an error to use this macro unless the node
* exists, has the given property, and that property specifies a reset
* controller reset line id as shown above.
*
* @param node_id devicetree node identifier
* @param idx logical index into "resets"
* @return static initializer for a struct reset_dt_spec for the property
*/
#define RESET_DT_SPEC_GET_BY_IDX(node_id, idx) \
{ \
.dev = DEVICE_DT_GET(DT_RESET_CTLR_BY_IDX(node_id, idx)), \
.id = DT_RESET_ID_BY_IDX(node_id, idx) \
}
/**
* @brief Like RESET_DT_SPEC_GET_BY_IDX(), with a fallback to a default value
*
* If the devicetree node identifier 'node_id' refers to a node with a
* 'resets' property, this expands to
* <tt>RESET_DT_SPEC_GET_BY_IDX(node_id, idx)</tt>. The @p
* default_value parameter is not expanded in this case.
*
* Otherwise, this expands to @p default_value.
*
* @param node_id devicetree node identifier
* @param idx logical index into the 'resets' property
* @param default_value fallback value to expand to
* @return static initializer for a struct reset_dt_spec for the property,
* or default_value if the node or property do not exist
*/
#define RESET_DT_SPEC_GET_BY_IDX_OR(node_id, idx, default_value) \
COND_CODE_1(DT_NODE_HAS_PROP(node_id, resets), \
(RESET_DT_SPEC_GET_BY_IDX(node_id, idx)), \
(default_value))
/**
* @brief Equivalent to RESET_DT_SPEC_GET_BY_IDX(node_id, 0).
*
* @param node_id devicetree node identifier
* @return static initializer for a struct reset_dt_spec for the property
* @see RESET_DT_SPEC_GET_BY_IDX()
*/
#define RESET_DT_SPEC_GET(node_id) \
RESET_DT_SPEC_GET_BY_IDX(node_id, 0)
/**
* @brief Equivalent to
* RESET_DT_SPEC_GET_BY_IDX_OR(node_id, 0, default_value).
*
* @param node_id devicetree node identifier
* @param default_value fallback value to expand to
* @return static initializer for a struct reset_dt_spec for the property,
* or default_value if the node or property do not exist
*/
#define RESET_DT_SPEC_GET_OR(node_id, default_value) \
RESET_DT_SPEC_GET_BY_IDX_OR(node_id, 0, default_value)
/**
* @brief Static initializer for a @p reset_dt_spec from a DT_DRV_COMPAT
* instance's Reset Controller property at an index.
*
* @param inst DT_DRV_COMPAT instance number
* @param idx logical index into "resets"
* @return static initializer for a struct reset_dt_spec for the property
* @see RESET_DT_SPEC_GET_BY_IDX()
*/
#define RESET_DT_SPEC_INST_GET_BY_IDX(inst, idx) \
RESET_DT_SPEC_GET_BY_IDX(DT_DRV_INST(inst), idx)
/**
* @brief Static initializer for a @p reset_dt_spec from a DT_DRV_COMPAT
* instance's 'resets' property at an index, with fallback
*
* @param inst DT_DRV_COMPAT instance number
* @param idx logical index into the 'resets' property
* @param default_value fallback value to expand to
* @return static initializer for a struct reset_dt_spec for the property,
* or default_value if the node or property do not exist
*/
#define RESET_DT_SPEC_INST_GET_BY_IDX_OR(inst, idx, default_value) \
COND_CODE_1(DT_PROP_HAS_IDX(DT_DRV_INST(inst), resets, idx), \
(RESET_DT_SPEC_GET_BY_IDX(DT_DRV_INST(inst), idx)), \
(default_value))
/**
* @brief Equivalent to RESET_DT_SPEC_INST_GET_BY_IDX(inst, 0).
*
* @param inst DT_DRV_COMPAT instance number
* @return static initializer for a struct reset_dt_spec for the property
* @see RESET_DT_SPEC_INST_GET_BY_IDX()
*/
#define RESET_DT_SPEC_INST_GET(inst) \
RESET_DT_SPEC_INST_GET_BY_IDX(inst, 0)
/**
* @brief Equivalent to
* RESET_DT_SPEC_INST_GET_BY_IDX_OR(node_id, 0, default_value).
*
* @param inst DT_DRV_COMPAT instance number
* @param default_value fallback value to expand to
* @return static initializer for a struct reset_dt_spec for the property,
* or default_value if the node or property do not exist
*/
#define RESET_DT_SPEC_INST_GET_OR(inst, default_value) \
RESET_DT_SPEC_INST_GET_BY_IDX_OR(inst, 0, default_value)
/** @cond INTERNAL_HIDDEN */
/**
* API template to get the reset status of the device.
*
* @see reset_status
*/
typedef int (*reset_api_status)(const struct device *dev, uint32_t id, uint8_t *status);
/**
* API template to put the device in reset state.
*
* @see reset_line_assert
*/
typedef int (*reset_api_line_assert)(const struct device *dev, uint32_t id);
/**
* API template to take out the device from reset state.
*
* @see reset_line_deassert
*/
typedef int (*reset_api_line_deassert)(const struct device *dev, uint32_t id);
/**
* API template to reset the device.
*
* @see reset_line_toggle
*/
typedef int (*reset_api_line_toggle)(const struct device *dev, uint32_t id);
/**
* @brief Reset Controller driver API
*/
__subsystem struct reset_driver_api {
reset_api_status status;
reset_api_line_assert line_assert;
reset_api_line_deassert line_deassert;
reset_api_line_toggle line_toggle;
};
/** @endcond */
/**
* @brief Get the reset status
*
* This function returns the reset status of the device.
*
* @param dev Reset controller device.
* @param id Reset line.
* @param status Where to write the reset status.
*
* @retval 0 On success.
* @retval -ENOSYS If the functionality is not implemented by the driver.
* @retval -errno Other negative errno in case of failure.
*/
__syscall int reset_status(const struct device *dev, uint32_t id, uint8_t *status);
static inline int z_impl_reset_status(const struct device *dev, uint32_t id, uint8_t *status)
{
const struct reset_driver_api *api = (const struct reset_driver_api *)dev->api;
if (api->status == NULL) {
return -ENOSYS;
}
return api->status(dev, id, status);
}
/**
* @brief Get the reset status from a @p reset_dt_spec.
*
* This is equivalent to:
*
* reset_status(spec->dev, spec->id, status);
*
* @param spec Reset controller specification from devicetree
* @param status Where to write the reset status.
*
* @return a value from reset_status()
*/
static inline int reset_status_dt(const struct reset_dt_spec *spec, uint8_t *status)
{
return reset_status(spec->dev, spec->id, status);
}
/**
* @brief Put the device in reset state
*
* This function sets/clears the reset bits of the device,
* depending on the logic level (active-high/active-low).
*
* @param dev Reset controller device.
* @param id Reset line.
*
* @retval 0 On success.
* @retval -ENOSYS If the functionality is not implemented by the driver.
* @retval -errno Other negative errno in case of failure.
*/
__syscall int reset_line_assert(const struct device *dev, uint32_t id);
static inline int z_impl_reset_line_assert(const struct device *dev, uint32_t id)
{
const struct reset_driver_api *api = (const struct reset_driver_api *)dev->api;
if (api->line_assert == NULL) {
return -ENOSYS;
}
return api->line_assert(dev, id);
}
/**
* @brief Assert the reset state from a @p reset_dt_spec.
*
* This is equivalent to:
*
* reset_line_assert(spec->dev, spec->id);
*
* @param spec Reset controller specification from devicetree
*
* @return a value from reset_line_assert()
*/
static inline int reset_line_assert_dt(const struct reset_dt_spec *spec)
{
return reset_line_assert(spec->dev, spec->id);
}
/**
* @brief Take out the device from reset state.
*
* This function sets/clears the reset bits of the device,
* depending on the logic level (active-low/active-high).
*
* @param dev Reset controller device.
* @param id Reset line.
*
* @retval 0 On success.
* @retval -ENOSYS If the functionality is not implemented by the driver.
* @retval -errno Other negative errno in case of failure.
*/
__syscall int reset_line_deassert(const struct device *dev, uint32_t id);
static inline int z_impl_reset_line_deassert(const struct device *dev, uint32_t id)
{
const struct reset_driver_api *api = (const struct reset_driver_api *)dev->api;
if (api->line_deassert == NULL) {
return -ENOSYS;
}
return api->line_deassert(dev, id);
}
/**
* @brief Deassert the reset state from a @p reset_dt_spec.
*
* This is equivalent to:
*
* reset_line_deassert(spec->dev, spec->id)
*
* @param spec Reset controller specification from devicetree
*
* @return a value from reset_line_deassert()
*/
static inline int reset_line_deassert_dt(const struct reset_dt_spec *spec)
{
return reset_line_deassert(spec->dev, spec->id);
}
/**
* @brief Reset the device.
*
* This function performs reset for a device (assert + deassert).
*
* @param dev Reset controller device.
* @param id Reset line.
*
* @retval 0 On success.
* @retval -ENOSYS If the functionality is not implemented by the driver.
* @retval -errno Other negative errno in case of failure.
*/
__syscall int reset_line_toggle(const struct device *dev, uint32_t id);
static inline int z_impl_reset_line_toggle(const struct device *dev, uint32_t id)
{
const struct reset_driver_api *api = (const struct reset_driver_api *)dev->api;
if (api->line_toggle == NULL) {
return -ENOSYS;
}
return api->line_toggle(dev, id);
}
/**
* @brief Reset the device from a @p reset_dt_spec.
*
* This is equivalent to:
*
* reset_line_toggle(spec->dev, spec->id)
*
* @param spec Reset controller specification from devicetree
*
* @return a value from reset_line_toggle()
*/
static inline int reset_line_toggle_dt(const struct reset_dt_spec *spec)
{
return reset_line_toggle(spec->dev, spec->id);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/reset.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_RESET_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/reset.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,694 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_SENSOR_DATA_TYPES_H
#define ZEPHYR_INCLUDE_DRIVERS_SENSOR_DATA_TYPES_H
#include <zephyr/dsp/types.h>
#include <zephyr/dsp/print_format.h>
#include <inttypes.h>
#ifdef __cplusplus
extern "C" {
#endif
struct sensor_data_header {
/**
* The closest timestamp for when the first frame was generated as attained by
* :c:func:`k_uptime_ticks`.
*/
uint64_t base_timestamp_ns;
/**
* The number of elements in the 'readings' array.
*
* This must be at least 1
*/
uint16_t reading_count;
};
/**
* Data for a sensor channel which reports on three axes. This is used by:
* - :c:enum:`SENSOR_CHAN_ACCEL_X`
* - :c:enum:`SENSOR_CHAN_ACCEL_Y`
* - :c:enum:`SENSOR_CHAN_ACCEL_Z`
* - :c:enum:`SENSOR_CHAN_ACCEL_XYZ`
* - :c:enum:`SENSOR_CHAN_GYRO_X`
* - :c:enum:`SENSOR_CHAN_GYRO_Y`
* - :c:enum:`SENSOR_CHAN_GYRO_Z`
* - :c:enum:`SENSOR_CHAN_GYRO_XYZ`
* - :c:enum:`SENSOR_CHAN_MAGN_X`
* - :c:enum:`SENSOR_CHAN_MAGN_Y`
* - :c:enum:`SENSOR_CHAN_MAGN_Z`
* - :c:enum:`SENSOR_CHAN_MAGN_XYZ`
* - :c:enum:`SENSOR_CHAN_POS_DX`
* - :c:enum:`SENSOR_CHAN_POS_DY`
* - :c:enum:`SENSOR_CHAN_POS_DZ`
* - :c:enum:`SENSOR_CHAN_POS_DXYZ`
*/
struct sensor_three_axis_data {
struct sensor_data_header header;
int8_t shift;
struct sensor_three_axis_sample_data {
uint32_t timestamp_delta;
union {
q31_t values[3];
q31_t v[3];
struct {
q31_t x;
q31_t y;
q31_t z;
};
};
} readings[1];
};
#define PRIsensor_three_axis_data PRIu64 "ns, (%" PRIq(6) ", %" PRIq(6) ", %" PRIq(6) ")"
#define PRIsensor_three_axis_data_arg(data_, readings_offset_) \
(data_).header.base_timestamp_ns + (data_).readings[(readings_offset_)].timestamp_delta, \
PRIq_arg((data_).readings[(readings_offset_)].x, 6, (data_).shift), \
PRIq_arg((data_).readings[(readings_offset_)].y, 6, (data_).shift), \
PRIq_arg((data_).readings[(readings_offset_)].z, 6, (data_).shift)
/**
* Data from a sensor where we only care about an event occurring. This is used to report triggers.
*/
struct sensor_occurrence_data {
struct sensor_data_header header;
struct sensor_occurrence_sample_data {
uint32_t timestamp_delta;
} readings[1];
};
#define PRIsensor_occurrence_data PRIu64 "ns"
#define PRIsensor_occurrence_data_arg(data_, readings_offset_) \
(data_).header.base_timestamp_ns + (data_).readings[(readings_offset_)].timestamp_delta
struct sensor_q31_data {
struct sensor_data_header header;
int8_t shift;
struct sensor_q31_sample_data {
uint32_t timestamp_delta;
union {
q31_t value;
q31_t light; /**< Unit: lux */
q31_t pressure; /**< Unit: kilopascal */
q31_t temperature; /**< Unit: degrees Celsius */
q31_t percent; /**< Unit: percent */
q31_t distance; /**< Unit: meters */
q31_t density; /**< Unit: ug/m^3 */
q31_t density_ppm; /**< Unit: parts per million */
q31_t density_ppb; /**< Unit: parts per billion */
q31_t resistance; /**< Unit: ohms */
q31_t voltage; /**< Unit: volts */
q31_t current; /**< Unit: amps */
q31_t power; /**< Unit: watts */
q31_t angle; /**< Unit: degrees */
q31_t electric_charge; /**< Unit: mAh */
q31_t humidity; /**< Unit: RH */
};
} readings[1];
};
#define PRIsensor_q31_data PRIu64 "ns (%" PRIq(6) ")"
#define PRIsensor_q31_data_arg(data_, readings_offset_) \
(data_).header.base_timestamp_ns + (data_).readings[(readings_offset_)].timestamp_delta, \
PRIq_arg((data_).readings[(readings_offset_)].value, 6, (data_).shift)
/**
* Data from a sensor that produces a byte of data. This is used by:
* - :c:enum:`SENSOR_CHAN_PROX`
*/
struct sensor_byte_data {
struct sensor_data_header header;
struct sensor_byte_sample_data {
uint32_t timestamp_delta;
union {
uint8_t value;
struct {
uint8_t is_near: 1;
uint8_t padding: 7;
};
};
} readings[1];
};
#define PRIsensor_byte_data(field_name_) PRIu64 "ns (" STRINGIFY(field_name_) " = %" PRIu8 ")"
#define PRIsensor_byte_data_arg(data_, readings_offset_, field_name_) \
(data_).header.base_timestamp_ns + (data_).readings[(readings_offset_)].timestamp_delta, \
(data_).readings[(readings_offset_)].field_name_
/**
* Data from a sensor that produces a count like value. This is used by:
* - :c:enum:`SENSOR_CHAN_GAUGE_CYCLE_COUNT`
*/
struct sensor_uint64_data {
struct sensor_data_header header;
struct sensor_uint64_sample_data {
uint32_t timestamp_delta;
uint64_t value;
} readings[1];
};
#define PRIsensor_uint64_data PRIu64 "ns (%" PRIu64 ")"
#define PRIsensor_uint64_data_arg(data_, readings_offset_) \
(data_).header.base_timestamp_ns + (data_).readings[(readings_offset_)].timestamp_delta, \
(data_).readings[(readings_offset_)].value
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_SENSOR_DATA_TYPES_H */
``` | /content/code_sandbox/include/zephyr/drivers/sensor_data_types.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,426 |
```objective-c
/*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_SENSOR_ATTRIBUTE_TYPES_H
#define ZEPHYR_INCLUDE_DRIVERS_SENSOR_ATTRIBUTE_TYPES_H
#include <zephyr/dsp/types.h>
#include <zephyr/dsp/print_format.h>
#include <inttypes.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Used by the following channel/attribute pairs:
* - SENSOR_CHAN_ACCEL_XYZ
* - SENSOR_ATTR_OFFSET
* - SENSOR_CHAN_GYRO_XYZ
* - SENSOR_ATTR_OFFSET
* - SENSOR_CHAN_MAGN_XYZ
* - SENSOR_ATTR_OFFSET
*/
struct sensor_three_axis_attribute {
int8_t shift;
union {
struct {
q31_t x;
q31_t y;
q31_t z;
};
q31_t values[3];
};
};
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_SENSOR_ATTRIBUTE_TYPES_H */
``` | /content/code_sandbox/include/zephyr/drivers/sensor_attribute_types.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 196 |
```objective-c
/*
*
*/
/**
* @file
* @brief Serial Wire Debug Port interface driver API
*/
#ifndef ZEPHYR_INCLUDE_SWDP_H_
#define ZEPHYR_INCLUDE_SWDP_H_
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/* SWDP packet request bits */
#define SWDP_REQUEST_APnDP BIT(0)
#define SWDP_REQUEST_RnW BIT(1)
#define SWDP_REQUEST_A2 BIT(2)
#define SWDP_REQUEST_A3 BIT(3)
/* SWDP acknowledge response bits */
#define SWDP_ACK_OK BIT(0)
#define SWDP_ACK_WAIT BIT(1)
#define SWDP_ACK_FAULT BIT(2)
/* SWDP transfer or parity error */
#define SWDP_TRANSFER_ERROR BIT(3)
/* SWDP Interface pins */
#define SWDP_SWCLK_PIN 0U
#define SWDP_SWDIO_PIN 1U
#define SWDP_nRESET_PIN 7U
/*
* Serial Wire Interface (SWDP) driver API.
* This is the mandatory API any Serial Wire driver needs to expose.
*/
struct swdp_api {
/**
* @brief Write count bits to SWDIO from data LSB first
*
* @param dev SWDP device
* @param count Number of bits to write
* @param data Bits to write
* @return 0 on success, or error code
*/
int (*swdp_output_sequence)(const struct device *dev,
uint32_t count,
const uint8_t *data);
/**
* @brief Read count bits from SWDIO into data LSB first
*
* @param dev SWDP device
* @param count Number of bits to read
* @param data Buffer to store bits read
* @return 0 on success, or error code
*/
int (*swdp_input_sequence)(const struct device *dev,
uint32_t count,
uint8_t *data);
/**
* @brief Perform SWDP transfer and store response
*
* @param dev SWDP device
* @param request SWDP request bits
* @param data Data to be transferred with request
* @param idle_cycles Idle cycles between request and response
* @param response Buffer to store response (ACK/WAIT/FAULT)
* @return 0 on success, or error code
*/
int (*swdp_transfer)(const struct device *dev,
uint8_t request,
uint32_t *data,
uint8_t idle_cycles,
uint8_t *response);
/**
* @brief Set SWCLK, SWDPIO, and nRESET pins state
* @note The bit positions are defined by the SWDP_*_PIN macros.
*
* @param dev SWDP device
* @param pins Bitmask of pins to set
* @param value Value to set pins to
* @return 0 on success, or error code
*/
int (*swdp_set_pins)(const struct device *dev,
uint8_t pins, uint8_t value);
/**
* @brief Get SWCLK, SWDPIO, and nRESET pins state
* @note The bit positions are defined by the SWDP_*_PIN macros.
*
* @param dev SWDP device
* @param state Place to store pins state
* @return 0 on success, or error code
*/
int (*swdp_get_pins)(const struct device *dev, uint8_t *state);
/**
* @brief Set SWDP clock frequency
*
* @param dev SWDP device
* @param clock Clock frequency in Hz
* @return 0 on success, or error code
*/
int (*swdp_set_clock)(const struct device *dev, uint32_t clock);
/**
* @brief Configure SWDP interface
*
* @param dev SWDP device
* @param turnaround Line turnaround cycles
* @param data_phase Always generate Data Phase (also on WAIT/FAULT)
* @return 0 on success, or error code
*/
int (*swdp_configure)(const struct device *dev,
uint8_t turnaround,
bool data_phase);
/**
* @brief Enable interface, set pins to default state
*
* @note SWDPIO is set to output mode, SWCLK and nRESET are set to high level.
*
* @param dev SWDP device
* @return 0 on success, or error code
*/
int (*swdp_port_on)(const struct device *dev);
/**
* @brief Disable interface, set pins to High-Z mode
*
* @param dev SWDP device
* @return 0 on success, or error code
*/
int (*swdp_port_off)(const struct device *dev);
};
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_SWDP_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/swdp.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,065 |
```objective-c
/** @file
* @brief Pipe UART driver header file.
*
* A pipe UART driver that allows applications to handle all aspects of
* received protocol data.
*/
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_UART_PIPE_H_
#define ZEPHYR_INCLUDE_DRIVERS_UART_PIPE_H_
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @brief Received data callback.
*
* This function is called when new data is received on UART. The off parameter
* can be used to alter offset at which received data is stored. Typically,
* when the complete data is received and a new buffer is provided off should
* be set to 0.
*
* @param buf Buffer with received data.
* @param off Data offset on next received and accumulated data length.
*
* @return Buffer to be used on next receive.
*/
typedef uint8_t *(*uart_pipe_recv_cb)(uint8_t *buf, size_t *off);
/** @brief Register UART application.
*
* This function is used to register new UART application.
*
* @param buf Initial buffer for received data.
* @param len Size of buffer.
* @param cb Callback to be called on data reception.
*/
void uart_pipe_register(uint8_t *buf, size_t len, uart_pipe_recv_cb cb);
/** @brief Send data over UART.
*
* This function is used to send data over UART.
*
* @param data Buffer with data to be send.
* @param len Size of data.
*
* @return 0 on success or negative error
*/
int uart_pipe_send(const uint8_t *data, int len);
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_UART_PIPE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/uart_pipe.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 377 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_EMUL_H_
#define ZEPHYR_INCLUDE_DRIVERS_EMUL_H_
/**
* @brief Emulators used to test drivers and higher-level code that uses them
* @defgroup io_emulators Emulator interface
* @ingroup testing
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
struct emul;
/* #includes required after forward-declaration of struct emul later defined in this header. */
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/espi_emul.h>
#include <zephyr/drivers/i2c_emul.h>
#include <zephyr/drivers/spi_emul.h>
#include <zephyr/drivers/mspi_emul.h>
#include <zephyr/drivers/uart_emul.h>
#include <zephyr/sys/iterable_sections.h>
/**
* The types of supported buses.
*/
enum emul_bus_type {
EMUL_BUS_TYPE_I2C,
EMUL_BUS_TYPE_ESPI,
EMUL_BUS_TYPE_SPI,
EMUL_BUS_TYPE_MSPI,
EMUL_BUS_TYPE_UART,
EMUL_BUS_TYPE_NONE,
};
/**
* Structure uniquely identifying a device to be emulated
*/
struct emul_link_for_bus {
const struct device *dev;
};
/** List of emulators attached to a bus */
struct emul_list_for_bus {
/** Identifiers for children of the node */
const struct emul_link_for_bus *children;
/** Number of children of the node */
unsigned int num_children;
};
/**
* Standard callback for emulator initialisation providing the initialiser
* record and the device that calls the emulator functions.
*
* @param emul Emulator to init
* @param parent Parent device that is using the emulator
*/
typedef int (*emul_init_t)(const struct emul *emul, const struct device *parent);
/**
* Emulator API stub when an emulator is not actually placed on a bus.
*/
struct no_bus_emul {
void *api;
uint16_t addr;
};
/** An emulator instance - represents the *target* emulated device/peripheral that is
* interacted with through an emulated bus. Instances of emulated bus nodes (e.g. i2c_emul)
* and emulators (i.e. struct emul) are exactly 1..1
*/
struct emul {
/** function used to initialise the emulator state */
emul_init_t init;
/** handle to the device for which this provides low-level emulation */
const struct device *dev;
/** Emulator-specific configuration data */
const void *cfg;
/** Emulator-specific data */
void *data;
/** The bus type that the emulator is attached to */
enum emul_bus_type bus_type;
/** Pointer to the emulated bus node */
union bus {
struct i2c_emul *i2c;
struct espi_emul *espi;
struct spi_emul *spi;
struct mspi_emul *mspi;
struct uart_emul *uart;
struct no_bus_emul *none;
} bus;
/** Address of the API structure exposed by the emulator instance */
const void *backend_api;
};
/**
* @brief Use the devicetree node identifier as a unique name.
*
* @param node_id A devicetree node identifier
*/
#define EMUL_DT_NAME_GET(node_id) _CONCAT(__emulreg_, node_id)
/* Get a unique identifier based on the given _dev_node_id's reg property and
* the bus its on. Intended for use in other internal macros when declaring {bus}_emul
* structs in peripheral emulators.
*/
#define Z_EMUL_REG_BUS_IDENTIFIER(_dev_node_id) (_CONCAT(_CONCAT(__emulreg_, _dev_node_id), _bus))
/* Conditionally places text based on what bus _dev_node_id is on. */
#define Z_EMUL_BUS(_dev_node_id, _i2c, _espi, _spi, _mspi, _uart, _none) \
COND_CODE_1(DT_ON_BUS(_dev_node_id, i2c), (_i2c), \
(COND_CODE_1(DT_ON_BUS(_dev_node_id, espi), (_espi), \
(COND_CODE_1(DT_ON_BUS(_dev_node_id, spi), (_spi), \
(COND_CODE_1(DT_ON_BUS(_dev_node_id, mspi), (_mspi), \
(COND_CODE_1(DT_ON_BUS(_dev_node_id, uart), (_uart), \
(_none))))))))))
/**
* @brief Define a new emulator
*
* This adds a new struct emul to the linker list of emulations. This is
* typically used in your emulator's DT_INST_FOREACH_STATUS_OKAY() clause.
*
* @param node_id Node ID of the driver to emulate (e.g. DT_DRV_INST(n)); the node_id *MUST* have a
* corresponding DEVICE_DT_DEFINE().
* @param init_fn function to call to initialise the emulator (see emul_init typedef)
* @param data_ptr emulator-specific data
* @param cfg_ptr emulator-specific configuration data
* @param bus_api emulator-specific bus api
* @param _backend_api emulator-specific backend api
*/
#define EMUL_DT_DEFINE(node_id, init_fn, data_ptr, cfg_ptr, bus_api, _backend_api) \
static struct Z_EMUL_BUS(node_id, i2c_emul, espi_emul, spi_emul, mspi_emul, uart_emul, \
no_bus_emul) Z_EMUL_REG_BUS_IDENTIFIER(node_id) = { \
.api = bus_api, \
IF_ENABLED(DT_NODE_HAS_PROP(node_id, reg), \
(.Z_EMUL_BUS(node_id, addr, chipsel, chipsel, dev_idx, dummy, addr) = \
DT_REG_ADDR(node_id),))}; \
const STRUCT_SECTION_ITERABLE(emul, EMUL_DT_NAME_GET(node_id)) __used = { \
.init = (init_fn), \
.dev = DEVICE_DT_GET(node_id), \
.cfg = (cfg_ptr), \
.data = (data_ptr), \
.bus_type = Z_EMUL_BUS(node_id, EMUL_BUS_TYPE_I2C, EMUL_BUS_TYPE_ESPI, \
EMUL_BUS_TYPE_SPI, EMUL_BUS_TYPE_MSPI, EMUL_BUS_TYPE_UART, \
EMUL_BUS_TYPE_NONE), \
.bus = {.Z_EMUL_BUS(node_id, i2c, espi, spi, mspi, uart, none) = \
&(Z_EMUL_REG_BUS_IDENTIFIER(node_id))}, \
.backend_api = (_backend_api), \
};
/**
* @brief Like EMUL_DT_DEFINE(), but uses an instance of a DT_DRV_COMPAT compatible instead of a
* node identifier.
*
* @param inst instance number. The @p node_id argument to EMUL_DT_DEFINE is set to
* <tt>DT_DRV_INST(inst)</tt>.
* @param ... other parameters as expected by EMUL_DT_DEFINE.
*/
#define EMUL_DT_INST_DEFINE(inst, ...) EMUL_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
/**
* @brief Get a <tt>const struct emul*</tt> from a devicetree node identifier
*
* @details Returns a pointer to an emulator object created from a devicetree
* node, if any device was allocated by an emulator implementation.
*
* If no such device was allocated, this will fail at linker time. If you get an
* error that looks like <tt>undefined reference to __device_dts_ord_<N></tt>,
* that is what happened. Check to make sure your emulator implementation is
* being compiled, usually by enabling the Kconfig options it requires.
*
* @param node_id A devicetree node identifier
* @return A pointer to the emul object created for that node
*/
#define EMUL_DT_GET(node_id) (&EMUL_DT_NAME_GET(node_id))
/**
* @brief Utility macro to obtain an optional reference to an emulator
*
* If the node identifier refers to a node with status `okay`, this returns `EMUL_DT_GET(node_id)`.
* Otherwise, it returns `NULL`.
*
* @param node_id A devicetree node identifier
* @return a @ref emul reference for the node identifier, which may be `NULL`.
*/
#define EMUL_DT_GET_OR_NULL(node_id) \
COND_CODE_1(DT_NODE_HAS_STATUS(node_id, okay), (EMUL_DT_GET(node_id)), (NULL))
/**
* @brief Set up a list of emulators
*
* @param dev Device the emulators are attached to (e.g. an I2C controller)
* @return 0 if OK
* @return negative value on error
*/
int emul_init_for_bus(const struct device *dev);
/**
* @brief Retrieve the emul structure for an emulator by name
*
* @details Emulator objects are created via the EMUL_DT_DEFINE() macro and placed in memory by the
* linker. If the emulator structure is needed for custom API calls, it can be retrieved by the name
* that the emulator exposes to the system (this is the devicetree node's label by default).
*
* @param name Emulator name to search for. A null pointer, or a pointer to an
* empty string, will cause NULL to be returned.
*
* @return pointer to emulator structure; NULL if not found or cannot be used.
*/
const struct emul *emul_get_binding(const char *name);
/**
* @}
*/
#define Z_MAYBE_EMUL_DECLARE_INTERNAL(node_id) extern const struct emul EMUL_DT_NAME_GET(node_id);
DT_FOREACH_STATUS_OKAY_NODE(Z_MAYBE_EMUL_DECLARE_INTERNAL);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* ZEPHYR_INCLUDE_DRIVERS_EMUL_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/emul.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,134 |
```objective-c
/*
*
*/
/**
* @file
* @brief Disk Driver Interface
*
* This file contains interface for disk access. Apart from disks, various
* other storage media like Flash and RAM disks may implement this interface to
* be used by various higher layers(consumers) like USB Mass storage
* and Filesystems.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_DISK_H_
#define ZEPHYR_INCLUDE_DRIVERS_DISK_H_
/**
* @brief Disk Driver Interface
* @defgroup disk_driver_interface Disk Driver Interface
* @since 1.6
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <zephyr/kernel.h>
#include <zephyr/types.h>
#include <zephyr/sys/dlist.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Possible Cmd Codes for disk_ioctl()
*/
/** Get the number of sectors in the disk */
#define DISK_IOCTL_GET_SECTOR_COUNT 1
/** Get the size of a disk SECTOR in bytes */
#define DISK_IOCTL_GET_SECTOR_SIZE 2
/** reserved. It used to be DISK_IOCTL_GET_DISK_SIZE */
#define DISK_IOCTL_RESERVED 3
/** How many sectors constitute a FLASH Erase block */
#define DISK_IOCTL_GET_ERASE_BLOCK_SZ 4
/** Commit any cached read/writes to disk */
#define DISK_IOCTL_CTRL_SYNC 5
/** Initialize the disk. This IOCTL must be issued before the disk can be
* used for I/O. It is reference counted, so only the first successful
* invocation of this macro on an uninitialized disk will initialize the IO
* device
*/
#define DISK_IOCTL_CTRL_INIT 6
/** Deinitialize the disk. This IOCTL can be used to de-initialize the disk,
* enabling it to be removed from the system if the disk is hot-pluggable.
* Disk usage is reference counted, so for a given disk the
* `DISK_IOCTL_CTRL_DEINIT` IOCTL must be issued as many times as the
* `DISK_IOCTL_CTRL_INIT` IOCTL was issued in order to de-initialize it.
*
* This macro optionally accepts a pointer to a boolean as the `buf` parameter,
* which if true indicates the disk should be forcibly stopped, ignoring all
* reference counts. The disk driver must report success if a forced stop is
* requested, but this operation is inherently unsafe.
*/
#define DISK_IOCTL_CTRL_DEINIT 7
/**
* @brief Possible return bitmasks for disk_status()
*/
/** Disk status okay */
#define DISK_STATUS_OK 0x00
/** Disk status uninitialized */
#define DISK_STATUS_UNINIT 0x01
/** Disk status no media */
#define DISK_STATUS_NOMEDIA 0x02
/** Disk status write protected */
#define DISK_STATUS_WR_PROTECT 0x04
struct disk_operations;
/**
* @brief Disk info
*/
struct disk_info {
/** Internally used list node */
sys_dnode_t node;
/** Disk name */
const char *name;
/** Disk operations */
const struct disk_operations *ops;
/** Device associated to this disk */
const struct device *dev;
/** Internally used disk reference count */
uint16_t refcnt;
};
/**
* @brief Disk operations
*/
struct disk_operations {
int (*init)(struct disk_info *disk);
int (*status)(struct disk_info *disk);
int (*read)(struct disk_info *disk, uint8_t *data_buf,
uint32_t start_sector, uint32_t num_sector);
int (*write)(struct disk_info *disk, const uint8_t *data_buf,
uint32_t start_sector, uint32_t num_sector);
int (*ioctl)(struct disk_info *disk, uint8_t cmd, void *buff);
};
/**
* @brief Register disk
*
* @param[in] disk Pointer to the disk info structure
*
* @return 0 on success, negative errno code on fail
*/
int disk_access_register(struct disk_info *disk);
/**
* @brief Unregister disk
*
* @param[in] disk Pointer to the disk info structure
*
* @return 0 on success, negative errno code on fail
*/
int disk_access_unregister(struct disk_info *disk);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_DISK_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/disk.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 920 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public PWM Driver APIs
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_PWM_H_
#define ZEPHYR_INCLUDE_DRIVERS_PWM_H_
/**
* @brief PWM Interface
* @defgroup pwm_interface PWM Interface
* @since 1.0
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <stdint.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/sys_clock.h>
#include <zephyr/sys/math_extras.h>
#include <zephyr/toolchain.h>
#include <zephyr/dt-bindings/pwm/pwm.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name PWM capture configuration flags
* @anchor PWM_CAPTURE_FLAGS
* @{
*/
/** @cond INTERNAL_HIDDEN */
/* Bit 0 is used for PWM_POLARITY_NORMAL/PWM_POLARITY_INVERTED */
#define PWM_CAPTURE_TYPE_SHIFT 1U
#define PWM_CAPTURE_TYPE_MASK (3U << PWM_CAPTURE_TYPE_SHIFT)
#define PWM_CAPTURE_MODE_SHIFT 3U
#define PWM_CAPTURE_MODE_MASK (1U << PWM_CAPTURE_MODE_SHIFT)
/** @endcond */
/** PWM pin capture captures period. */
#define PWM_CAPTURE_TYPE_PERIOD (1U << PWM_CAPTURE_TYPE_SHIFT)
/** PWM pin capture captures pulse width. */
#define PWM_CAPTURE_TYPE_PULSE (2U << PWM_CAPTURE_TYPE_SHIFT)
/** PWM pin capture captures both period and pulse width. */
#define PWM_CAPTURE_TYPE_BOTH (PWM_CAPTURE_TYPE_PERIOD | \
PWM_CAPTURE_TYPE_PULSE)
/** PWM pin capture captures a single period/pulse width. */
#define PWM_CAPTURE_MODE_SINGLE (0U << PWM_CAPTURE_MODE_SHIFT)
/** PWM pin capture captures period/pulse width continuously. */
#define PWM_CAPTURE_MODE_CONTINUOUS (1U << PWM_CAPTURE_MODE_SHIFT)
/** @} */
/**
* @brief Provides a type to hold PWM configuration flags.
*
* The lower 8 bits are used for standard flags.
* The upper 8 bits are reserved for SoC specific flags.
*
* @see @ref PWM_CAPTURE_FLAGS.
*/
typedef uint16_t pwm_flags_t;
/**
* @brief Container for PWM information specified in devicetree.
*
* This type contains a pointer to a PWM device, channel number (controlled by
* the PWM device), the PWM signal period in nanoseconds and the flags
* applicable to the channel. Note that not all PWM drivers support flags. In
* such case, flags will be set to 0.
*
* @see PWM_DT_SPEC_GET_BY_NAME
* @see PWM_DT_SPEC_GET_BY_NAME_OR
* @see PWM_DT_SPEC_GET_BY_IDX
* @see PWM_DT_SPEC_GET_BY_IDX_OR
* @see PWM_DT_SPEC_GET
* @see PWM_DT_SPEC_GET_OR
*/
struct pwm_dt_spec {
/** PWM device instance. */
const struct device *dev;
/** Channel number. */
uint32_t channel;
/** Period in nanoseconds. */
uint32_t period;
/** Flags. */
pwm_flags_t flags;
};
/**
* @brief Static initializer for a struct pwm_dt_spec
*
* This returns a static initializer for a struct pwm_dt_spec given a devicetree
* node identifier and an index.
*
* Example devicetree fragment:
*
* @code{.dts}
* n: node {
* pwms = <&pwm1 1 1000 PWM_POLARITY_NORMAL>,
* <&pwm2 3 2000 PWM_POLARITY_INVERTED>;
* pwm-names = "alpha", "beta";
* };
* @endcode
*
* Example usage:
*
* @code{.c}
* const struct pwm_dt_spec spec =
* PWM_DT_SPEC_GET_BY_NAME(DT_NODELABEL(n), alpha);
*
* // Initializes 'spec' to:
* // {
* // .dev = DEVICE_DT_GET(DT_NODELABEL(pwm1)),
* // .channel = 1,
* // .period = 1000,
* // .flags = PWM_POLARITY_NORMAL,
* // }
* @endcode
*
* The device (dev) must still be checked for readiness, e.g. using
* device_is_ready(). It is an error to use this macro unless the node exists,
* has the 'pwms' property, and that 'pwms' property specifies a PWM controller,
* a channel, a period in nanoseconds and optionally flags.
*
* @param node_id Devicetree node identifier.
* @param name Lowercase-and-underscores name of a pwms element as defined by
* the node's pwm-names property.
*
* @return Static initializer for a struct pwm_dt_spec for the property.
*
* @see PWM_DT_SPEC_INST_GET_BY_NAME
*/
#define PWM_DT_SPEC_GET_BY_NAME(node_id, name) \
{ \
.dev = DEVICE_DT_GET(DT_PWMS_CTLR_BY_NAME(node_id, name)), \
.channel = DT_PWMS_CHANNEL_BY_NAME(node_id, name), \
.period = DT_PWMS_PERIOD_BY_NAME(node_id, name), \
.flags = DT_PWMS_FLAGS_BY_NAME(node_id, name), \
}
/**
* @brief Static initializer for a struct pwm_dt_spec from a DT_DRV_COMPAT
* instance.
*
* @param inst DT_DRV_COMPAT instance number
* @param name Lowercase-and-underscores name of a pwms element as defined by
* the node's pwm-names property.
*
* @return Static initializer for a struct pwm_dt_spec for the property.
*
* @see PWM_DT_SPEC_GET_BY_NAME
*/
#define PWM_DT_SPEC_INST_GET_BY_NAME(inst, name) \
PWM_DT_SPEC_GET_BY_NAME(DT_DRV_INST(inst), name)
/**
* @brief Like PWM_DT_SPEC_GET_BY_NAME(), with a fallback to a default value.
*
* If the devicetree node identifier 'node_id' refers to a node with a property
* 'pwms', this expands to <tt>PWM_DT_SPEC_GET_BY_NAME(node_id, name)</tt>. The
* @p default_value parameter is not expanded in this case. Otherwise, this
* expands to @p default_value.
*
* @param node_id Devicetree node identifier.
* @param name Lowercase-and-underscores name of a pwms element as defined by
* the node's pwm-names property
* @param default_value Fallback value to expand to.
*
* @return Static initializer for a struct pwm_dt_spec for the property,
* or @p default_value if the node or property do not exist.
*
* @see PWM_DT_SPEC_INST_GET_BY_NAME_OR
*/
#define PWM_DT_SPEC_GET_BY_NAME_OR(node_id, name, default_value) \
COND_CODE_1(DT_NODE_HAS_PROP(node_id, pwms), \
(PWM_DT_SPEC_GET_BY_NAME(node_id, name)), \
(default_value))
/**
* @brief Like PWM_DT_SPEC_INST_GET_BY_NAME(), with a fallback to a default
* value.
*
* @param inst DT_DRV_COMPAT instance number
* @param name Lowercase-and-underscores name of a pwms element as defined by
* the node's pwm-names property.
* @param default_value Fallback value to expand to.
*
* @return Static initializer for a struct pwm_dt_spec for the property,
* or @p default_value if the node or property do not exist.
*
* @see PWM_DT_SPEC_GET_BY_NAME_OR
*/
#define PWM_DT_SPEC_INST_GET_BY_NAME_OR(inst, name, default_value) \
PWM_DT_SPEC_GET_BY_NAME_OR(DT_DRV_INST(inst), name, default_value)
/**
* @brief Static initializer for a struct pwm_dt_spec
*
* This returns a static initializer for a struct pwm_dt_spec given a devicetree
* node identifier and an index.
*
* Example devicetree fragment:
*
* @code{.dts}
* n: node {
* pwms = <&pwm1 1 1000 PWM_POLARITY_NORMAL>,
* <&pwm2 3 2000 PWM_POLARITY_INVERTED>;
* };
* @endcode
*
* Example usage:
*
* @code{.c}
* const struct pwm_dt_spec spec =
* PWM_DT_SPEC_GET_BY_IDX(DT_NODELABEL(n), 1);
*
* // Initializes 'spec' to:
* // {
* // .dev = DEVICE_DT_GET(DT_NODELABEL(pwm2)),
* // .channel = 3,
* // .period = 2000,
* // .flags = PWM_POLARITY_INVERTED,
* // }
* @endcode
*
* The device (dev) must still be checked for readiness, e.g. using
* device_is_ready(). It is an error to use this macro unless the node exists,
* has the 'pwms' property, and that 'pwms' property specifies a PWM controller,
* a channel, a period in nanoseconds and optionally flags.
*
* @param node_id Devicetree node identifier.
* @param idx Logical index into 'pwms' property.
*
* @return Static initializer for a struct pwm_dt_spec for the property.
*
* @see PWM_DT_SPEC_INST_GET_BY_IDX
*/
#define PWM_DT_SPEC_GET_BY_IDX(node_id, idx) \
{ \
.dev = DEVICE_DT_GET(DT_PWMS_CTLR_BY_IDX(node_id, idx)), \
.channel = DT_PWMS_CHANNEL_BY_IDX(node_id, idx), \
.period = DT_PWMS_PERIOD_BY_IDX(node_id, idx), \
.flags = DT_PWMS_FLAGS_BY_IDX(node_id, idx), \
}
/**
* @brief Static initializer for a struct pwm_dt_spec from a DT_DRV_COMPAT
* instance.
*
* @param inst DT_DRV_COMPAT instance number
* @param idx Logical index into 'pwms' property.
*
* @return Static initializer for a struct pwm_dt_spec for the property.
*
* @see PWM_DT_SPEC_GET_BY_IDX
*/
#define PWM_DT_SPEC_INST_GET_BY_IDX(inst, idx) \
PWM_DT_SPEC_GET_BY_IDX(DT_DRV_INST(inst), idx)
/**
* @brief Like PWM_DT_SPEC_GET_BY_IDX(), with a fallback to a default value.
*
* If the devicetree node identifier 'node_id' refers to a node with a property
* 'pwms', this expands to <tt>PWM_DT_SPEC_GET_BY_IDX(node_id, idx)</tt>. The
* @p default_value parameter is not expanded in this case. Otherwise, this
* expands to @p default_value.
*
* @param node_id Devicetree node identifier.
* @param idx Logical index into 'pwms' property.
* @param default_value Fallback value to expand to.
*
* @return Static initializer for a struct pwm_dt_spec for the property,
* or @p default_value if the node or property do not exist.
*
* @see PWM_DT_SPEC_INST_GET_BY_IDX_OR
*/
#define PWM_DT_SPEC_GET_BY_IDX_OR(node_id, idx, default_value) \
COND_CODE_1(DT_NODE_HAS_PROP(node_id, pwms), \
(PWM_DT_SPEC_GET_BY_IDX(node_id, idx)), \
(default_value))
/**
* @brief Like PWM_DT_SPEC_INST_GET_BY_IDX(), with a fallback to a default
* value.
*
* @param inst DT_DRV_COMPAT instance number
* @param idx Logical index into 'pwms' property.
* @param default_value Fallback value to expand to.
*
* @return Static initializer for a struct pwm_dt_spec for the property,
* or @p default_value if the node or property do not exist.
*
* @see PWM_DT_SPEC_GET_BY_IDX_OR
*/
#define PWM_DT_SPEC_INST_GET_BY_IDX_OR(inst, idx, default_value) \
PWM_DT_SPEC_GET_BY_IDX_OR(DT_DRV_INST(inst), idx, default_value)
/**
* @brief Equivalent to <tt>PWM_DT_SPEC_GET_BY_IDX(node_id, 0)</tt>.
*
* @param node_id Devicetree node identifier.
*
* @return Static initializer for a struct pwm_dt_spec for the property.
*
* @see PWM_DT_SPEC_GET_BY_IDX
* @see PWM_DT_SPEC_INST_GET
*/
#define PWM_DT_SPEC_GET(node_id) PWM_DT_SPEC_GET_BY_IDX(node_id, 0)
/**
* @brief Equivalent to <tt>PWM_DT_SPEC_INST_GET_BY_IDX(inst, 0)</tt>.
*
* @param inst DT_DRV_COMPAT instance number
*
* @return Static initializer for a struct pwm_dt_spec for the property.
*
* @see PWM_DT_SPEC_INST_GET_BY_IDX
* @see PWM_DT_SPEC_GET
*/
#define PWM_DT_SPEC_INST_GET(inst) PWM_DT_SPEC_GET(DT_DRV_INST(inst))
/**
* @brief Equivalent to
* <tt>PWM_DT_SPEC_GET_BY_IDX_OR(node_id, 0, default_value)</tt>.
*
* @param node_id Devicetree node identifier.
* @param default_value Fallback value to expand to.
*
* @return Static initializer for a struct pwm_dt_spec for the property.
*
* @see PWM_DT_SPEC_GET_BY_IDX_OR
* @see PWM_DT_SPEC_INST_GET_OR
*/
#define PWM_DT_SPEC_GET_OR(node_id, default_value) \
PWM_DT_SPEC_GET_BY_IDX_OR(node_id, 0, default_value)
/**
* @brief Equivalent to
* <tt>PWM_DT_SPEC_INST_GET_BY_IDX_OR(inst, 0, default_value)</tt>.
*
* @param inst DT_DRV_COMPAT instance number
* @param default_value Fallback value to expand to.
*
* @return Static initializer for a struct pwm_dt_spec for the property.
*
* @see PWM_DT_SPEC_INST_GET_BY_IDX_OR
* @see PWM_DT_SPEC_GET_OR
*/
#define PWM_DT_SPEC_INST_GET_OR(inst, default_value) \
PWM_DT_SPEC_GET_OR(DT_DRV_INST(inst), default_value)
/**
* @brief PWM capture callback handler function signature
*
* @note The callback handler will be called in interrupt context.
*
* @note @kconfig{CONFIG_PWM_CAPTURE} must be selected to enable PWM capture
* support.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
* @param period_cycles Captured PWM period width (in clock cycles). HW
* specific.
* @param pulse_cycles Captured PWM pulse width (in clock cycles). HW specific.
* @param status Status for the PWM capture (0 if no error, negative errno
* otherwise. See pwm_capture_cycles() return value
* descriptions for details).
* @param user_data User data passed to pwm_configure_capture()
*/
typedef void (*pwm_capture_callback_handler_t)(const struct device *dev,
uint32_t channel,
uint32_t period_cycles,
uint32_t pulse_cycles,
int status, void *user_data);
/** @cond INTERNAL_HIDDEN */
/**
* @brief PWM driver API call to configure PWM pin period and pulse width.
* @see pwm_set_cycles() for argument description.
*/
typedef int (*pwm_set_cycles_t)(const struct device *dev, uint32_t channel,
uint32_t period_cycles, uint32_t pulse_cycles,
pwm_flags_t flags);
/**
* @brief PWM driver API call to obtain the PWM cycles per second (frequency).
* @see pwm_get_cycles_per_sec() for argument description
*/
typedef int (*pwm_get_cycles_per_sec_t)(const struct device *dev,
uint32_t channel, uint64_t *cycles);
#ifdef CONFIG_PWM_CAPTURE
/**
* @brief PWM driver API call to configure PWM capture.
* @see pwm_configure_capture() for argument description.
*/
typedef int (*pwm_configure_capture_t)(const struct device *dev,
uint32_t channel, pwm_flags_t flags,
pwm_capture_callback_handler_t cb,
void *user_data);
/**
* @brief PWM driver API call to enable PWM capture.
* @see pwm_enable_capture() for argument description.
*/
typedef int (*pwm_enable_capture_t)(const struct device *dev, uint32_t channel);
/**
* @brief PWM driver API call to disable PWM capture.
* @see pwm_disable_capture() for argument description
*/
typedef int (*pwm_disable_capture_t)(const struct device *dev,
uint32_t channel);
#endif /* CONFIG_PWM_CAPTURE */
/** @brief PWM driver API definition. */
__subsystem struct pwm_driver_api {
pwm_set_cycles_t set_cycles;
pwm_get_cycles_per_sec_t get_cycles_per_sec;
#ifdef CONFIG_PWM_CAPTURE
pwm_configure_capture_t configure_capture;
pwm_enable_capture_t enable_capture;
pwm_disable_capture_t disable_capture;
#endif /* CONFIG_PWM_CAPTURE */
};
/** @endcond */
/**
* @brief Set the period and pulse width for a single PWM output.
*
* The PWM period and pulse width will synchronously be set to the new values
* without glitches in the PWM signal, but the call will not block for the
* change to take effect.
*
* @note Not all PWM controllers support synchronous, glitch-free updates of the
* PWM period and pulse width. Depending on the hardware, changing the PWM
* period and/or pulse width may cause a glitch in the generated PWM signal.
*
* @note Some multi-channel PWM controllers share the PWM period across all
* channels. Depending on the hardware, changing the PWM period for one channel
* may affect the PWM period for the other channels of the same PWM controller.
*
* Passing 0 as @p pulse will cause the pin to be driven to a constant
* inactive level.
* Passing a non-zero @p pulse equal to @p period will cause the pin
* to be driven to a constant active level.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
* @param period Period (in clock cycles) set to the PWM. HW specific.
* @param pulse Pulse width (in clock cycles) set to the PWM. HW specific.
* @param flags Flags for pin configuration.
*
* @retval 0 If successful.
* @retval -EINVAL If pulse > period.
* @retval -errno Negative errno code on failure.
*/
__syscall int pwm_set_cycles(const struct device *dev, uint32_t channel,
uint32_t period, uint32_t pulse,
pwm_flags_t flags);
static inline int z_impl_pwm_set_cycles(const struct device *dev,
uint32_t channel, uint32_t period,
uint32_t pulse, pwm_flags_t flags)
{
const struct pwm_driver_api *api =
(const struct pwm_driver_api *)dev->api;
if (pulse > period) {
return -EINVAL;
}
return api->set_cycles(dev, channel, period, pulse, flags);
}
/**
* @brief Get the clock rate (cycles per second) for a single PWM output.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
* @param[out] cycles Pointer to the memory to store clock rate (cycles per
* sec). HW specific.
*
* @retval 0 If successful.
* @retval -errno Negative errno code on failure.
*/
__syscall int pwm_get_cycles_per_sec(const struct device *dev, uint32_t channel,
uint64_t *cycles);
static inline int z_impl_pwm_get_cycles_per_sec(const struct device *dev,
uint32_t channel,
uint64_t *cycles)
{
const struct pwm_driver_api *api =
(const struct pwm_driver_api *)dev->api;
return api->get_cycles_per_sec(dev, channel, cycles);
}
/**
* @brief Set the period and pulse width in nanoseconds for a single PWM output.
*
* @note Utility macros such as PWM_MSEC() can be used to convert from other
* scales or units to nanoseconds, the units used by this function.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
* @param period Period (in nanoseconds) set to the PWM.
* @param pulse Pulse width (in nanoseconds) set to the PWM.
* @param flags Flags for pin configuration (polarity).
*
* @retval 0 If successful.
* @retval -ENOTSUP If requested period or pulse cycles are not supported.
* @retval -errno Other negative errno code on failure.
*/
static inline int pwm_set(const struct device *dev, uint32_t channel,
uint32_t period, uint32_t pulse, pwm_flags_t flags)
{
int err;
uint64_t pulse_cycles;
uint64_t period_cycles;
uint64_t cycles_per_sec;
err = pwm_get_cycles_per_sec(dev, channel, &cycles_per_sec);
if (err < 0) {
return err;
}
period_cycles = (period * cycles_per_sec) / NSEC_PER_SEC;
if (period_cycles > UINT32_MAX) {
return -ENOTSUP;
}
pulse_cycles = (pulse * cycles_per_sec) / NSEC_PER_SEC;
if (pulse_cycles > UINT32_MAX) {
return -ENOTSUP;
}
return pwm_set_cycles(dev, channel, (uint32_t)period_cycles,
(uint32_t)pulse_cycles, flags);
}
/**
* @brief Set the period and pulse width in nanoseconds from a struct
* pwm_dt_spec (with custom period).
*
* This is equivalent to:
*
* pwm_set(spec->dev, spec->channel, period, pulse, spec->flags)
*
* The period specified in @p spec is ignored. This API call can be used when
* the period specified in Devicetree needs to be changed at runtime.
*
* @param[in] spec PWM specification from devicetree.
* @param period Period (in nanoseconds) set to the PWM.
* @param pulse Pulse width (in nanoseconds) set to the PWM.
*
* @return A value from pwm_set().
*
* @see pwm_set_pulse_dt()
*/
static inline int pwm_set_dt(const struct pwm_dt_spec *spec, uint32_t period,
uint32_t pulse)
{
return pwm_set(spec->dev, spec->channel, period, pulse, spec->flags);
}
/**
* @brief Set the period and pulse width in nanoseconds from a struct
* pwm_dt_spec.
*
* This is equivalent to:
*
* pwm_set(spec->dev, spec->channel, spec->period, pulse, spec->flags)
*
* @param[in] spec PWM specification from devicetree.
* @param pulse Pulse width (in nanoseconds) set to the PWM.
*
* @return A value from pwm_set().
*
* @see pwm_set_pulse_dt()
*/
static inline int pwm_set_pulse_dt(const struct pwm_dt_spec *spec,
uint32_t pulse)
{
return pwm_set(spec->dev, spec->channel, spec->period, pulse,
spec->flags);
}
/**
* @brief Convert from PWM cycles to microseconds.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
* @param cycles Cycles to be converted.
* @param[out] usec Pointer to the memory to store calculated usec.
*
* @retval 0 If successful.
* @retval -ERANGE If result is too large.
* @retval -errno Other negative errno code on failure.
*/
static inline int pwm_cycles_to_usec(const struct device *dev, uint32_t channel,
uint32_t cycles, uint64_t *usec)
{
int err;
uint64_t temp;
uint64_t cycles_per_sec;
err = pwm_get_cycles_per_sec(dev, channel, &cycles_per_sec);
if (err < 0) {
return err;
}
if (u64_mul_overflow(cycles, (uint64_t)USEC_PER_SEC, &temp)) {
return -ERANGE;
}
*usec = temp / cycles_per_sec;
return 0;
}
/**
* @brief Convert from PWM cycles to nanoseconds.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
* @param cycles Cycles to be converted.
* @param[out] nsec Pointer to the memory to store the calculated nsec.
*
* @retval 0 If successful.
* @retval -ERANGE If result is too large.
* @retval -errno Other negative errno code on failure.
*/
static inline int pwm_cycles_to_nsec(const struct device *dev, uint32_t channel,
uint32_t cycles, uint64_t *nsec)
{
int err;
uint64_t temp;
uint64_t cycles_per_sec;
err = pwm_get_cycles_per_sec(dev, channel, &cycles_per_sec);
if (err < 0) {
return err;
}
if (u64_mul_overflow(cycles, (uint64_t)NSEC_PER_SEC, &temp)) {
return -ERANGE;
}
*nsec = temp / cycles_per_sec;
return 0;
}
#if defined(CONFIG_PWM_CAPTURE) || defined(__DOXYGEN__)
/**
* @brief Configure PWM period/pulse width capture for a single PWM input.
*
* After configuring PWM capture using this function, the capture can be
* enabled/disabled using pwm_enable_capture() and
* pwm_disable_capture().
*
* @note This API function cannot be invoked from user space due to the use of a
* function callback. In user space, one of the simpler API functions
* (pwm_capture_cycles(), pwm_capture_usec(), or
* pwm_capture_nsec()) can be used instead.
*
* @note @kconfig{CONFIG_PWM_CAPTURE} must be selected for this function to be
* available.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
* @param flags PWM capture flags
* @param[in] cb Application callback handler function to be called upon capture
* @param[in] user_data User data to pass to the application callback handler
* function
*
* @retval -EINVAL if invalid function parameters were given
* @retval -ENOSYS if PWM capture is not supported or the given flags are not
* supported
* @retval -EIO if IO error occurred while configuring
* @retval -EBUSY if PWM capture is already in progress
*/
static inline int pwm_configure_capture(const struct device *dev,
uint32_t channel, pwm_flags_t flags,
pwm_capture_callback_handler_t cb,
void *user_data)
{
const struct pwm_driver_api *api =
(const struct pwm_driver_api *)dev->api;
if (api->configure_capture == NULL) {
return -ENOSYS;
}
return api->configure_capture(dev, channel, flags, cb,
user_data);
}
#endif /* CONFIG_PWM_CAPTURE */
/**
* @brief Enable PWM period/pulse width capture for a single PWM input.
*
* The PWM pin must be configured using pwm_configure_capture() prior to
* calling this function.
*
* @note @kconfig{CONFIG_PWM_CAPTURE} must be selected for this function to be
* available.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
*
* @retval 0 If successful.
* @retval -EINVAL if invalid function parameters were given
* @retval -ENOSYS if PWM capture is not supported
* @retval -EIO if IO error occurred while enabling PWM capture
* @retval -EBUSY if PWM capture is already in progress
*/
__syscall int pwm_enable_capture(const struct device *dev, uint32_t channel);
#ifdef CONFIG_PWM_CAPTURE
static inline int z_impl_pwm_enable_capture(const struct device *dev,
uint32_t channel)
{
const struct pwm_driver_api *api =
(const struct pwm_driver_api *)dev->api;
if (api->enable_capture == NULL) {
return -ENOSYS;
}
return api->enable_capture(dev, channel);
}
#endif /* CONFIG_PWM_CAPTURE */
/**
* @brief Disable PWM period/pulse width capture for a single PWM input.
*
* @note @kconfig{CONFIG_PWM_CAPTURE} must be selected for this function to be
* available.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
*
* @retval 0 If successful.
* @retval -EINVAL if invalid function parameters were given
* @retval -ENOSYS if PWM capture is not supported
* @retval -EIO if IO error occurred while disabling PWM capture
*/
__syscall int pwm_disable_capture(const struct device *dev, uint32_t channel);
#ifdef CONFIG_PWM_CAPTURE
static inline int z_impl_pwm_disable_capture(const struct device *dev,
uint32_t channel)
{
const struct pwm_driver_api *api =
(const struct pwm_driver_api *)dev->api;
if (api->disable_capture == NULL) {
return -ENOSYS;
}
return api->disable_capture(dev, channel);
}
#endif /* CONFIG_PWM_CAPTURE */
/**
* @brief Capture a single PWM period/pulse width in clock cycles for a single
* PWM input.
*
* This API function wraps calls to pwm_configure_capture(),
* pwm_enable_capture(), and pwm_disable_capture() and passes
* the capture result to the caller. The function is blocking until either the
* PWM capture is completed or a timeout occurs.
*
* @note @kconfig{CONFIG_PWM_CAPTURE} must be selected for this function to be
* available.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
* @param flags PWM capture flags.
* @param[out] period Pointer to the memory to store the captured PWM period
* width (in clock cycles). HW specific.
* @param[out] pulse Pointer to the memory to store the captured PWM pulse width
* (in clock cycles). HW specific.
* @param timeout Waiting period for the capture to complete.
*
* @retval 0 If successful.
* @retval -EBUSY PWM capture already in progress.
* @retval -EAGAIN Waiting period timed out.
* @retval -EIO IO error while capturing.
* @retval -ERANGE If result is too large.
*/
__syscall int pwm_capture_cycles(const struct device *dev, uint32_t channel,
pwm_flags_t flags, uint32_t *period,
uint32_t *pulse, k_timeout_t timeout);
/**
* @brief Capture a single PWM period/pulse width in microseconds for a single
* PWM input.
*
* This API function wraps calls to pwm_capture_cycles() and
* pwm_cycles_to_usec() and passes the capture result to the caller. The
* function is blocking until either the PWM capture is completed or a timeout
* occurs.
*
* @note @kconfig{CONFIG_PWM_CAPTURE} must be selected for this function to be
* available.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
* @param flags PWM capture flags.
* @param[out] period Pointer to the memory to store the captured PWM period
* width (in usec).
* @param[out] pulse Pointer to the memory to store the captured PWM pulse width
* (in usec).
* @param timeout Waiting period for the capture to complete.
*
* @retval 0 If successful.
* @retval -EBUSY PWM capture already in progress.
* @retval -EAGAIN Waiting period timed out.
* @retval -EIO IO error while capturing.
* @retval -ERANGE If result is too large.
* @retval -errno Other negative errno code on failure.
*/
static inline int pwm_capture_usec(const struct device *dev, uint32_t channel,
pwm_flags_t flags, uint64_t *period,
uint64_t *pulse, k_timeout_t timeout)
{
int err;
uint32_t pulse_cycles;
uint32_t period_cycles;
err = pwm_capture_cycles(dev, channel, flags, &period_cycles,
&pulse_cycles, timeout);
if (err < 0) {
return err;
}
err = pwm_cycles_to_usec(dev, channel, period_cycles, period);
if (err < 0) {
return err;
}
err = pwm_cycles_to_usec(dev, channel, pulse_cycles, pulse);
if (err < 0) {
return err;
}
return 0;
}
/**
* @brief Capture a single PWM period/pulse width in nanoseconds for a single
* PWM input.
*
* This API function wraps calls to pwm_capture_cycles() and
* pwm_cycles_to_nsec() and passes the capture result to the caller. The
* function is blocking until either the PWM capture is completed or a timeout
* occurs.
*
* @note @kconfig{CONFIG_PWM_CAPTURE} must be selected for this function to be
* available.
*
* @param[in] dev PWM device instance.
* @param channel PWM channel.
* @param flags PWM capture flags.
* @param[out] period Pointer to the memory to store the captured PWM period
* width (in nsec).
* @param[out] pulse Pointer to the memory to store the captured PWM pulse width
* (in nsec).
* @param timeout Waiting period for the capture to complete.
*
* @retval 0 If successful.
* @retval -EBUSY PWM capture already in progress.
* @retval -EAGAIN Waiting period timed out.
* @retval -EIO IO error while capturing.
* @retval -ERANGE If result is too large.
* @retval -errno Other negative errno code on failure.
*/
static inline int pwm_capture_nsec(const struct device *dev, uint32_t channel,
pwm_flags_t flags, uint64_t *period,
uint64_t *pulse, k_timeout_t timeout)
{
int err;
uint32_t pulse_cycles;
uint32_t period_cycles;
err = pwm_capture_cycles(dev, channel, flags, &period_cycles,
&pulse_cycles, timeout);
if (err < 0) {
return err;
}
err = pwm_cycles_to_nsec(dev, channel, period_cycles, period);
if (err < 0) {
return err;
}
err = pwm_cycles_to_nsec(dev, channel, pulse_cycles, pulse);
if (err < 0) {
return err;
}
return 0;
}
/**
* @brief Validate that the PWM device is ready.
*
* @param spec PWM specification from devicetree
*
* @retval true If the PWM device is ready for use
* @retval false If the PWM device is not ready for use
*/
static inline bool pwm_is_ready_dt(const struct pwm_dt_spec *spec)
{
return device_is_ready(spec->dev);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/pwm.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_PWM_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/pwm.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 7,362 |
```objective-c
/*
*/
#ifndef INCLUDE_ZEPHYR_DRIVERS_EMUL_BBRAM_H_
#define INCLUDE_ZEPHYR_DRIVERS_EMUL_BBRAM_H_
#include <zephyr/drivers/emul.h>
#include <stdint.h>
/**
* @brief BBRAM emulator backend API
* @defgroup bbram_emulator_backend BBRAM emulator backend API
* @ingroup io_interfaces
* @{
*/
/**
* @cond INTERNAL_HIDDEN
*
* These are for internal use only, so skip these in public documentation.
*/
__subsystem struct emul_bbram_driver_api {
/** Sets the data */
int (*set_data)(const struct emul *target, size_t offset, size_t count,
const uint8_t *data);
/** Checks the data */
int (*get_data)(const struct emul *target, size_t offset, size_t count, uint8_t *data);
};
/**
* @endcond
*/
/**
* @brief Set the expected data in the bbram region
*
* @param target Pointer to the emulator instance to operate on
* @param offset Offset within the memory to set
* @param count Number of bytes to write
* @param data The data to write
* @return 0 if successful
* @return -ENOTSUP if no backend API or if the set_data function isn't implemented
* @return -ERANGE if the destination address is out of range.
*/
static inline int emul_bbram_backend_set_data(const struct emul *target, size_t offset,
size_t count, const uint8_t *data)
{
if (target == NULL || target->backend_api == NULL) {
return -ENOTSUP;
}
struct emul_bbram_driver_api *api = (struct emul_bbram_driver_api *)target->backend_api;
if (api->set_data == NULL) {
return -ENOTSUP;
}
return api->set_data(target, offset, count, data);
}
/**
* @brief Get the expected data in the bbram region
*
* @param target Pointer to the emulator instance to operate on
* @param offset Offset within the memory to get
* @param count Number of bytes to read
* @param data The data buffer to hold the result
* @return 0 if successful
* @return -ENOTSUP if no backend API or if the get_data function isn't implemented
* @return -ERANGE if the address is out of range.
*/
static inline int emul_bbram_backend_get_data(const struct emul *target, size_t offset,
size_t count, uint8_t *data)
{
if (target == NULL || target->backend_api == NULL) {
return -ENOTSUP;
}
struct emul_bbram_driver_api *api = (struct emul_bbram_driver_api *)target->backend_api;
if (api->get_data == NULL) {
return -ENOTSUP;
}
return api->get_data(target, offset, count, data);
}
/**
* @}
*/
#endif /* INCLUDE_ZEPHYR_DRIVERS_EMUL_BBRAM_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/emul_bbram.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 659 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public SYSCON driver APIs
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_SYSCON_H_
#define ZEPHYR_INCLUDE_DRIVERS_SYSCON_H_
/**
* @brief SYSCON Interface
* @defgroup syscon_interface SYSCON Interface
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* API template to get the base address of the syscon region.
*
* @see syscon_get_base
*/
typedef int (*syscon_api_get_base)(const struct device *dev, uintptr_t *addr);
/**
* API template to read a single register.
*
* @see syscon_read_reg
*/
typedef int (*syscon_api_read_reg)(const struct device *dev, uint16_t reg, uint32_t *val);
/**
* API template to write a single register.
*
* @see syscon_write_reg
*/
typedef int (*syscon_api_write_reg)(const struct device *dev, uint16_t reg, uint32_t val);
/**
* API template to get the size of the syscon register.
*
* @see syscon_get_size
*/
typedef int (*syscon_api_get_size)(const struct device *dev, size_t *size);
/**
* @brief System Control (syscon) register driver API
*/
__subsystem struct syscon_driver_api {
syscon_api_read_reg read;
syscon_api_write_reg write;
syscon_api_get_base get_base;
syscon_api_get_size get_size;
};
/**
* @brief Get the syscon base address
*
* @param dev The device to get the register size for.
* @param addr Where to write the base address.
* @return 0 When addr was written to.
*/
__syscall int syscon_get_base(const struct device *dev, uintptr_t *addr);
static inline int z_impl_syscon_get_base(const struct device *dev, uintptr_t *addr)
{
const struct syscon_driver_api *api = (const struct syscon_driver_api *)dev->api;
if (api == NULL) {
return -ENOTSUP;
}
return api->get_base(dev, addr);
}
/**
* @brief Read from syscon register
*
* This function reads from a specific register in the syscon area
*
* @param dev The device to get the register size for.
* @param reg The register offset
* @param val The returned value read from the syscon register
*
* @return 0 on success, negative on error
*/
__syscall int syscon_read_reg(const struct device *dev, uint16_t reg, uint32_t *val);
static inline int z_impl_syscon_read_reg(const struct device *dev, uint16_t reg, uint32_t *val)
{
const struct syscon_driver_api *api = (const struct syscon_driver_api *)dev->api;
if (api == NULL) {
return -ENOTSUP;
}
return api->read(dev, reg, val);
}
/**
* @brief Write to syscon register
*
* This function writes to a specific register in the syscon area
*
* @param dev The device to get the register size for.
* @param reg The register offset
* @param val The value to be written in the register
*
* @return 0 on success, negative on error
*/
__syscall int syscon_write_reg(const struct device *dev, uint16_t reg, uint32_t val);
static inline int z_impl_syscon_write_reg(const struct device *dev, uint16_t reg, uint32_t val)
{
const struct syscon_driver_api *api = (const struct syscon_driver_api *)dev->api;
if (api == NULL) {
return -ENOTSUP;
}
return api->write(dev, reg, val);
}
/**
* Get the size of the syscon register in bytes.
*
* @param dev The device to get the register size for.
* @param size Pointer to write the size to.
* @return 0 for success.
*/
__syscall int syscon_get_size(const struct device *dev, size_t *size);
static inline int z_impl_syscon_get_size(const struct device *dev, size_t *size)
{
const struct syscon_driver_api *api = (const struct syscon_driver_api *)dev->api;
return api->get_size(dev, size);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/syscon.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_SYSCON_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/syscon.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 976 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public SMBus Driver APIs
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_SMBUS_H_
#define ZEPHYR_INCLUDE_DRIVERS_SMBUS_H_
/**
* @brief SMBus Interface
* @defgroup smbus_interface SMBus Interface
* @since 3.4
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/sys/slist.h>
#include <zephyr/types.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name SMBus Protocol commands
* @{
*
* SMBus Specification defines the following SMBus protocols operations
*/
/**
* SMBus Quick protocol is a very simple command with no data sent or
* received. Peripheral may denote only R/W bit, which can still be
* used for the peripheral management, for example to switch peripheral
* On/Off. Quick protocol can also be used for peripheral devices
* scanning.
*
* @code
* 0 1
* 0 1 2 3 4 5 6 7 8 9 0
* +-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |D|A|P|
* +-+-+-+-+-+-+-+-+-+-+-+
* @endcode
*/
#define SMBUS_CMD_QUICK 0b000
/**
* SMBus Byte protocol can send or receive one byte of data.
*
* @code
* Byte Write
*
* 0 1 2
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |W|A| Command code |A|P|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Byte Read
*
* 0 1 2
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |R|A| Byte received |N|P|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* @endcode
*/
#define SMBUS_CMD_BYTE 0b001
/**
* SMBus Byte Data protocol sends the first byte (command) followed
* by read or write one byte.
*
* @code
* Byte Data Write
*
* 0 1 2
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |W|A| Command code |A| Data Write |A|P|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Byte Data Read
*
* 0 1 2
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |W|A| Command code |A|S| Periph Addr |R|A|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Data Read |N|P|
* +-+-+-+-+-+-+-+-+-+-+
* @endcode
*/
#define SMBUS_CMD_BYTE_DATA 0b010
/**
* SMBus Word Data protocol sends the first byte (command) followed
* by read or write two bytes.
*
* @code
* Word Data Write
*
* 0 1 2
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |W|A| Command code |A| Data Write Low|A|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Data Write Hi |A|P|
* +-+-+-+-+-+-+-+-+-+-+
*
* Word Data Read
*
* 0 1 2
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |W|A| Command code |A|S| Periph Addr |R|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |A| Data Read Low |A| Data Read Hi |N|P|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* @endcode
*/
#define SMBUS_CMD_WORD_DATA 0b011
/**
* SMBus Process Call protocol is Write Word followed by
* Read Word. It is named so because the command sends data and waits
* for the peripheral to return a reply.
*
* @code
* 0 1 2
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |W|A| Command code |A| Data Write Low|A|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Data Write Hi |A|S| Periph Addr |R|A| Data Read Low |A|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Data Read Hi |N|P|
* +-+-+-+-+-+-+-+-+-+-+
* @endcode
*/
#define SMBUS_CMD_PROC_CALL 0b100
/**
* SMBus Block protocol reads or writes a block of data up to 32 bytes.
* The Count byte specifies the amount of data.
*
* @code
*
* SMBus Block Write
*
* 0 1 2
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |W|A| Command code |A| Send Count=N |A|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Data Write 1 |A| ... |A| Data Write N |A|P|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* SMBus Block Read
*
* 0 1 2
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |W|A| Command code |A|S| Periph Addr |R|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |A| Recv Count=N |A| Data Read 1 |A| ... |A|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Data Read N |N|P|
* +-+-+-+-+-+-+-+-+-+-+
* @endcode
*/
#define SMBUS_CMD_BLOCK 0b101
/**
* SMBus Block Write - Block Read Process Call protocol is
* Block Write followed by Block Read.
*
* @code
* 0 1 2
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |S| Periph Addr |W|A| Command code |A| Count = N |A|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Data Write 1 |A| ... |A| Data Write N |A|S|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Periph Addr |R|A| Recv Count=N |A| Data Read 1 |A| |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ... |A| Data Read N |N|P|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* @endcode
*/
#define SMBUS_CMD_BLOCK_PROC 0b111
/** @} */
/** Maximum number of bytes in SMBus Block protocol */
#define SMBUS_BLOCK_BYTES_MAX 32
/**
* @name SMBus device functionality
* @{
*
* The following parameters describe the functionality of the SMBus device
*/
/** Peripheral to act as Controller. */
#define SMBUS_MODE_CONTROLLER BIT(0)
/** Support Packet Error Code (PEC) checking */
#define SMBUS_MODE_PEC BIT(1)
/** Support Host Notify functionality */
#define SMBUS_MODE_HOST_NOTIFY BIT(2)
/** Support SMBALERT signal functionality */
#define SMBUS_MODE_SMBALERT BIT(3)
/** @} */
/**
* @name SMBus special reserved addresses
* @{
*
* The following addresses are reserved by SMBus specification
*/
/**
* @brief Alert Response Address (ARA)
*
* A broadcast address used by the system host as part of the
* Alert Response Protocol.
*/
#define SMBUS_ADDRESS_ARA 0x0c
/** @} */
/**
* @name SMBus read / write direction
* @{
*/
/** @brief SMBus read / write direction */
enum smbus_direction {
/** Write a message to SMBus peripheral */
SMBUS_MSG_WRITE = 0,
/** Read a message from SMBus peripheral */
SMBUS_MSG_READ = 1,
};
/** @} */
/** @cond INTERNAL_HIDDEN */
#define SMBUS_MSG_RW_MASK BIT(0)
/** @endcond */
struct smbus_callback;
/**
* @brief Define SMBus callback handler function signature.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param cb Structure smbus_callback owning this handler.
* @param addr Address of the SMBus peripheral device.
*/
typedef void (*smbus_callback_handler_t)(const struct device *dev,
struct smbus_callback *cb,
uint8_t addr);
/**
* @brief SMBus callback structure
*
* Used to register a callback in the driver instance callback list.
* As many callbacks as needed can be added as long as each of them
* is a unique pointer of struct smbus_callback.
*
* Note: Such struct should not be allocated on stack.
*/
struct smbus_callback {
/** This should be used in driver for a callback list management */
sys_snode_t node;
/** Actual callback function being called when relevant */
smbus_callback_handler_t handler;
/** Peripheral device address */
uint8_t addr;
};
/**
* @brief Complete SMBus DT information
*/
struct smbus_dt_spec {
/** SMBus bus */
const struct device *bus;
/** Address of the SMBus peripheral device */
uint16_t addr;
};
/**
* @brief Structure initializer for smbus_dt_spec from devicetree
*
* This helper macro expands to a static initializer for a <tt>struct
* smbus_dt_spec</tt> by reading the relevant bus and address data from
* the devicetree.
*
* @param node_id Devicetree node identifier for the SMBus device whose
* struct smbus_dt_spec to create an initializer for
*/
#define SMBUS_DT_SPEC_GET(node_id) \
{ \
.bus = DEVICE_DT_GET(DT_BUS(node_id)), \
.addr = DT_REG_ADDR(node_id) \
}
/**
* @brief Structure initializer for smbus_dt_spec from devicetree instance
*
* This is equivalent to
* <tt>SMBUS_DT_SPEC_GET(DT_DRV_INST(inst))</tt>.
*
* @param inst Devicetree instance number
*/
#define SMBUS_DT_SPEC_INST_GET(inst) SMBUS_DT_SPEC_GET(DT_DRV_INST(inst))
/**
* @cond INTERNAL_HIDDEN
*
* These are for internal use only, so skip these in
* public documentation.
*/
typedef int (*smbus_api_configure_t)(const struct device *dev,
uint32_t dev_config);
typedef int (*smbus_api_get_config_t)(const struct device *dev,
uint32_t *dev_config);
typedef int (*smbus_api_quick_t)(const struct device *dev,
uint16_t addr, enum smbus_direction);
typedef int (*smbus_api_byte_write_t)(const struct device *dev,
uint16_t addr, uint8_t byte);
typedef int (*smbus_api_byte_read_t)(const struct device *dev,
uint16_t addr, uint8_t *byte);
typedef int (*smbus_api_byte_data_write_t)(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t byte);
typedef int (*smbus_api_byte_data_read_t)(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t *byte);
typedef int (*smbus_api_word_data_write_t)(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint16_t word);
typedef int (*smbus_api_word_data_read_t)(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint16_t *word);
typedef int (*smbus_api_pcall_t)(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint16_t send_word, uint16_t *recv_word);
typedef int (*smbus_api_block_write_t)(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t count, uint8_t *buf);
typedef int (*smbus_api_block_read_t)(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t *count, uint8_t *buf);
typedef int (*smbus_api_block_pcall_t)(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t send_count, uint8_t *send_buf,
uint8_t *recv_count, uint8_t *recv_buf);
typedef int (*smbus_api_smbalert_cb_t)(const struct device *dev,
struct smbus_callback *cb);
typedef int (*smbus_api_host_notify_cb_t)(const struct device *dev,
struct smbus_callback *cb);
__subsystem struct smbus_driver_api {
smbus_api_configure_t configure;
smbus_api_get_config_t get_config;
smbus_api_quick_t smbus_quick;
smbus_api_byte_write_t smbus_byte_write;
smbus_api_byte_read_t smbus_byte_read;
smbus_api_byte_data_write_t smbus_byte_data_write;
smbus_api_byte_data_read_t smbus_byte_data_read;
smbus_api_word_data_write_t smbus_word_data_write;
smbus_api_word_data_read_t smbus_word_data_read;
smbus_api_pcall_t smbus_pcall;
smbus_api_block_write_t smbus_block_write;
smbus_api_block_read_t smbus_block_read;
smbus_api_block_pcall_t smbus_block_pcall;
smbus_api_smbalert_cb_t smbus_smbalert_set_cb;
smbus_api_smbalert_cb_t smbus_smbalert_remove_cb;
smbus_api_host_notify_cb_t smbus_host_notify_set_cb;
smbus_api_host_notify_cb_t smbus_host_notify_remove_cb;
};
/**
* @endcond
*/
#if defined(CONFIG_SMBUS_STATS) || defined(__DOXYGEN__)
#include <zephyr/stats/stats.h>
/** @cond INTERNAL_HIDDEN */
STATS_SECT_START(smbus)
STATS_SECT_ENTRY32(bytes_read)
STATS_SECT_ENTRY32(bytes_written)
STATS_SECT_ENTRY32(command_count)
STATS_SECT_END;
STATS_NAME_START(smbus)
STATS_NAME(smbus, bytes_read)
STATS_NAME(smbus, bytes_written)
STATS_NAME(smbus, command_count)
STATS_NAME_END(smbus);
struct smbus_device_state {
struct device_state devstate;
struct stats_smbus stats;
};
/**
* @brief Define a statically allocated and section assigned smbus device state
*/
#define Z_SMBUS_DEVICE_STATE_DEFINE(node_id, dev_name) \
static struct smbus_device_state Z_DEVICE_STATE_NAME(dev_name) \
__attribute__((__section__(".z_devstate")));
/**
* @brief Define an smbus device init wrapper function
*
* This does device instance specific initialization of common data
* (such as stats) and calls the given init_fn
*/
#define Z_SMBUS_INIT_FN(dev_name, init_fn) \
static inline int \
UTIL_CAT(dev_name, _init)(const struct device *dev) \
{ \
struct smbus_device_state *state = \
CONTAINER_OF(dev->state, \
struct smbus_device_state, \
devstate); \
stats_init(&state->stats.s_hdr, STATS_SIZE_32, 4, \
STATS_NAME_INIT_PARMS(smbus)); \
stats_register(dev->name, &(state->stats.s_hdr)); \
return init_fn(dev); \
}
/** @endcond */
/**
* @brief Updates the SMBus stats
*
* @param dev Pointer to the device structure for the SMBus driver instance
* to update stats for.
* @param sent Number of bytes sent
* @param recv Number of bytes received
*/
static inline void smbus_xfer_stats(const struct device *dev, uint8_t sent,
uint8_t recv)
{
struct smbus_device_state *state =
CONTAINER_OF(dev->state, struct smbus_device_state, devstate);
STATS_INC(state->stats, command_count);
STATS_INCN(state->stats, bytes_read, recv);
STATS_INCN(state->stats, bytes_written, sent);
}
/**
* @brief Like DEVICE_DT_DEFINE() with SMBus specifics.
*
* @details Defines a device which implements the SMBus API. May
* generate a custom device_state container struct and init_fn
* wrapper when needed depending on SMBus @kconfig{CONFIG_SMBUS_STATS}.
*
* @param node_id The devicetree node identifier.
*
* @param init_fn Name of the init function of the driver.
*
* @param pm_device PM device resources reference
* (NULL if device does not use PM).
*
* @param data_ptr Pointer to the device's private data.
*
* @param cfg_ptr The address to the structure containing the
* configuration information for this instance of the driver.
*
* @param level The initialization level. See SYS_INIT() for
* details.
*
* @param prio Priority within the selected initialization level. See
* SYS_INIT() for details.
*
* @param api_ptr Provides an initial pointer to the API function struct
* used by the driver. Can be NULL.
*/
#define SMBUS_DEVICE_DT_DEFINE(node_id, init_fn, pm_device, \
data_ptr, cfg_ptr, level, prio, \
api_ptr, ...) \
Z_SMBUS_DEVICE_STATE_DEFINE(node_id, \
Z_DEVICE_DT_DEV_NAME(node_id)); \
Z_SMBUS_INIT_FN(Z_DEVICE_DT_DEV_NAME(node_id), init_fn) \
Z_DEVICE_DEFINE(node_id, Z_DEVICE_DT_DEV_NAME(node_id), \
DEVICE_DT_NAME(node_id), \
&UTIL_CAT(Z_DEVICE_DT_DEV_NAME(node_id), _init),\
pm_device, \
data_ptr, cfg_ptr, level, prio, \
api_ptr, \
&(Z_DEVICE_STATE_NAME(Z_DEVICE_DT_DEV_NAME \
(node_id)).devstate), \
__VA_ARGS__)
#else /* CONFIG_SMBUS_STATS */
static inline void smbus_xfer_stats(const struct device *dev, uint8_t sent,
uint8_t recv)
{
ARG_UNUSED(dev);
ARG_UNUSED(sent);
ARG_UNUSED(recv);
}
#define SMBUS_DEVICE_DT_DEFINE(node_id, init_fn, pm_device, \
data_ptr, cfg_ptr, level, prio, \
api_ptr, ...) \
DEVICE_DT_DEFINE(node_id, &init_fn, pm_device, \
data_ptr, cfg_ptr, level, prio, \
api_ptr, __VA_ARGS__)
#endif /* CONFIG_SMBUS_STATS */
/**
* @brief Like SMBUS_DEVICE_DT_DEFINE() for an instance of a DT_DRV_COMPAT
* compatible
*
* @param inst instance number. This is replaced by
* <tt>DT_DRV_COMPAT(inst)</tt> in the call to SMBUS_DEVICE_DT_DEFINE().
*
* @param ... other parameters as expected by SMBUS_DEVICE_DT_DEFINE().
*/
#define SMBUS_DEVICE_DT_INST_DEFINE(inst, ...) \
SMBUS_DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
/**
* @brief Configure operation of a SMBus host controller.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param dev_config Bit-packed 32-bit value to the device runtime configuration
* for the SMBus controller.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
__syscall int smbus_configure(const struct device *dev, uint32_t dev_config);
static inline int z_impl_smbus_configure(const struct device *dev,
uint32_t dev_config)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
return api->configure(dev, dev_config);
}
/**
* @brief Get configuration of a SMBus host controller.
*
* This routine provides a way to get current configuration. It is allowed to
* call the function before smbus_configure, because some SMBus ports can be
* configured during init process. However, if the SMBus port is not configured,
* smbus_get_config returns an error.
*
* smbus_get_config can return cached config or probe hardware, but it has to be
* up to date with current configuration.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param dev_config Pointer to return bit-packed 32-bit value of
* the SMBus controller configuration.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_get_config() is not implemented
* by the driver.
*/
__syscall int smbus_get_config(const struct device *dev, uint32_t *dev_config);
static inline int z_impl_smbus_get_config(const struct device *dev,
uint32_t *dev_config)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->get_config == NULL) {
return -ENOSYS;
}
return api->get_config(dev, dev_config);
}
/**
* @brief Add SMBUSALERT callback for a SMBus host controller.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param cb Pointer to a callback structure.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_smbalert_set_cb() is not implemented
* by the driver.
*/
static inline int smbus_smbalert_set_cb(const struct device *dev,
struct smbus_callback *cb)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_smbalert_set_cb == NULL) {
return -ENOSYS;
}
return api->smbus_smbalert_set_cb(dev, cb);
}
/**
* @brief Remove SMBUSALERT callback from a SMBus host controller.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param cb Pointer to a callback structure.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_smbalert_remove_cb() is not implemented
* by the driver.
*/
__syscall int smbus_smbalert_remove_cb(const struct device *dev,
struct smbus_callback *cb);
static inline int z_impl_smbus_smbalert_remove_cb(const struct device *dev,
struct smbus_callback *cb)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_smbalert_remove_cb == NULL) {
return -ENOSYS;
}
return api->smbus_smbalert_remove_cb(dev, cb);
}
/**
* @brief Add Host Notify callback for a SMBus host controller.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param cb Pointer to a callback structure.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_host_notify_set_cb() is not implemented
* by the driver.
*/
static inline int smbus_host_notify_set_cb(const struct device *dev,
struct smbus_callback *cb)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_host_notify_set_cb == NULL) {
return -ENOSYS;
}
return api->smbus_host_notify_set_cb(dev, cb);
}
/**
* @brief Remove Host Notify callback from a SMBus host controller.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param cb Pointer to a callback structure.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_host_notify_remove_cb() is not implemented
* by the driver.
*/
__syscall int smbus_host_notify_remove_cb(const struct device *dev,
struct smbus_callback *cb);
static inline int z_impl_smbus_host_notify_remove_cb(const struct device *dev,
struct smbus_callback *cb)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_host_notify_remove_cb == NULL) {
return -ENOSYS;
}
return api->smbus_host_notify_remove_cb(dev, cb);
}
/**
* @brief Perform SMBus Quick operation
*
* This routine provides a generic interface to perform SMBus Quick
* operation.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* driver configured in controller mode.
* @param addr Address of the SMBus peripheral device.
* @param direction Direction Read or Write.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_quick() is not implemented
* by the driver.
*/
__syscall int smbus_quick(const struct device *dev, uint16_t addr,
enum smbus_direction direction);
static inline int z_impl_smbus_quick(const struct device *dev, uint16_t addr,
enum smbus_direction direction)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_quick == NULL) {
return -ENOSYS;
}
if (direction != SMBUS_MSG_READ && direction != SMBUS_MSG_WRITE) {
return -EINVAL;
}
return api->smbus_quick(dev, addr, direction);
}
/**
* @brief Perform SMBus Byte Write operation
*
* This routine provides a generic interface to perform SMBus
* Byte Write operation.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param addr Address of the SMBus peripheral device.
* @param byte Byte to be sent to the peripheral device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_byte_write() is not implemented
* by the driver.
*/
__syscall int smbus_byte_write(const struct device *dev, uint16_t addr,
uint8_t byte);
static inline int z_impl_smbus_byte_write(const struct device *dev,
uint16_t addr, uint8_t byte)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_byte_write == NULL) {
return -ENOSYS;
}
return api->smbus_byte_write(dev, addr, byte);
}
/**
* @brief Perform SMBus Byte Read operation
*
* This routine provides a generic interface to perform SMBus
* Byte Read operation.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param addr Address of the SMBus peripheral device.
* @param byte Byte received from the peripheral device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_byte_read() is not implemented
* by the driver.
*/
__syscall int smbus_byte_read(const struct device *dev, uint16_t addr,
uint8_t *byte);
static inline int z_impl_smbus_byte_read(const struct device *dev,
uint16_t addr, uint8_t *byte)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_byte_read == NULL) {
return -ENOSYS;
}
return api->smbus_byte_read(dev, addr, byte);
}
/**
* @brief Perform SMBus Byte Data Write operation
*
* This routine provides a generic interface to perform SMBus
* Byte Data Write operation.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param addr Address of the SMBus peripheral device.
* @param cmd Command byte which is sent to peripheral device first.
* @param byte Byte to be sent to the peripheral device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_byte_data_write() is not implemented
* by the driver.
*/
__syscall int smbus_byte_data_write(const struct device *dev, uint16_t addr,
uint8_t cmd, uint8_t byte);
static inline int z_impl_smbus_byte_data_write(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t byte)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_byte_data_write == NULL) {
return -ENOSYS;
}
return api->smbus_byte_data_write(dev, addr, cmd, byte);
}
/**
* @brief Perform SMBus Byte Data Read operation
*
* This routine provides a generic interface to perform SMBus
* Byte Data Read operation.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param addr Address of the SMBus peripheral device.
* @param cmd Command byte which is sent to peripheral device first.
* @param byte Byte received from the peripheral device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_byte_data_read() is not implemented
* by the driver.
*/
__syscall int smbus_byte_data_read(const struct device *dev, uint16_t addr,
uint8_t cmd, uint8_t *byte);
static inline int z_impl_smbus_byte_data_read(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t *byte)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_byte_data_read == NULL) {
return -ENOSYS;
}
return api->smbus_byte_data_read(dev, addr, cmd, byte);
}
/**
* @brief Perform SMBus Word Data Write operation
*
* This routine provides a generic interface to perform SMBus
* Word Data Write operation.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param addr Address of the SMBus peripheral device.
* @param cmd Command byte which is sent to peripheral device first.
* @param word Word (16-bit) to be sent to the peripheral device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_word_data_write() is not implemented
* by the driver.
*/
__syscall int smbus_word_data_write(const struct device *dev, uint16_t addr,
uint8_t cmd, uint16_t word);
static inline int z_impl_smbus_word_data_write(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint16_t word)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_word_data_write == NULL) {
return -ENOSYS;
}
return api->smbus_word_data_write(dev, addr, cmd, word);
}
/**
* @brief Perform SMBus Word Data Read operation
*
* This routine provides a generic interface to perform SMBus
* Word Data Read operation.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param addr Address of the SMBus peripheral device.
* @param cmd Command byte which is sent to peripheral device first.
* @param word Word (16-bit) received from the peripheral device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_word_data_read() is not implemented
* by the driver.
*/
__syscall int smbus_word_data_read(const struct device *dev, uint16_t addr,
uint8_t cmd, uint16_t *word);
static inline int z_impl_smbus_word_data_read(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint16_t *word)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_word_data_read == NULL) {
return -ENOSYS;
}
return api->smbus_word_data_read(dev, addr, cmd, word);
}
/**
* @brief Perform SMBus Process Call operation
*
* This routine provides a generic interface to perform SMBus
* Process Call operation, which means Write 2 bytes following by
* Read 2 bytes.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param addr Address of the SMBus peripheral device.
* @param cmd Command byte which is sent to peripheral device first.
* @param send_word Word (16-bit) to be sent to the peripheral device.
* @param recv_word Word (16-bit) received from the peripheral device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_pcall() is not implemented
* by the driver.
*/
__syscall int smbus_pcall(const struct device *dev, uint16_t addr,
uint8_t cmd, uint16_t send_word, uint16_t *recv_word);
static inline int z_impl_smbus_pcall(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint16_t send_word, uint16_t *recv_word)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_pcall == NULL) {
return -ENOSYS;
}
return api->smbus_pcall(dev, addr, cmd, send_word, recv_word);
}
/**
* @brief Perform SMBus Block Write operation
*
* This routine provides a generic interface to perform SMBus
* Block Write operation.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param addr Address of the SMBus peripheral device.
* @param cmd Command byte which is sent to peripheral device first.
* @param count Size of the data block buffer. Maximum 32 bytes.
* @param buf Data block buffer to be sent to the peripheral device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_block_write() is not implemented
* by the driver.
*/
__syscall int smbus_block_write(const struct device *dev, uint16_t addr,
uint8_t cmd, uint8_t count, uint8_t *buf);
static inline int z_impl_smbus_block_write(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t count, uint8_t *buf)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_block_write == NULL) {
return -ENOSYS;
}
if (count < 1 || count > SMBUS_BLOCK_BYTES_MAX) {
return -EINVAL;
}
return api->smbus_block_write(dev, addr, cmd, count, buf);
}
/**
* @brief Perform SMBus Block Read operation
*
* This routine provides a generic interface to perform SMBus
* Block Read operation.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param addr Address of the SMBus peripheral device.
* @param cmd Command byte which is sent to peripheral device first.
* @param count Size of the data peripheral sent. Maximum 32 bytes.
* @param buf Data block buffer received from the peripheral device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_block_read() is not implemented
* by the driver.
*/
__syscall int smbus_block_read(const struct device *dev, uint16_t addr,
uint8_t cmd, uint8_t *count, uint8_t *buf);
static inline int z_impl_smbus_block_read(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t *count, uint8_t *buf)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_block_read == NULL) {
return -ENOSYS;
}
return api->smbus_block_read(dev, addr, cmd, count, buf);
}
/**
* @brief Perform SMBus Block Process Call operation
*
* This routine provides a generic interface to perform SMBus
* Block Process Call operation. This operation is basically
* Block Write followed by Block Read.
*
* @param dev Pointer to the device structure for the SMBus driver instance.
* @param addr Address of the SMBus peripheral device.
* @param cmd Command byte which is sent to peripheral device first.
* @param snd_count Size of the data block buffer to send.
* @param snd_buf Data block buffer send to the peripheral device.
* @param rcv_count Size of the data peripheral sent.
* @param rcv_buf Data block buffer received from the peripheral device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If function smbus_block_pcall() is not implemented
* by the driver.
*/
__syscall int smbus_block_pcall(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t snd_count, uint8_t *snd_buf,
uint8_t *rcv_count, uint8_t *rcv_buf);
static inline int z_impl_smbus_block_pcall(const struct device *dev,
uint16_t addr, uint8_t cmd,
uint8_t snd_count, uint8_t *snd_buf,
uint8_t *rcv_count, uint8_t *rcv_buf)
{
const struct smbus_driver_api *api =
(const struct smbus_driver_api *)dev->api;
if (api->smbus_block_pcall == NULL) {
return -ENOSYS;
}
return api->smbus_block_pcall(dev, addr, cmd, snd_count, snd_buf,
rcv_count, rcv_buf);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/smbus.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_SMBUS_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/smbus.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 8,965 |
```objective-c
/*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_REGULATOR_H_
#define ZEPHYR_INCLUDE_DRIVERS_REGULATOR_H_
/**
* @brief Regulator Interface
* @defgroup regulator_interface Regulator Interface
* @since 2.4
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <stdint.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#ifdef CONFIG_REGULATOR_THREAD_SAFE_REFCNT
#include <zephyr/kernel.h>
#endif
#include <zephyr/sys/util_macro.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Opaque type to store regulator DVS states */
typedef uint8_t regulator_dvs_state_t;
/** Opaque type to store regulator modes */
typedef uint8_t regulator_mode_t;
/** Opaque bit map for regulator error flags (see @ref REGULATOR_ERRORS) */
typedef uint8_t regulator_error_flags_t;
/**
* @name Regulator error flags.
* @anchor REGULATOR_ERRORS
* @{
*/
/** Voltage is too high. */
#define REGULATOR_ERROR_OVER_VOLTAGE BIT(0)
/** Current is too high. */
#define REGULATOR_ERROR_OVER_CURRENT BIT(1)
/** Temperature is too high. */
#define REGULATOR_ERROR_OVER_TEMP BIT(2)
/** @} */
/** @cond INTERNAL_HIDDEN */
typedef int (*regulator_dvs_state_set_t)(const struct device *dev,
regulator_dvs_state_t state);
typedef int (*regulator_ship_mode_t)(const struct device *dev);
/** @brief Driver-specific API functions to support parent regulator control. */
__subsystem struct regulator_parent_driver_api {
regulator_dvs_state_set_t dvs_state_set;
regulator_ship_mode_t ship_mode;
};
typedef int (*regulator_enable_t)(const struct device *dev);
typedef int (*regulator_disable_t)(const struct device *dev);
typedef unsigned int (*regulator_count_voltages_t)(const struct device *dev);
typedef int (*regulator_list_voltage_t)(const struct device *dev,
unsigned int idx, int32_t *volt_uv);
typedef int (*regulator_set_voltage_t)(const struct device *dev, int32_t min_uv,
int32_t max_uv);
typedef int (*regulator_get_voltage_t)(const struct device *dev,
int32_t *volt_uv);
typedef unsigned int (*regulator_count_current_limits_t)(const struct device *dev);
typedef int (*regulator_list_current_limit_t)(const struct device *dev,
unsigned int idx, int32_t *current_ua);
typedef int (*regulator_set_current_limit_t)(const struct device *dev,
int32_t min_ua, int32_t max_ua);
typedef int (*regulator_get_current_limit_t)(const struct device *dev,
int32_t *curr_ua);
typedef int (*regulator_set_mode_t)(const struct device *dev,
regulator_mode_t mode);
typedef int (*regulator_get_mode_t)(const struct device *dev,
regulator_mode_t *mode);
typedef int (*regulator_set_active_discharge_t)(const struct device *dev,
bool active_discharge);
typedef int (*regulator_get_active_discharge_t)(const struct device *dev,
bool *active_discharge);
typedef int (*regulator_get_error_flags_t)(
const struct device *dev, regulator_error_flags_t *flags);
/** @brief Driver-specific API functions to support regulator control. */
__subsystem struct regulator_driver_api {
regulator_enable_t enable;
regulator_disable_t disable;
regulator_count_voltages_t count_voltages;
regulator_list_voltage_t list_voltage;
regulator_set_voltage_t set_voltage;
regulator_get_voltage_t get_voltage;
regulator_count_current_limits_t count_current_limits;
regulator_list_current_limit_t list_current_limit;
regulator_set_current_limit_t set_current_limit;
regulator_get_current_limit_t get_current_limit;
regulator_set_mode_t set_mode;
regulator_get_mode_t get_mode;
regulator_set_active_discharge_t set_active_discharge;
regulator_get_active_discharge_t get_active_discharge;
regulator_get_error_flags_t get_error_flags;
};
/**
* @name Regulator flags
* @anchor REGULATOR_FLAGS
* @{
*/
/** Indicates regulator must stay always ON */
#define REGULATOR_ALWAYS_ON BIT(0)
/** Indicates regulator must be initialized ON */
#define REGULATOR_BOOT_ON BIT(1)
/** Indicates if regulator must be enabled when initialized */
#define REGULATOR_INIT_ENABLED (REGULATOR_ALWAYS_ON | REGULATOR_BOOT_ON)
/** Regulator active discharge state mask */
#define REGULATOR_ACTIVE_DISCHARGE_MASK GENMASK(3, 2)
/** Regulator active discharge state flag position*/
#define REGULATOR_ACTIVE_DISCHARGE_POS 2
/** Disable regulator active discharge */
#define REGULATOR_ACTIVE_DISCHARGE_DISABLE 0
/** Enable regulator active discharge */
#define REGULATOR_ACTIVE_DISCHARGE_ENABLE 1
/** Leave regulator active discharge state as default */
#define REGULATOR_ACTIVE_DISCHARGE_DEFAULT 2
/** Regulator active discharge set bits */
#define REGULATOR_ACTIVE_DISCHARGE_SET_BITS(x) \
(((x) << REGULATOR_ACTIVE_DISCHARGE_POS) & REGULATOR_ACTIVE_DISCHARGE_MASK)
/** Regulator active discharge get bits */
#define REGULATOR_ACTIVE_DISCHARGE_GET_BITS(x) \
(((x) & REGULATOR_ACTIVE_DISCHARGE_MASK) >> REGULATOR_ACTIVE_DISCHARGE_POS)
/** Indicates regulator must be initialized OFF */
#define REGULATOR_BOOT_OFF BIT(4)
/** @} */
/** Indicates initial mode is unknown/not specified */
#define REGULATOR_INITIAL_MODE_UNKNOWN UINT8_MAX
/**
* @brief Common regulator config.
*
* This structure **must** be placed first in the driver's config structure.
*/
struct regulator_common_config {
/** Minimum allowed voltage, in microvolts. */
int32_t min_uv;
/** Maximum allowed voltage, in microvolts. */
int32_t max_uv;
/** Initial voltage, in microvolts. */
int32_t init_uv;
/** Minimum allowed current, in microamps. */
int32_t min_ua;
/** Maximum allowed current, in microamps. */
int32_t max_ua;
/** Initial current, in microamps. */
int32_t init_ua;
/** Startup delay, in microseconds. */
uint32_t startup_delay_us;
/** Off to on delay, in microseconds. */
uint32_t off_on_delay_us;
/** Allowed modes */
const regulator_mode_t *allowed_modes;
/** Number of allowed modes */
uint8_t allowed_modes_cnt;
/** Regulator initial mode */
regulator_mode_t initial_mode;
/** Flags (@reg REGULATOR_FLAGS). */
uint8_t flags;
};
/**
* @brief Initialize common driver config from devicetree.
*
* @param node_id Node identifier.
*/
#define REGULATOR_DT_COMMON_CONFIG_INIT(node_id) \
{ \
.min_uv = DT_PROP_OR(node_id, regulator_min_microvolt, \
INT32_MIN), \
.max_uv = DT_PROP_OR(node_id, regulator_max_microvolt, \
INT32_MAX), \
.init_uv = DT_PROP_OR(node_id, regulator_init_microvolt, \
INT32_MIN), \
.min_ua = DT_PROP_OR(node_id, regulator_min_microamp, \
INT32_MIN), \
.max_ua = DT_PROP_OR(node_id, regulator_max_microamp, \
INT32_MAX), \
.init_ua = DT_PROP_OR(node_id, regulator_init_microamp, \
INT32_MIN), \
.startup_delay_us = DT_PROP_OR(node_id, startup_delay_us, 0), \
.off_on_delay_us = DT_PROP_OR(node_id, off_on_delay_us, 0), \
.allowed_modes = (const regulator_mode_t []) \
DT_PROP_OR(node_id, regulator_allowed_modes, {}), \
.allowed_modes_cnt = \
DT_PROP_LEN_OR(node_id, regulator_allowed_modes, 0), \
.initial_mode = DT_PROP_OR(node_id, regulator_initial_mode, \
REGULATOR_INITIAL_MODE_UNKNOWN), \
.flags = ((DT_PROP_OR(node_id, regulator_always_on, 0U) * \
REGULATOR_ALWAYS_ON) | \
(DT_PROP_OR(node_id, regulator_boot_on, 0U) * \
REGULATOR_BOOT_ON) | \
(REGULATOR_ACTIVE_DISCHARGE_SET_BITS( \
DT_PROP_OR(node_id, regulator_active_discharge, \
REGULATOR_ACTIVE_DISCHARGE_DEFAULT))) | \
(DT_PROP_OR(node_id, regulator_boot_off, 0U) * \
REGULATOR_BOOT_OFF)), \
}
/**
* @brief Initialize common driver config from devicetree instance.
*
* @param inst Instance.
*/
#define REGULATOR_DT_INST_COMMON_CONFIG_INIT(inst) \
REGULATOR_DT_COMMON_CONFIG_INIT(DT_DRV_INST(inst))
/**
* @brief Common regulator data.
*
* This structure **must** be placed first in the driver's data structure.
*/
struct regulator_common_data {
#if defined(CONFIG_REGULATOR_THREAD_SAFE_REFCNT) || defined(__DOXYGEN__)
/** Lock (only if @kconfig{CONFIG_REGULATOR_THREAD_SAFE_REFCNT}=y) */
struct k_mutex lock;
#endif
/** Reference count */
int refcnt;
};
/**
* @brief Initialize common regulator data.
*
* This function **must** be called when driver is initialized.
*
* @param dev Regulator device instance.
*/
void regulator_common_data_init(const struct device *dev);
/**
* @brief Common function to initialize the regulator at init time.
*
* This function needs to be called after drivers initialize the regulator. It
* will:
*
* - Automatically enable the regulator if it is set to `regulator-boot-on`
* or `regulator-always-on` and increase its usage count.
* - Automatically disable the regulator if it is set to `regulator-boot-off`.
* - Configure the regulator mode if `regulator-initial-mode` is set.
* - Ensure regulator voltage is set to a valid range.
*
* Regulators that are enabled by default in hardware, must set @p is_enabled to
* `true`.
*
* @param dev Regulator device instance
* @param is_enabled Indicate if the regulator is enabled by default in
* hardware.
*
* @retval 0 If enabled successfully.
* @retval -errno Negative errno in case of failure.
*/
int regulator_common_init(const struct device *dev, bool is_enabled);
/**
* @brief Check if regulator is expected to be enabled at init time.
*
* @param dev Regulator device instance
* @return true If regulator needs to be enabled at init time.
* @return false If regulator does not need to be enabled at init time.
*/
static inline bool regulator_common_is_init_enabled(const struct device *dev)
{
const struct regulator_common_config *config =
(const struct regulator_common_config *)dev->config;
return (config->flags & REGULATOR_INIT_ENABLED) != 0U;
}
/**
* @brief Get minimum supported voltage.
*
* @param dev Regulator device instance.
* @param min_uv Where minimum voltage will be stored, in microvolts.
*
* @retval 0 If successful
* @retval -ENOENT If minimum voltage is not specified.
*/
static inline int regulator_common_get_min_voltage(const struct device *dev, int32_t *min_uv)
{
const struct regulator_common_config *config =
(const struct regulator_common_config *)dev->config;
if (config->min_uv == INT32_MIN) {
return -ENOENT;
}
*min_uv = config->min_uv;
return 0;
}
/** @endcond */
/**
* @brief Regulator Parent Interface
* @defgroup regulator_parent_interface Regulator Parent Interface
* @{
*/
/**
* @brief Set a DVS state.
*
* Some PMICs feature DVS (Dynamic Voltage Scaling) by allowing to program the
* voltage level for multiple states. Such states may be automatically changed
* by hardware using GPIO pins. Certain MCUs even allow to automatically
* configure specific output pins when entering low-power modes so that PMIC
* state is changed without software intervention. This API can be used when
* state needs to be changed by software.
*
* @param dev Parent regulator device instance.
* @param state DVS state (vendor specific identifier).
*
* @retval 0 If successful.
* @retval -ENOTSUP If given state is not supported.
* @retval -EPERM If state can't be changed by software.
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
static inline int regulator_parent_dvs_state_set(const struct device *dev,
regulator_dvs_state_t state)
{
const struct regulator_parent_driver_api *api =
(const struct regulator_parent_driver_api *)dev->api;
if (api->dvs_state_set == NULL) {
return -ENOSYS;
}
return api->dvs_state_set(dev, state);
}
/**
* @brief Enter ship mode.
*
* Some PMICs feature a ship mode, which allows the system to save power.
* Exit from low power is normally by pin transition.
*
* This API can be used when ship mode needs to be entered.
*
* @param dev Parent regulator device instance.
*
* @retval 0 If successful.
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
static inline int regulator_parent_ship_mode(const struct device *dev)
{
const struct regulator_parent_driver_api *api =
(const struct regulator_parent_driver_api *)dev->api;
if (api->ship_mode == NULL) {
return -ENOSYS;
}
return api->ship_mode(dev);
}
/** @} */
/**
* @brief Enable a regulator.
*
* Reference-counted request that a regulator be turned on. A regulator is
* considered "on" when it has reached a stable/usable state. Regulators that
* are always on, or configured in devicetree with `regulator-always-on` will
* always stay enabled, and so this function will always succeed.
*
* @param dev Regulator device instance
*
* @retval 0 If regulator has been successfully enabled.
* @retval -errno Negative errno in case of failure.
* @retval -ENOTSUP If regulator enablement can not be controlled.
*/
int regulator_enable(const struct device *dev);
/**
* @brief Check if a regulator is enabled.
*
* @param dev Regulator device instance.
*
* @retval true If regulator is enabled.
* @retval false If regulator is disabled.
*/
bool regulator_is_enabled(const struct device *dev);
/**
* @brief Disable a regulator.
*
* Release a regulator after a previous regulator_enable() completed
* successfully. Regulators that are always on, or configured in devicetree with
* `regulator-always-on` will always stay enabled, and so this function will
* always succeed.
*
* This must be invoked at most once for each successful regulator_enable().
*
* @param dev Regulator device instance.
*
* @retval 0 If regulator has been successfully disabled.
* @retval -errno Negative errno in case of failure.
* @retval -ENOTSUP If regulator disablement can not be controlled.
*/
int regulator_disable(const struct device *dev);
/**
* @brief Obtain the number of supported voltage levels.
*
* Each voltage level supported by a regulator gets an index, starting from
* zero. The total number of supported voltage levels can be used together with
* regulator_list_voltage() to list all supported voltage levels.
*
* @param dev Regulator device instance.
*
* @return Number of supported voltages.
*/
static inline unsigned int regulator_count_voltages(const struct device *dev)
{
const struct regulator_driver_api *api =
(const struct regulator_driver_api *)dev->api;
if (api->count_voltages == NULL) {
return 0U;
}
return api->count_voltages(dev);
}
/**
* @brief Obtain the value of a voltage given an index.
*
* Each voltage level supported by a regulator gets an index, starting from
* zero. Together with regulator_count_voltages(), this function can be used
* to iterate over all supported voltages.
*
* @param dev Regulator device instance.
* @param idx Voltage index.
* @param[out] volt_uv Where voltage for the given @p index will be stored, in
* microvolts.
*
* @retval 0 If @p index corresponds to a supported voltage.
* @retval -EINVAL If @p index does not correspond to a supported voltage.
*/
static inline int regulator_list_voltage(const struct device *dev,
unsigned int idx, int32_t *volt_uv)
{
const struct regulator_driver_api *api =
(const struct regulator_driver_api *)dev->api;
if (api->list_voltage == NULL) {
return -EINVAL;
}
return api->list_voltage(dev, idx, volt_uv);
}
/**
* @brief Check if a voltage within a window is supported.
*
* @param dev Regulator device instance.
* @param min_uv Minimum voltage in microvolts.
* @param max_uv maximum voltage in microvolts.
*
* @retval true If voltage is supported.
* @retval false If voltage is not supported.
*/
bool regulator_is_supported_voltage(const struct device *dev, int32_t min_uv,
int32_t max_uv);
/**
* @brief Set the output voltage.
*
* The output voltage will be configured to the closest supported output
* voltage. regulator_get_voltage() can be used to obtain the actual configured
* voltage. The voltage will be applied to the active or selected mode. Output
* voltage may be limited using `regulator-min-microvolt` and/or
* `regulator-max-microvolt` in devicetree.
*
* @param dev Regulator device instance.
* @param min_uv Minimum acceptable voltage in microvolts.
* @param max_uv Maximum acceptable voltage in microvolts.
*
* @retval 0 If successful.
* @retval -EINVAL If the given voltage window is not valid.
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
int regulator_set_voltage(const struct device *dev, int32_t min_uv,
int32_t max_uv);
/**
* @brief Obtain output voltage.
*
* @param dev Regulator device instance.
* @param[out] volt_uv Where configured output voltage will be stored.
*
* @retval 0 If successful
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
static inline int regulator_get_voltage(const struct device *dev,
int32_t *volt_uv)
{
const struct regulator_driver_api *api =
(const struct regulator_driver_api *)dev->api;
if (api->get_voltage == NULL) {
return -ENOSYS;
}
return api->get_voltage(dev, volt_uv);
}
/**
* @brief Obtain the number of supported current limit levels.
*
* Each current limit level supported by a regulator gets an index, starting from
* zero. The total number of supported current limit levels can be used together with
* regulator_list_current_limit() to list all supported current limit levels.
*
* @param dev Regulator device instance.
*
* @return Number of supported current limits.
*/
static inline unsigned int regulator_count_current_limits(const struct device *dev)
{
const struct regulator_driver_api *api =
(const struct regulator_driver_api *)dev->api;
if (api->count_current_limits == NULL) {
return 0U;
}
return api->count_current_limits(dev);
}
/**
* @brief Obtain the value of a current limit given an index.
*
* Each current limit level supported by a regulator gets an index, starting from
* zero. Together with regulator_count_current_limits(), this function can be used
* to iterate over all supported current limits.
*
* @param dev Regulator device instance.
* @param idx Current index.
* @param[out] current_ua Where current for the given @p index will be stored, in
* microamps.
*
* @retval 0 If @p index corresponds to a supported current limit.
* @retval -EINVAL If @p index does not correspond to a supported current limit.
*/
static inline int regulator_list_current_limit(const struct device *dev,
unsigned int idx, int32_t *current_ua)
{
const struct regulator_driver_api *api =
(const struct regulator_driver_api *)dev->api;
if (api->list_current_limit == NULL) {
return -EINVAL;
}
return api->list_current_limit(dev, idx, current_ua);
}
/**
* @brief Set output current limit.
*
* The output current limit will be configured to the closest supported output
* current limit. regulator_get_current_limit() can be used to obtain the actual
* configured current limit. Current may be limited using `current-min-microamp`
* and/or `current-max-microamp` in Devicetree.
*
* @param dev Regulator device instance.
* @param min_ua Minimum acceptable current limit in microamps.
* @param max_ua Maximum acceptable current limit in microamps.
*
* @retval 0 If successful.
* @retval -EINVAL If the given current limit window is not valid.
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
int regulator_set_current_limit(const struct device *dev, int32_t min_ua,
int32_t max_ua);
/**
* @brief Get output current limit.
*
* @param dev Regulator device instance.
* @param[out] curr_ua Where output current limit will be stored.
*
* @retval 0 If successful.
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
static inline int regulator_get_current_limit(const struct device *dev,
int32_t *curr_ua)
{
const struct regulator_driver_api *api =
(const struct regulator_driver_api *)dev->api;
if (api->get_current_limit == NULL) {
return -ENOSYS;
}
return api->get_current_limit(dev, curr_ua);
}
/**
* @brief Set mode.
*
* Regulators can support multiple modes in order to permit different voltage
* configuration or better power savings. This API will apply a mode for
* the regulator. Allowed modes may be limited using `regulator-allowed-modes`
* devicetree property.
*
* @param dev Regulator device instance.
* @param mode Mode to select for this regulator.
*
* @retval 0 If successful.
* @retval -ENOTSUP If mode is not supported.
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
int regulator_set_mode(const struct device *dev, regulator_mode_t mode);
/**
* @brief Get mode.
*
* @param dev Regulator device instance.
* @param[out] mode Where mode will be stored.
*
* @retval 0 If successful.
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
static inline int regulator_get_mode(const struct device *dev,
regulator_mode_t *mode)
{
const struct regulator_driver_api *api =
(const struct regulator_driver_api *)dev->api;
if (api->get_mode == NULL) {
return -ENOSYS;
}
return api->get_mode(dev, mode);
}
/**
* @brief Set active discharge setting.
*
* @param dev Regulator device instance.
* @param active_discharge Active discharge enable or disable.
*
* @retval 0 If successful.
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
static inline int regulator_set_active_discharge(const struct device *dev,
bool active_discharge)
{
const struct regulator_driver_api *api =
(const struct regulator_driver_api *)dev->api;
if (api->set_active_discharge == NULL) {
return -ENOSYS;
}
return api->set_active_discharge(dev, active_discharge);
}
/**
* @brief Get active discharge setting.
*
* @param dev Regulator device instance.
* @param[out] active_discharge Where active discharge will be stored.
*
* @retval 0 If successful.
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
static inline int regulator_get_active_discharge(const struct device *dev,
bool *active_discharge)
{
const struct regulator_driver_api *api =
(const struct regulator_driver_api *)dev->api;
if (api->get_active_discharge == NULL) {
return -ENOSYS;
}
return api->get_active_discharge(dev, active_discharge);
}
/**
* @brief Get active error flags.
*
* @param dev Regulator device instance.
* @param[out] flags Where error flags will be stored.
*
* @retval 0 If successful.
* @retval -ENOSYS If function is not implemented.
* @retval -errno In case of any other error.
*/
static inline int regulator_get_error_flags(const struct device *dev,
regulator_error_flags_t *flags)
{
const struct regulator_driver_api *api =
(const struct regulator_driver_api *)dev->api;
if (api->get_error_flags == NULL) {
return -ENOSYS;
}
return api->get_error_flags(dev, flags);
}
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* ZEPHYR_INCLUDE_DRIVERS_REGULATOR_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/regulator.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 5,468 |
```objective-c
/*
*
*/
/**
* @file drivers/tee.h
*
* @brief Public APIs for the tee driver.
*/
/*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_TEE_H_
#define ZEPHYR_INCLUDE_DRIVERS_TEE_H_
#include <zephyr/device.h>
#include <zephyr/kernel.h>
#include <zephyr/sys/util.h>
/**
* @brief Trusted Execution Environment Interface
* @defgroup tee_interface TEE Interface
* @ingroup io_interfaces
* @{
*
* The generic interface to work with Trusted Execution Environment (TEE).
* TEE is Trusted OS, running in the Secure Space, such as TrustZone in ARM cpus.
* It also can be presented as the separate secure co-processors. It allows system
* to implement logic, separated from the Normal World.
*
* Using TEE syscalls:
* - tee_get_version() to get current TEE capabilities
* - tee_open_session() to open new session to the TA
* - tee_close_session() to close session to the TA
* - tee_cancel() to cancel session or invoke function
* - tee_invoke_func() to invoke function to the TA
* - tee_shm_register() to register shared memory region
* - tee_shm_unregister() to unregister shared memory region
* - tee_shm_alloc() to allocate shared memory region
* - tee_shm_free() to free shared memory region
*/
#ifdef __cplusplus
extern "C" {
#endif
#define TEE_UUID_LEN 16
#define TEE_GEN_CAP_GP BIT(0) /* GlobalPlatform compliant TEE */
#define TEE_GEN_CAP_PRIVILEGED BIT(1) /* Privileged device (for supplicant) */
#define TEE_GEN_CAP_REG_MEM BIT(2) /* Supports registering shared memory */
#define TEE_GEN_CAP_MEMREF_NULL BIT(3) /* Support NULL MemRef */
#define TEE_SHM_REGISTER BIT(0)
#define TEE_SHM_ALLOC BIT(1)
#define TEE_PARAM_ATTR_TYPE_NONE 0 /* parameter not used */
#define TEE_PARAM_ATTR_TYPE_VALUE_INPUT 1
#define TEE_PARAM_ATTR_TYPE_VALUE_OUTPUT 2
#define TEE_PARAM_ATTR_TYPE_VALUE_INOUT 3 /* input and output */
#define TEE_PARAM_ATTR_TYPE_MEMREF_INPUT 5
#define TEE_PARAM_ATTR_TYPE_MEMREF_OUTPUT 6
#define TEE_PARAM_ATTR_TYPE_MEMREF_INOUT 7 /* input and output */
#define TEE_PARAM_ATTR_TYPE_MASK 0xff
#define TEE_PARAM_ATTR_META 0x100
#define TEE_PARAM_ATTR_MASK (TEE_PARAM_ATTR_TYPE_MASK | TEE_PARAM_ATTR_META)
/**
* @brief Function error origins, of type TEEC_ErrorOrigin. These indicate where in
* the software stack a particular return value originates from.
*
* TEEC_ORIGIN_API The error originated within the TEE Client API
* implementation.
* TEEC_ORIGIN_COMMS The error originated within the underlying
* communications stack linking the rich OS with
* the TEE.
* TEEC_ORIGIN_TEE The error originated within the common TEE code.
* TEEC_ORIGIN_TRUSTED_APP The error originated within the Trusted Application
* code.
*/
#define TEEC_ORIGIN_API 0x00000001
#define TEEC_ORIGIN_COMMS 0x00000002
#define TEEC_ORIGIN_TEE 0x00000003
#define TEEC_ORIGIN_TRUSTED_APP 0x00000004
/**
* Return values. Type is TEEC_Result
*
* TEEC_SUCCESS The operation was successful.
* TEEC_ERROR_GENERIC Non-specific cause.
* TEEC_ERROR_ACCESS_DENIED Access privileges are not sufficient.
* TEEC_ERROR_CANCEL The operation was canceled.
* TEEC_ERROR_ACCESS_CONFLICT Concurrent accesses caused conflict.
* TEEC_ERROR_EXCESS_DATA Too much data for the requested operation was
* passed.
* TEEC_ERROR_BAD_FORMAT Input data was of invalid format.
* TEEC_ERROR_BAD_PARAMETERS Input parameters were invalid.
* TEEC_ERROR_BAD_STATE Operation is not valid in the current state.
* TEEC_ERROR_ITEM_NOT_FOUND The requested data item is not found.
* TEEC_ERROR_NOT_IMPLEMENTED The requested operation should exist but is not
* yet implemented.
* TEEC_ERROR_NOT_SUPPORTED The requested operation is valid but is not
* supported in this implementation.
* TEEC_ERROR_NO_DATA Expected data was missing.
* TEEC_ERROR_OUT_OF_MEMORY System ran out of resources.
* TEEC_ERROR_BUSY The system is busy working on something else.
* TEEC_ERROR_COMMUNICATION Communication with a remote party failed.
* TEEC_ERROR_SECURITY A security fault was detected.
* TEEC_ERROR_SHORT_BUFFER The supplied buffer is too short for the
* generated output.
* TEEC_ERROR_TARGET_DEAD Trusted Application has panicked
* during the operation.
*/
/**
* Standard defined error codes.
*/
#define TEEC_SUCCESS 0x00000000
#define TEEC_ERROR_STORAGE_NOT_AVAILABLE 0xF0100003
#define TEEC_ERROR_GENERIC 0xFFFF0000
#define TEEC_ERROR_ACCESS_DENIED 0xFFFF0001
#define TEEC_ERROR_CANCEL 0xFFFF0002
#define TEEC_ERROR_ACCESS_CONFLICT 0xFFFF0003
#define TEEC_ERROR_EXCESS_DATA 0xFFFF0004
#define TEEC_ERROR_BAD_FORMAT 0xFFFF0005
#define TEEC_ERROR_BAD_PARAMETERS 0xFFFF0006
#define TEEC_ERROR_BAD_STATE 0xFFFF0007
#define TEEC_ERROR_ITEM_NOT_FOUND 0xFFFF0008
#define TEEC_ERROR_NOT_IMPLEMENTED 0xFFFF0009
#define TEEC_ERROR_NOT_SUPPORTED 0xFFFF000A
#define TEEC_ERROR_NO_DATA 0xFFFF000B
#define TEEC_ERROR_OUT_OF_MEMORY 0xFFFF000C
#define TEEC_ERROR_BUSY 0xFFFF000D
#define TEEC_ERROR_COMMUNICATION 0xFFFF000E
#define TEEC_ERROR_SECURITY 0xFFFF000F
#define TEEC_ERROR_SHORT_BUFFER 0xFFFF0010
#define TEEC_ERROR_EXTERNAL_CANCEL 0xFFFF0011
#define TEEC_ERROR_TARGET_DEAD 0xFFFF3024
#define TEEC_ERROR_STORAGE_NO_SPACE 0xFFFF3041
/**
* Session login methods, for use in tee_open_session() as parameter
* connectionMethod. Type is uint32_t.
*
* TEEC_LOGIN_PUBLIC No login data is provided.
* TEEC_LOGIN_USER Login data about the user running the Client
* Application process is provided.
* TEEC_LOGIN_GROUP Login data about the group running the Client
* Application process is provided.
* TEEC_LOGIN_APPLICATION Login data about the running Client Application
* itself is provided.
* TEEC_LOGIN_USER_APPLICATION Login data about the user and the running
* Client Application itself is provided.
* TEEC_LOGIN_GROUP_APPLICATION Login data about the group and the running
* Client Application itself is provided.
*/
#define TEEC_LOGIN_PUBLIC 0x00000000
#define TEEC_LOGIN_USER 0x00000001
#define TEEC_LOGIN_GROUP 0x00000002
#define TEEC_LOGIN_APPLICATION 0x00000004
#define TEEC_LOGIN_USER_APPLICATION 0x00000005
#define TEEC_LOGIN_GROUP_APPLICATION 0x00000006
/**
* @brief TEE version
*
* Identifies the TEE implementation,@ref impl_id is one of TEE_IMPL_ID_* above.
* @ref impl_caps is implementation specific, for example TEE_OPTEE_CAP_*
* is valid when @ref impl_id == TEE_IMPL_ID_OPTEE.
*/
struct tee_version_info {
uint32_t impl_id; /**< [out] TEE implementation id */
uint32_t impl_caps; /**< [out] implementation specific capabilities */
uint32_t gen_caps; /**< Generic capabilities, defined by TEE_GEN_CAPS_* above */
};
/**
* @brief - Open session argument
*/
struct tee_open_session_arg {
uint8_t uuid[TEE_UUID_LEN]; /**< [in] UUID of the Trusted Application */
uint8_t clnt_uuid[TEE_UUID_LEN]; /**< [in] UUID of client */
uint32_t clnt_login; /**< login class of client, TEE_IOCTL_LOGIN_* above */
uint32_t cancel_id; /**< [in] cancellation id, a unique value to identify this request */
uint32_t session; /**< [out] session id */
uint32_t ret; /**< [out] return value */
uint32_t ret_origin; /**< [out] origin of the return value */
};
/**
* @brief Tee parameter
*
* @ref attr & TEE_PARAM_ATTR_TYPE_MASK indicates if memref or value is used in
* the union. TEE_PARAM_ATTR_TYPE_VALUE_* indicates value and
* TEE_PARAM_ATTR_TYPE_MEMREF_* indicates memref. TEE_PARAM_ATTR_TYPE_NONE
* indicates that none of the members are used.
*
* Shared memory is allocated with TEE_IOC_SHM_ALLOC which returns an
* identifier representing the shared memory object. A memref can reference
* a part of a shared memory by specifying an offset (@ref a) and size (@ref b) of
* the object. To supply the entire shared memory object set the offset
* (@ref a) to 0 and size (@ref b) to the previously returned size of the object.
*/
struct tee_param {
uint64_t attr; /**< attributes */
uint64_t a; /**< if a memref, offset into the shared memory object, else a value*/
uint64_t b; /**< if a memref, size of the buffer, else a value parameter */
uint64_t c; /**< if a memref, shared memory identifier, else a value parameter */
};
/**
* @brief Invokes a function in a Trusted Application
*/
struct tee_invoke_func_arg {
uint32_t func; /**< [in] Trusted Application function, specific to the TA */
uint32_t session; /**< [in] session id */
uint32_t cancel_id; /**< [in] cancellation id, a unique value to identify this request */
uint32_t ret; /**< [out] return value */
uint32_t ret_origin; /**< [out] origin of the return value */
};
/**
* @brief Tee shared memory structure
*/
struct tee_shm {
const struct device *dev; /**< [out] pointer to the device driver structure */
void *addr; /**< [out] shared buffer pointer */
uint64_t size; /**< [out] shared buffer size */
uint32_t flags; /**< [out] shared buffer flags */
};
/**
* @typedef tee_get_version_t
*
* @brief Callback API to get current tee version
*
* See @a tee_version_get() for argument definitions.
*/
typedef int (*tee_get_version_t)(const struct device *dev, struct tee_version_info *info);
/**
* @typedef tee_open_session_t
*
* @brief Callback API to open session to Trusted Application
*
* See @a tee_open_session() for argument definitions.
*/
typedef int (*tee_open_session_t)(const struct device *dev, struct tee_open_session_arg *arg,
unsigned int num_param, struct tee_param *param,
uint32_t *session_id);
/**
* @typedef tee_close_session_t
*
* @brief Callback API to close session to TA
*
* See @a tee_close_session() for argument definitions.
*/
typedef int (*tee_close_session_t)(const struct device *dev, uint32_t session_id);
/**
* @typedef tee_cancel_t
*
* @brief Callback API to cancel open session of invoke function to TA
*
* See @a tee_cancel() for argument definitions.
*/
typedef int (*tee_cancel_t)(const struct device *dev, uint32_t session_id, uint32_t cancel_id);
/**
* @typedef tee_invoke_func_t
*
* @brief Callback API to invoke function to TA
*
* See @a tee_invoke_func() for argument definitions.
*/
typedef int (*tee_invoke_func_t)(const struct device *dev, struct tee_invoke_func_arg *arg,
unsigned int num_param, struct tee_param *param);
/**
* @typedef tee_shm_register_t
*
* @brief Callback API to register shared memory
*
* See @a tee_shm_register() for argument definitions.
*/
typedef int (*tee_shm_register_t)(const struct device *dev, struct tee_shm *shm);
/**
* @typedef tee_shm_unregister_t
*
* @brief Callback API to unregister shared memory
*
* See @a tee_shm_unregister() for argument definitions.
*/
typedef int (*tee_shm_unregister_t)(const struct device *dev, struct tee_shm *shm);
/**
* @typedef tee_suppl_recv_t
*
* @brief Callback API to receive a request for TEE supplicant
*
* See @a tee_suppl_recv() for argument definitions.
*/
typedef int (*tee_suppl_recv_t)(const struct device *dev, uint32_t *func, unsigned int *num_params,
struct tee_param *param);
/**
* @typedef tee_suppl_send_t
*
* @brief Callback API to send a request for TEE supplicant
*
* See @a tee_suppl_send() for argument definitions.
*/
typedef int (*tee_suppl_send_t)(const struct device *dev, unsigned int ret, unsigned int num_params,
struct tee_param *param);
__subsystem struct tee_driver_api {
tee_get_version_t get_version;
tee_open_session_t open_session;
tee_close_session_t close_session;
tee_cancel_t cancel;
tee_invoke_func_t invoke_func;
tee_shm_register_t shm_register;
tee_shm_unregister_t shm_unregister;
tee_suppl_recv_t suppl_recv;
tee_suppl_send_t suppl_send;
};
/**
* @brief Get the current TEE version info
*
* Returns info as tee version info which includes capabilities description
*
* @param dev TEE device
* @param info Structure to return the capabilities
*
* @retval -ENOSYS If callback was not implemented
*
* @retval 0 On success, negative on error
*/
__syscall int tee_get_version(const struct device *dev, struct tee_version_info *info);
static inline int z_impl_tee_get_version(const struct device *dev, struct tee_version_info *info)
{
const struct tee_driver_api *api = (const struct tee_driver_api *)dev->api;
if (!api->get_version) {
return -ENOSYS;
}
return api->get_version(dev, info);
}
/**
* @brief Open session for Trusted Environment
*
* Opens the new session to the Trusted Environment
*
* @param dev TEE device
* @param arg Structure with the session arguments
* @param num_param Number of the additional params to be passed
* @param param List of the params to pass to open_session call
* @param session_id Returns id of the created session
*
* @retval -ENOSYS If callback was not implemented
*
* @retval 0 On success, negative on error
*/
__syscall int tee_open_session(const struct device *dev, struct tee_open_session_arg *arg,
unsigned int num_param, struct tee_param *param,
uint32_t *session_id);
static inline int z_impl_tee_open_session(const struct device *dev,
struct tee_open_session_arg *arg,
unsigned int num_param, struct tee_param *param,
uint32_t *session_id)
{
const struct tee_driver_api *api = (const struct tee_driver_api *)dev->api;
if (!api->open_session) {
return -ENOSYS;
}
return api->open_session(dev, arg, num_param, param, session_id);
}
/**
* @brief Close session for Trusted Environment
*
* Closes session to the Trusted Environment
*
* @param dev TEE device
* @param session_id session to close
*
* @retval -ENOSYS If callback was not implemented
*
* @retval 0 On success, negative on error
*/
__syscall int tee_close_session(const struct device *dev, uint32_t session_id);
static inline int z_impl_tee_close_session(const struct device *dev, uint32_t session_id)
{
const struct tee_driver_api *api = (const struct tee_driver_api *)dev->api;
if (!api->close_session) {
return -ENOSYS;
}
return api->close_session(dev, session_id);
}
/**
* @brief Cancel session or invoke function for Trusted Environment
*
* Cancels session or invoke function for TA
*
* @param dev TEE device
* @param session_id session to close
* @param cancel_id cancel reason
*
* @retval -ENOSYS If callback was not implemented
*
* @retval 0 On success, negative on error
*/
__syscall int tee_cancel(const struct device *dev, uint32_t session_id, uint32_t cancel_id);
static inline int z_impl_tee_cancel(const struct device *dev, uint32_t session_id,
uint32_t cancel_id)
{
const struct tee_driver_api *api = (const struct tee_driver_api *)dev->api;
if (!api->cancel) {
return -ENOSYS;
}
return api->cancel(dev, session_id, cancel_id);
}
/**
* @brief Invoke function for Trusted Environment Application
*
* Invokes function to the TA
*
* @param dev TEE device
* @param arg Structure with the invoke function arguments
* @param num_param Number of the additional params to be passed
* @param param List of the params to pass to open_session call
*
* @retval -ENOSYS If callback was not implemented
*
* @retval 0 On success, negative on error
*/
__syscall int tee_invoke_func(const struct device *dev, struct tee_invoke_func_arg *arg,
unsigned int num_param, struct tee_param *param);
static inline int z_impl_tee_invoke_func(const struct device *dev, struct tee_invoke_func_arg *arg,
unsigned int num_param, struct tee_param *param)
{
const struct tee_driver_api *api = (const struct tee_driver_api *)dev->api;
if (!api->invoke_func) {
return -ENOSYS;
}
return api->invoke_func(dev, arg, num_param, param);
}
/**
* @brief Helper function to allocate and register shared memory
*
* Allocates and registers shared memory for TEE
*
* @param dev TEE device
* @param addr Address of the shared memory
* @param align Region alignment
* @param size Size of the shared memory region
* @param flags Flags to set registering parameters
* @param shmp Return shared memory structure
*
* @retval 0 On success, negative on error
*/
int tee_add_shm(const struct device *dev, void *addr, size_t align, size_t size, uint32_t flags,
struct tee_shm **shmp);
/**
* @brief Helper function to remove and unregister shared memory
*
* Removes and unregisters shared memory for TEE
*
* @param dev TEE device
* @param shm Pointer to tee_shm structure
*
* @retval 0 On success, negative on error
*/
int tee_rm_shm(const struct device *dev, struct tee_shm *shm);
/**
* @brief Register shared memory for Trusted Environment
*
* Registers shared memory for TEE
*
* @param dev TEE device
* @param addr Address of the shared memory
* @param size Size of the shared memory region
* @param flags Flags to set registering parameters
* @param shm Return shared memory structure
*
* @retval -ENOSYS If callback was not implemented
*
* @retval 0 On success, negative on error
*/
__syscall int tee_shm_register(const struct device *dev, void *addr, size_t size,
uint32_t flags, struct tee_shm **shm);
static inline int z_impl_tee_shm_register(const struct device *dev, void *addr, size_t size,
uint32_t flags, struct tee_shm **shm)
{
flags &= ~TEE_SHM_ALLOC;
return tee_add_shm(dev, addr, 0, size, flags | TEE_SHM_REGISTER, shm);
}
/**
* @brief Unregister shared memory for Trusted Environment
*
* Unregisters shared memory for TEE
*
* @param dev TEE device
* @param shm Shared memory structure
*
* @retval -ENOSYS If callback was not implemented
*
* @retval 0 On success, negative on error
*/
__syscall int tee_shm_unregister(const struct device *dev, struct tee_shm *shm);
static inline int z_impl_tee_shm_unregister(const struct device *dev, struct tee_shm *shm)
{
return tee_rm_shm(dev, shm);
}
/**
* @brief Allocate shared memory region for Trusted Environment
*
* Allocate shared memory for TEE
*
* @param dev TEE device
* @param size Region size
* @param flags to allocate region
* @param shm Return shared memory structure
*
* @retval -ENOSYS If callback was not implemented
*
* @retval 0 On success, negative on error
*/
__syscall int tee_shm_alloc(const struct device *dev, size_t size, uint32_t flags,
struct tee_shm **shm);
static inline int z_impl_tee_shm_alloc(const struct device *dev, size_t size, uint32_t flags,
struct tee_shm **shm)
{
return tee_add_shm(dev, NULL, 0, size, flags | TEE_SHM_ALLOC | TEE_SHM_REGISTER, shm);
}
/**
* @brief Free shared memory region for Trusted Environment
*
* Frees shared memory for TEE
*
* @param dev TEE device
* @param shm Shared memory structure
*
* @retval -ENOSYS If callback was not implemented
*
* @retval 0 On success, negative on error
*/
__syscall int tee_shm_free(const struct device *dev, struct tee_shm *shm);
static inline int z_impl_tee_shm_free(const struct device *dev, struct tee_shm *shm)
{
return tee_rm_shm(dev, shm);
}
/**
* @brief Receive a request for TEE Supplicant
*
* @param dev TEE device
* @param func Supplicant function
* @param num_params Number of parameters to be passed
* @param param List of the params for send/receive
*
* @retval -ENOSYS If callback was not implemented
*
* @retval 0 On success, negative on error
*/
__syscall int tee_suppl_recv(const struct device *dev, uint32_t *func, unsigned int *num_params,
struct tee_param *param);
static inline int z_impl_tee_suppl_recv(const struct device *dev, uint32_t *func,
unsigned int *num_params, struct tee_param *param)
{
const struct tee_driver_api *api = (const struct tee_driver_api *)dev->api;
if (!api->suppl_recv) {
return -ENOSYS;
}
return api->suppl_recv(dev, func, num_params, param);
}
/**
* @brief Send a request for TEE Supplicant function
*
* @param dev TEE device
* @param ret supplicant return code
* @param num_params Number of parameters to be passed
* @param param List of the params for send/receive
*
* @retval -ENOSYS If callback was not implemented
* @retval Return value for sent request
*
* @retval 0 On success, negative on error
*/
__syscall int tee_suppl_send(const struct device *dev, unsigned int ret, unsigned int num_params,
struct tee_param *param);
static inline int z_impl_tee_suppl_send(const struct device *dev, unsigned int ret,
unsigned int num_params, struct tee_param *param)
{
const struct tee_driver_api *api = (const struct tee_driver_api *)dev->api;
if (!api->suppl_send) {
return -ENOSYS;
}
return api->suppl_send(dev, ret, num_params, param);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/tee.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_TEE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/tee.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 5,471 |
```objective-c
/**
* @file
*
* @brief Public APIs for the I2C drivers.
*/
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_I2C_H_
#define ZEPHYR_INCLUDE_DRIVERS_I2C_H_
/**
* @brief I2C Interface
* @defgroup i2c_interface I2C Interface
* @since 1.0
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <zephyr/device.h>
#include <zephyr/kernel.h>
#include <zephyr/sys/slist.h>
#include <zephyr/rtio/rtio.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* The following #defines are used to configure the I2C controller.
*/
/** I2C Standard Speed: 100 kHz */
#define I2C_SPEED_STANDARD (0x1U)
/** I2C Fast Speed: 400 kHz */
#define I2C_SPEED_FAST (0x2U)
/** I2C Fast Plus Speed: 1 MHz */
#define I2C_SPEED_FAST_PLUS (0x3U)
/** I2C High Speed: 3.4 MHz */
#define I2C_SPEED_HIGH (0x4U)
/** I2C Ultra Fast Speed: 5 MHz */
#define I2C_SPEED_ULTRA (0x5U)
/** Device Tree specified speed */
#define I2C_SPEED_DT (0x7U)
#define I2C_SPEED_SHIFT (1U)
#define I2C_SPEED_SET(speed) (((speed) << I2C_SPEED_SHIFT) \
& I2C_SPEED_MASK)
#define I2C_SPEED_MASK (0x7U << I2C_SPEED_SHIFT) /* 3 bits */
#define I2C_SPEED_GET(cfg) (((cfg) & I2C_SPEED_MASK) \
>> I2C_SPEED_SHIFT)
/** Use 10-bit addressing. DEPRECATED - Use I2C_MSG_ADDR_10_BITS instead. */
#define I2C_ADDR_10_BITS BIT(0)
/** Peripheral to act as Controller. */
#define I2C_MODE_CONTROLLER BIT(4)
/**
* @brief Complete I2C DT information
*
* @param bus is the I2C bus
* @param addr is the target address
*/
struct i2c_dt_spec {
const struct device *bus;
uint16_t addr;
};
/**
* @brief Structure initializer for i2c_dt_spec from devicetree (on I3C bus)
*
* This helper macro expands to a static initializer for a <tt>struct
* i2c_dt_spec</tt> by reading the relevant bus and address data from
* the devicetree.
*
* @param node_id Devicetree node identifier for the I2C device whose
* struct i2c_dt_spec to create an initializer for
*/
#define I2C_DT_SPEC_GET_ON_I3C(node_id) \
.bus = DEVICE_DT_GET(DT_BUS(node_id)), \
.addr = DT_PROP_BY_IDX(node_id, reg, 0)
/**
* @brief Structure initializer for i2c_dt_spec from devicetree (on I2C bus)
*
* This helper macro expands to a static initializer for a <tt>struct
* i2c_dt_spec</tt> by reading the relevant bus and address data from
* the devicetree.
*
* @param node_id Devicetree node identifier for the I2C device whose
* struct i2c_dt_spec to create an initializer for
*/
#define I2C_DT_SPEC_GET_ON_I2C(node_id) \
.bus = DEVICE_DT_GET(DT_BUS(node_id)), \
.addr = DT_REG_ADDR(node_id)
/**
* @brief Structure initializer for i2c_dt_spec from devicetree
*
* This helper macro expands to a static initializer for a <tt>struct
* i2c_dt_spec</tt> by reading the relevant bus and address data from
* the devicetree.
*
* @param node_id Devicetree node identifier for the I2C device whose
* struct i2c_dt_spec to create an initializer for
*/
#define I2C_DT_SPEC_GET(node_id) \
{ \
COND_CODE_1(DT_ON_BUS(node_id, i3c), \
(I2C_DT_SPEC_GET_ON_I3C(node_id)), \
(I2C_DT_SPEC_GET_ON_I2C(node_id))) \
}
/**
* @brief Structure initializer for i2c_dt_spec from devicetree instance
*
* This is equivalent to
* <tt>I2C_DT_SPEC_GET(DT_DRV_INST(inst))</tt>.
*
* @param inst Devicetree instance number
*/
#define I2C_DT_SPEC_INST_GET(inst) \
I2C_DT_SPEC_GET(DT_DRV_INST(inst))
/*
* I2C_MSG_* are I2C Message flags.
*/
/** Write message to I2C bus. */
#define I2C_MSG_WRITE (0U << 0U)
/** Read message from I2C bus. */
#define I2C_MSG_READ BIT(0)
/** @cond INTERNAL_HIDDEN */
#define I2C_MSG_RW_MASK BIT(0)
/** @endcond */
/** Send STOP after this message. */
#define I2C_MSG_STOP BIT(1)
/** RESTART I2C transaction for this message.
*
* @note Not all I2C drivers have or require explicit support for this
* feature. Some drivers require this be present on a read message
* that follows a write, or vice-versa. Some drivers will merge
* adjacent fragments into a single transaction using this flag; some
* will not. */
#define I2C_MSG_RESTART BIT(2)
/** Use 10-bit addressing for this message.
*
* @note Not all SoC I2C implementations support this feature. */
#define I2C_MSG_ADDR_10_BITS BIT(3)
/**
* @brief One I2C Message.
*
* This defines one I2C message to transact on the I2C bus.
*
* @note Some of the configurations supported by this API may not be
* supported by specific SoC I2C hardware implementations, in
* particular features related to bus transactions intended to read or
* write data from different buffers within a single transaction.
* Invocations of i2c_transfer() may not indicate an error when an
* unsupported configuration is encountered. In some cases drivers
* will generate separate transactions for each message fragment, with
* or without presence of @ref I2C_MSG_RESTART in #flags.
*/
struct i2c_msg {
/** Data buffer in bytes */
uint8_t *buf;
/** Length of buffer in bytes */
uint32_t len;
/** Flags for this message */
uint8_t flags;
};
/**
* @brief I2C callback for asynchronous transfer requests
*
* @param dev I2C device which is notifying of transfer completion or error
* @param result Result code of the transfer request. 0 is success, -errno for failure.
* @param data Transfer requester supplied data which is passed along to the callback.
*/
typedef void (*i2c_callback_t)(const struct device *dev, int result, void *data);
/**
* @cond INTERNAL_HIDDEN
*
* These are for internal use only, so skip these in
* public documentation.
*/
struct i2c_target_config;
typedef int (*i2c_api_configure_t)(const struct device *dev,
uint32_t dev_config);
typedef int (*i2c_api_get_config_t)(const struct device *dev,
uint32_t *dev_config);
typedef int (*i2c_api_full_io_t)(const struct device *dev,
struct i2c_msg *msgs,
uint8_t num_msgs,
uint16_t addr);
typedef int (*i2c_api_target_register_t)(const struct device *dev,
struct i2c_target_config *cfg);
typedef int (*i2c_api_target_unregister_t)(const struct device *dev,
struct i2c_target_config *cfg);
#ifdef CONFIG_I2C_CALLBACK
typedef int (*i2c_api_transfer_cb_t)(const struct device *dev,
struct i2c_msg *msgs,
uint8_t num_msgs,
uint16_t addr,
i2c_callback_t cb,
void *userdata);
#endif /* CONFIG_I2C_CALLBACK */
#if defined(CONFIG_I2C_RTIO) || defined(__DOXYGEN__)
/**
* @typedef i2c_api_iodev_submit
* @brief Callback API for submitting work to a I2C device with RTIO
*/
typedef void (*i2c_api_iodev_submit)(const struct device *dev,
struct rtio_iodev_sqe *iodev_sqe);
#endif /* CONFIG_I2C_RTIO */
typedef int (*i2c_api_recover_bus_t)(const struct device *dev);
__subsystem struct i2c_driver_api {
i2c_api_configure_t configure;
i2c_api_get_config_t get_config;
i2c_api_full_io_t transfer;
i2c_api_target_register_t target_register;
i2c_api_target_unregister_t target_unregister;
#ifdef CONFIG_I2C_CALLBACK
i2c_api_transfer_cb_t transfer_cb;
#endif
#ifdef CONFIG_I2C_RTIO
i2c_api_iodev_submit iodev_submit;
#endif
i2c_api_recover_bus_t recover_bus;
};
typedef int (*i2c_target_api_register_t)(const struct device *dev);
typedef int (*i2c_target_api_unregister_t)(const struct device *dev);
__subsystem struct i2c_target_driver_api {
i2c_target_api_register_t driver_register;
i2c_target_api_unregister_t driver_unregister;
};
/**
* @endcond
*/
/** Target device responds to 10-bit addressing. */
#define I2C_TARGET_FLAGS_ADDR_10_BITS BIT(0)
/** @brief Function called when a write to the device is initiated.
*
* This function is invoked by the controller when the bus completes a
* start condition for a write operation to the address associated
* with a particular device.
*
* A success return shall cause the controller to ACK the next byte
* received. An error return shall cause the controller to NACK the
* next byte received.
*
* @param config the configuration structure associated with the
* device to which the operation is addressed.
*
* @return 0 if the write is accepted, or a negative error code.
*/
typedef int (*i2c_target_write_requested_cb_t)(
struct i2c_target_config *config);
/** @brief Function called when a write to the device is continued.
*
* This function is invoked by the controller when it completes
* reception of a byte of data in an ongoing write operation to the
* device.
*
* A success return shall cause the controller to ACK the next byte
* received. An error return shall cause the controller to NACK the
* next byte received.
*
* @param config the configuration structure associated with the
* device to which the operation is addressed.
*
* @param val the byte received by the controller.
*
* @return 0 if more data can be accepted, or a negative error
* code.
*/
typedef int (*i2c_target_write_received_cb_t)(
struct i2c_target_config *config, uint8_t val);
/** @brief Function called when a read from the device is initiated.
*
* This function is invoked by the controller when the bus completes a
* start condition for a read operation from the address associated
* with a particular device.
*
* The value returned in @p *val will be transmitted. A success
* return shall cause the controller to react to additional read
* operations. An error return shall cause the controller to ignore
* bus operations until a new start condition is received.
*
* @param config the configuration structure associated with the
* device to which the operation is addressed.
*
* @param val pointer to storage for the first byte of data to return
* for the read request.
*
* @return 0 if more data can be requested, or a negative error code.
*/
typedef int (*i2c_target_read_requested_cb_t)(
struct i2c_target_config *config, uint8_t *val);
/** @brief Function called when a read from the device is continued.
*
* This function is invoked by the controller when the bus is ready to
* provide additional data for a read operation from the address
* associated with the device device.
*
* The value returned in @p *val will be transmitted. A success
* return shall cause the controller to react to additional read
* operations. An error return shall cause the controller to ignore
* bus operations until a new start condition is received.
*
* @param config the configuration structure associated with the
* device to which the operation is addressed.
*
* @param val pointer to storage for the next byte of data to return
* for the read request.
*
* @return 0 if data has been provided, or a negative error code.
*/
typedef int (*i2c_target_read_processed_cb_t)(
struct i2c_target_config *config, uint8_t *val);
#ifdef CONFIG_I2C_TARGET_BUFFER_MODE
/** @brief Function called when a write to the device is completed.
*
* This function is invoked by the controller when it completes
* reception of data from the source buffer to the destination
* buffer in an ongoing write operation to the device.
*
* @param config the configuration structure associated with the
* device to which the operation is addressed.
*
* @param ptr pointer to the buffer that contains the data to be transferred.
*
* @param len the length of the data to be transferred.
*/
typedef void (*i2c_target_buf_write_received_cb_t)(
struct i2c_target_config *config, uint8_t *ptr, uint32_t len);
/** @brief Function called when a read from the device is initiated.
*
* This function is invoked by the controller when the bus is ready to
* provide additional data by buffer for a read operation from the address
* associated with the device.
*
* The value returned in @p **ptr and @p *len will be transmitted. A success
* return shall cause the controller to react to additional read operations.
* An error return shall cause the controller to ignore bus operations until
* a new start condition is received.
*
* @param config the configuration structure associated with the
* device to which the operation is addressed.
*
* @param ptr pointer to storage for the address of data buffer to return
* for the read request.
*
* @param len pointer to storage for the length of the data to be transferred
* for the read request.
*
* @return 0 if data has been provided, or a negative error code.
*/
typedef int (*i2c_target_buf_read_requested_cb_t)(
struct i2c_target_config *config, uint8_t **ptr, uint32_t *len);
#endif
/** @brief Function called when a stop condition is observed after a
* start condition addressed to a particular device.
*
* This function is invoked by the controller when the bus is ready to
* provide additional data for a read operation from the address
* associated with the device device. After the function returns the
* controller shall enter a state where it is ready to react to new
* start conditions.
*
* @param config the configuration structure associated with the
* device to which the operation is addressed.
*
* @return Ignored.
*/
typedef int (*i2c_target_stop_cb_t)(struct i2c_target_config *config);
/** @brief Structure providing callbacks to be implemented for devices
* that supports the I2C target API.
*
* This structure may be shared by multiple devices that implement the
* same API at different addresses on the bus.
*/
struct i2c_target_callbacks {
i2c_target_write_requested_cb_t write_requested;
i2c_target_read_requested_cb_t read_requested;
i2c_target_write_received_cb_t write_received;
i2c_target_read_processed_cb_t read_processed;
#ifdef CONFIG_I2C_TARGET_BUFFER_MODE
i2c_target_buf_write_received_cb_t buf_write_received;
i2c_target_buf_read_requested_cb_t buf_read_requested;
#endif
i2c_target_stop_cb_t stop;
};
/** @brief Structure describing a device that supports the I2C
* target API.
*
* Instances of this are passed to the i2c_target_register() and
* i2c_target_unregister() functions to indicate addition and removal
* of a target device, respective.
*
* Fields other than @c node must be initialized by the module that
* implements the device behavior prior to passing the object
* reference to i2c_target_register().
*/
struct i2c_target_config {
/** Private, do not modify */
sys_snode_t node;
/** Flags for the target device defined by I2C_TARGET_FLAGS_* constants */
uint8_t flags;
/** Address for this target device */
uint16_t address;
/** Callback functions */
const struct i2c_target_callbacks *callbacks;
};
/**
* @brief Validate that I2C bus is ready.
*
* @param spec I2C specification from devicetree
*
* @retval true if the I2C bus is ready for use.
* @retval false if the I2C bus is not ready for use.
*/
static inline bool i2c_is_ready_dt(const struct i2c_dt_spec *spec)
{
/* Validate bus is ready */
return device_is_ready(spec->bus);
}
/**
* @brief Check if the current message is a read operation
*
* @param msg The message to check
* @return true if the I2C message is a read operation
* @return false if the I2C message is a write operation
*/
static inline bool i2c_is_read_op(const struct i2c_msg *msg)
{
return (msg->flags & I2C_MSG_READ) == I2C_MSG_READ;
}
/**
* @brief Check if the current message includes a stop.
*
* @param msg The message to check
* @return true if the I2C message includes a stop
* @return false if the I2C message includes a stop
*/
static inline bool i2c_is_stop_op(const struct i2c_msg *msg)
{
return (msg->flags & I2C_MSG_STOP) == I2C_MSG_STOP;
}
/**
* @brief Dump out an I2C message
*
* Dumps out a list of I2C messages. For any that are writes (W), the data is
* displayed in hex. Setting dump_read will dump the data for read messages too,
* which only makes sense when called after the messages have been processed.
*
* It looks something like this (with name "testing"):
*
* @code
* D: I2C msg: testing, addr=56
* D: W len=01: 06
* D: W len=0e:
* D: contents:
* D: 00 01 02 03 04 05 06 07 |........
* D: 08 09 0a 0b 0c 0d |......
* D: W len=01: 0f
* D: R len=01: 6c
* @endcode
*
* @param dev Target for the messages being sent. Its name will be printed in the log.
* @param msgs Array of messages to dump.
* @param num_msgs Number of messages to dump.
* @param addr Address of the I2C target device.
* @param dump_read Dump data from I2C reads, otherwise only writes have data dumped.
*/
void i2c_dump_msgs_rw(const struct device *dev, const struct i2c_msg *msgs, uint8_t num_msgs,
uint16_t addr, bool dump_read);
/**
* @brief Dump out an I2C message, before it is executed.
*
* This is equivalent to:
*
* i2c_dump_msgs_rw(dev, msgs, num_msgs, addr, false);
*
* The read messages' data isn't dumped.
*
* @param dev Target for the messages being sent. Its name will be printed in the log.
* @param msgs Array of messages to dump.
* @param num_msgs Number of messages to dump.
* @param addr Address of the I2C target device.
*/
static inline void i2c_dump_msgs(const struct device *dev, const struct i2c_msg *msgs,
uint8_t num_msgs, uint16_t addr)
{
i2c_dump_msgs_rw(dev, msgs, num_msgs, addr, false);
}
#if defined(CONFIG_I2C_STATS) || defined(__DOXYGEN__)
#include <zephyr/stats/stats.h>
/** @cond INTERNAL_HIDDEN */
STATS_SECT_START(i2c)
STATS_SECT_ENTRY32(bytes_read)
STATS_SECT_ENTRY32(bytes_written)
STATS_SECT_ENTRY32(message_count)
STATS_SECT_ENTRY32(transfer_call_count)
STATS_SECT_END;
STATS_NAME_START(i2c)
STATS_NAME(i2c, bytes_read)
STATS_NAME(i2c, bytes_written)
STATS_NAME(i2c, message_count)
STATS_NAME(i2c, transfer_call_count)
STATS_NAME_END(i2c);
/** @endcond */
/**
* @brief I2C specific device state which allows for i2c device class specific additions
*/
struct i2c_device_state {
struct device_state devstate;
struct stats_i2c stats;
};
/**
* @brief Updates the i2c stats for i2c transfers
*
* @param dev I2C device to update stats for
* @param msgs Array of struct i2c_msg
* @param num_msgs Number of i2c_msgs
*/
static inline void i2c_xfer_stats(const struct device *dev, struct i2c_msg *msgs,
uint8_t num_msgs)
{
struct i2c_device_state *state =
CONTAINER_OF(dev->state, struct i2c_device_state, devstate);
uint32_t bytes_read = 0U;
uint32_t bytes_written = 0U;
STATS_INC(state->stats, transfer_call_count);
STATS_INCN(state->stats, message_count, num_msgs);
for (uint8_t i = 0U; i < num_msgs; i++) {
if (msgs[i].flags & I2C_MSG_READ) {
bytes_read += msgs[i].len;
} else {
bytes_written += msgs[i].len;
}
}
STATS_INCN(state->stats, bytes_read, bytes_read);
STATS_INCN(state->stats, bytes_written, bytes_written);
}
/** @cond INTERNAL_HIDDEN */
/**
* @brief Define a statically allocated and section assigned i2c device state
*/
#define Z_I2C_DEVICE_STATE_DEFINE(dev_id) \
static struct i2c_device_state Z_DEVICE_STATE_NAME(dev_id) \
__attribute__((__section__(".z_devstate")))
/**
* @brief Define an i2c device init wrapper function
*
* This does device instance specific initialization of common data (such as stats)
* and calls the given init_fn
*/
#define Z_I2C_INIT_FN(dev_id, init_fn) \
static inline int UTIL_CAT(dev_id, _init)(const struct device *dev) \
{ \
struct i2c_device_state *state = \
CONTAINER_OF(dev->state, struct i2c_device_state, devstate); \
stats_init(&state->stats.s_hdr, STATS_SIZE_32, 4, \
STATS_NAME_INIT_PARMS(i2c)); \
stats_register(dev->name, &(state->stats.s_hdr)); \
if (!is_null_no_warn(init_fn)) { \
return init_fn(dev); \
} \
\
return 0; \
}
/** @endcond */
/**
* @brief Like DEVICE_DT_DEFINE() with I2C specifics.
*
* @details Defines a device which implements the I2C API. May
* generate a custom device_state container struct and init_fn
* wrapper when needed depending on I2C @kconfig{CONFIG_I2C_STATS}.
*
* @param node_id The devicetree node identifier.
*
* @param init_fn Name of the init function of the driver. Can be `NULL`.
*
* @param pm PM device resources reference (NULL if device does not use PM).
*
* @param data Pointer to the device's private data.
*
* @param config The address to the structure containing the
* configuration information for this instance of the driver.
*
* @param level The initialization level. See SYS_INIT() for
* details.
*
* @param prio Priority within the selected initialization level. See
* SYS_INIT() for details.
*
* @param api Provides an initial pointer to the API function struct
* used by the driver. Can be NULL.
*/
#define I2C_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
prio, api, ...) \
Z_I2C_DEVICE_STATE_DEFINE(Z_DEVICE_DT_DEV_ID(node_id)); \
Z_I2C_INIT_FN(Z_DEVICE_DT_DEV_ID(node_id), init_fn) \
Z_DEVICE_DEFINE(node_id, Z_DEVICE_DT_DEV_ID(node_id), \
DEVICE_DT_NAME(node_id), \
&UTIL_CAT(Z_DEVICE_DT_DEV_ID(node_id), _init), \
pm, data, config, level, prio, api, \
&(Z_DEVICE_STATE_NAME(Z_DEVICE_DT_DEV_ID(node_id)).devstate), \
__VA_ARGS__)
#else /* CONFIG_I2C_STATS */
static inline void i2c_xfer_stats(const struct device *dev, struct i2c_msg *msgs,
uint8_t num_msgs)
{
ARG_UNUSED(dev);
ARG_UNUSED(msgs);
ARG_UNUSED(num_msgs);
}
#define I2C_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
prio, api, ...) \
DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
prio, api, __VA_ARGS__)
#endif /* CONFIG_I2C_STATS */
/**
* @brief Like I2C_DEVICE_DT_DEFINE() for an instance of a DT_DRV_COMPAT compatible
*
* @param inst instance number. This is replaced by
* <tt>DT_DRV_COMPAT(inst)</tt> in the call to I2C_DEVICE_DT_DEFINE().
*
* @param ... other parameters as expected by I2C_DEVICE_DT_DEFINE().
*/
#define I2C_DEVICE_DT_INST_DEFINE(inst, ...) \
I2C_DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
/**
* @brief Configure operation of a host controller.
*
* @param dev Pointer to the device structure for the driver instance.
* @param dev_config Bit-packed 32-bit value to the device runtime configuration
* for the I2C controller.
*
* @retval 0 If successful.
* @retval -EIO General input / output error, failed to configure device.
*/
__syscall int i2c_configure(const struct device *dev, uint32_t dev_config);
static inline int z_impl_i2c_configure(const struct device *dev,
uint32_t dev_config)
{
const struct i2c_driver_api *api =
(const struct i2c_driver_api *)dev->api;
return api->configure(dev, dev_config);
}
/**
* @brief Get configuration of a host controller.
*
* This routine provides a way to get current configuration. It is allowed to
* call the function before i2c_configure, because some I2C ports can be
* configured during init process. However, if the I2C port is not configured,
* i2c_get_config returns an error.
*
* i2c_get_config can return cached config or probe hardware, but it has to be
* up to date with current configuration.
*
* @param dev Pointer to the device structure for the driver instance.
* @param dev_config Pointer to return bit-packed 32-bit value of
* the I2C controller configuration.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ERANGE Configured I2C frequency is invalid.
* @retval -ENOSYS If get config is not implemented
*/
__syscall int i2c_get_config(const struct device *dev, uint32_t *dev_config);
static inline int z_impl_i2c_get_config(const struct device *dev, uint32_t *dev_config)
{
const struct i2c_driver_api *api = (const struct i2c_driver_api *)dev->api;
if (api->get_config == NULL) {
return -ENOSYS;
}
return api->get_config(dev, dev_config);
}
/**
* @brief Perform data transfer to another I2C device in controller mode.
*
* This routine provides a generic interface to perform data transfer
* to another I2C device synchronously. Use i2c_read()/i2c_write()
* for simple read or write.
*
* The array of message @a msgs must not be NULL. The number of
* message @a num_msgs may be zero,in which case no transfer occurs.
*
* @note Not all scatter/gather transactions can be supported by all
* drivers. As an example, a gather write (multiple consecutive
* `i2c_msg` buffers all configured for `I2C_MSG_WRITE`) may be packed
* into a single transaction by some drivers, but others may emit each
* fragment as a distinct write transaction, which will not produce
* the same behavior. See the documentation of `struct i2c_msg` for
* limitations on support for multi-message bus transactions.
*
* @note The last message in the scatter/gather transaction implies a STOP
* whether or not it is explicitly set. This ensures the bus is in a good
* state for the next transaction which may be from a different call context.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param msgs Array of messages to transfer.
* @param num_msgs Number of messages to transfer.
* @param addr Address of the I2C target device.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
__syscall int i2c_transfer(const struct device *dev,
struct i2c_msg *msgs, uint8_t num_msgs,
uint16_t addr);
static inline int z_impl_i2c_transfer(const struct device *dev,
struct i2c_msg *msgs, uint8_t num_msgs,
uint16_t addr)
{
const struct i2c_driver_api *api =
(const struct i2c_driver_api *)dev->api;
if (!num_msgs) {
return 0;
}
msgs[num_msgs - 1].flags |= I2C_MSG_STOP;
int res = api->transfer(dev, msgs, num_msgs, addr);
i2c_xfer_stats(dev, msgs, num_msgs);
if (IS_ENABLED(CONFIG_I2C_DUMP_MESSAGES)) {
i2c_dump_msgs_rw(dev, msgs, num_msgs, addr, true);
}
return res;
}
#if defined(CONFIG_I2C_CALLBACK) || defined(__DOXYGEN__)
/**
* @brief Perform data transfer to another I2C device in controller mode.
*
* This routine provides a generic interface to perform data transfer
* to another I2C device asynchronously with a callback completion.
*
* @see i2c_transfer()
* @funcprops \isr_ok
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param msgs Array of messages to transfer, must live until callback completes.
* @param num_msgs Number of messages to transfer.
* @param addr Address of the I2C target device.
* @param cb Function pointer for completion callback.
* @param userdata Userdata passed to callback.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If transfer async is not implemented
* @retval -EWOULDBLOCK If the device is temporarily busy doing another transfer
*/
static inline int i2c_transfer_cb(const struct device *dev,
struct i2c_msg *msgs,
uint8_t num_msgs,
uint16_t addr,
i2c_callback_t cb,
void *userdata)
{
const struct i2c_driver_api *api =
(const struct i2c_driver_api *)dev->api;
if (api->transfer_cb == NULL) {
return -ENOSYS;
}
if (!num_msgs) {
cb(dev, 0, userdata);
return 0;
}
msgs[num_msgs - 1].flags |= I2C_MSG_STOP;
return api->transfer_cb(dev, msgs, num_msgs, addr, cb, userdata);
}
/**
* @brief Perform data transfer to another I2C device in master mode asynchronously.
*
* This is equivalent to:
*
* i2c_transfer_cb(spec->bus, msgs, num_msgs, spec->addr, cb, userdata);
*
* @param spec I2C specification from devicetree.
* @param msgs Array of messages to transfer.
* @param num_msgs Number of messages to transfer.
* @param cb Function pointer for completion callback.
* @param userdata Userdata passed to callback.
*
* @return a value from i2c_transfer_cb()
*/
static inline int i2c_transfer_cb_dt(const struct i2c_dt_spec *spec,
struct i2c_msg *msgs,
uint8_t num_msgs,
i2c_callback_t cb,
void *userdata)
{
return i2c_transfer_cb(spec->bus, msgs, num_msgs, spec->addr, cb, userdata);
}
/**
* @brief Write then read data from an I2C device asynchronously.
*
* This supports the common operation "this is what I want", "now give
* it to me" transaction pair through a combined write-then-read bus
* transaction but using i2c_transfer_cb. This helper function expects
* caller to pass a message pointer with 2 and only 2 size.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in master mode.
* @param msgs Array of messages to transfer.
* @param num_msgs Number of messages to transfer.
* @param addr Address of the I2C device
* @param write_buf Pointer to the data to be written
* @param num_write Number of bytes to write
* @param read_buf Pointer to storage for read data
* @param num_read Number of bytes to read
* @param cb Function pointer for completion callback.
* @param userdata Userdata passed to callback.
*
* @retval 0 if successful
* @retval negative on error.
*/
static inline int i2c_write_read_cb(const struct device *dev, struct i2c_msg *msgs,
uint8_t num_msgs, uint16_t addr, const void *write_buf,
size_t num_write, void *read_buf, size_t num_read,
i2c_callback_t cb, void *userdata)
{
if ((msgs == NULL) || (num_msgs != 2)) {
return -EINVAL;
}
msgs[0].buf = (uint8_t *)write_buf;
msgs[0].len = num_write;
msgs[0].flags = I2C_MSG_WRITE;
msgs[1].buf = (uint8_t *)read_buf;
msgs[1].len = num_read;
msgs[1].flags = I2C_MSG_RESTART | I2C_MSG_READ | I2C_MSG_STOP;
return i2c_transfer_cb(dev, msgs, num_msgs, addr, cb, userdata);
}
/**
* @brief Write then read data from an I2C device asynchronously.
*
* This is equivalent to:
*
* i2c_write_read_cb(spec->bus, msgs, num_msgs,
* spec->addr, write_buf,
* num_write, read_buf, num_read);
*
* @param spec I2C specification from devicetree.
* @param msgs Array of messages to transfer.
* @param num_msgs Number of messages to transfer.
* @param write_buf Pointer to the data to be written
* @param num_write Number of bytes to write
* @param read_buf Pointer to storage for read data
* @param num_read Number of bytes to read
* @param cb Function pointer for completion callback.
* @param userdata Userdata passed to callback.
*
* @return a value from i2c_write_read_cb()
*/
static inline int i2c_write_read_cb_dt(const struct i2c_dt_spec *spec, struct i2c_msg *msgs,
uint8_t num_msgs, const void *write_buf, size_t num_write,
void *read_buf, size_t num_read, i2c_callback_t cb,
void *userdata)
{
return i2c_write_read_cb(spec->bus, msgs, num_msgs, spec->addr, write_buf, num_write,
read_buf, num_read, cb, userdata);
}
#if defined(CONFIG_POLL) || defined(__DOXYGEN__)
/** @cond INTERNAL_HIDDEN */
void z_i2c_transfer_signal_cb(const struct device *dev, int result, void *userdata);
/** @endcond */
/**
* @brief Perform data transfer to another I2C device in controller mode.
*
* This routine provides a generic interface to perform data transfer
* to another I2C device asynchronously with a k_poll_signal completion.
*
* @see i2c_transfer_cb()
* @funcprops \isr_ok
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param msgs Array of messages to transfer, must live until callback completes.
* @param num_msgs Number of messages to transfer.
* @param addr Address of the I2C target device.
* @param sig Signal to notify of transfer completion.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
* @retval -ENOSYS If transfer async is not implemented
* @retval -EWOULDBLOCK If the device is temporarily busy doing another transfer
*/
static inline int i2c_transfer_signal(const struct device *dev,
struct i2c_msg *msgs,
uint8_t num_msgs,
uint16_t addr,
struct k_poll_signal *sig)
{
const struct i2c_driver_api *api = (const struct i2c_driver_api *)dev->api;
if (api->transfer_cb == NULL) {
return -ENOSYS;
}
return api->transfer_cb(dev, msgs, num_msgs, addr, z_i2c_transfer_signal_cb, sig);
}
#endif /* CONFIG_POLL */
#endif /* CONFIG_I2C_CALLBACK */
#if defined(CONFIG_I2C_RTIO) || defined(__DOXYGEN__)
/**
* @brief Submit request(s) to an I2C device with RTIO
*
* @param iodev_sqe Prepared submissions queue entry connected to an iodev
* defined by I2C_DT_IODEV_DEFINE.
*/
static inline void i2c_iodev_submit(struct rtio_iodev_sqe *iodev_sqe)
{
const struct i2c_dt_spec *dt_spec = (const struct i2c_dt_spec *)iodev_sqe->sqe.iodev->data;
const struct device *dev = dt_spec->bus;
const struct i2c_driver_api *api = (const struct i2c_driver_api *)dev->api;
api->iodev_submit(dt_spec->bus, iodev_sqe);
}
extern const struct rtio_iodev_api i2c_iodev_api;
/**
* @brief Define an iodev for a given dt node on the bus
*
* These do not need to be shared globally but doing so
* will save a small amount of memory.
*
* @param name Symbolic name of the iodev to define
* @param node_id Devicetree node identifier
*/
#define I2C_DT_IODEV_DEFINE(name, node_id) \
const struct i2c_dt_spec _i2c_dt_spec_##name = \
I2C_DT_SPEC_GET(node_id); \
RTIO_IODEV_DEFINE(name, &i2c_iodev_api, (void *)&_i2c_dt_spec_##name)
/**
* @brief Define an iodev for a given i2c device on a bus
*
* These do not need to be shared globally but doing so
* will save a small amount of memory.
*
* @param name Symbolic name of the iodev to define
* @param _bus Node ID for I2C bus
* @param _addr I2C target address
*/
#define I2C_IODEV_DEFINE(name, _bus, _addr) \
const struct i2c_dt_spec _i2c_dt_spec_##name = { \
.bus = DEVICE_DT_GET(_bus), \
.addr = _addr, \
}; \
RTIO_IODEV_DEFINE(name, &i2c_iodev_api, (void *)&_i2c_dt_spec_##name)
/**
* @brief Copy the i2c_msgs into a set of RTIO requests
*
* @param r RTIO context
* @param iodev RTIO IODev to target for the submissions
* @param msgs Array of messages
* @param num_msgs Number of i2c msgs in array
*
* @retval sqe Last submission in the queue added
* @retval NULL Not enough memory in the context to copy the requests
*/
struct rtio_sqe *i2c_rtio_copy(struct rtio *r,
struct rtio_iodev *iodev,
const struct i2c_msg *msgs,
uint8_t num_msgs);
#endif /* CONFIG_I2C_RTIO */
/**
* @brief Perform data transfer to another I2C device in controller mode.
*
* This is equivalent to:
*
* i2c_transfer(spec->bus, msgs, num_msgs, spec->addr);
*
* @param spec I2C specification from devicetree.
* @param msgs Array of messages to transfer.
* @param num_msgs Number of messages to transfer.
*
* @return a value from i2c_transfer()
*/
static inline int i2c_transfer_dt(const struct i2c_dt_spec *spec,
struct i2c_msg *msgs, uint8_t num_msgs)
{
return i2c_transfer(spec->bus, msgs, num_msgs, spec->addr);
}
/**
* @brief Recover the I2C bus
*
* Attempt to recover the I2C bus.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @retval 0 If successful
* @retval -EBUSY If bus is not clear after recovery attempt.
* @retval -EIO General input / output error.
* @retval -ENOSYS If bus recovery is not implemented
*/
__syscall int i2c_recover_bus(const struct device *dev);
static inline int z_impl_i2c_recover_bus(const struct device *dev)
{
const struct i2c_driver_api *api =
(const struct i2c_driver_api *)dev->api;
if (api->recover_bus == NULL) {
return -ENOSYS;
}
return api->recover_bus(dev);
}
/**
* @brief Registers the provided config as Target device of a controller.
*
* Enable I2C target mode for the 'dev' I2C bus driver using the provided
* 'config' struct containing the functions and parameters to send bus
* events. The I2C target will be registered at the address provided as 'address'
* struct member. Addressing mode - 7 or 10 bit - depends on the 'flags'
* struct member. Any I2C bus events related to the target mode will be passed
* onto I2C target device driver via a set of callback functions provided in
* the 'callbacks' struct member.
*
* Most of the existing hardware allows simultaneous support for controller
* and target mode. This is however not guaranteed.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in target mode.
* @param cfg Config struct with functions and parameters used by the I2C driver
* to send bus events
*
* @retval 0 Is successful
* @retval -EINVAL If parameters are invalid
* @retval -EIO General input / output error.
* @retval -ENOSYS If target mode is not implemented
*/
static inline int i2c_target_register(const struct device *dev,
struct i2c_target_config *cfg)
{
const struct i2c_driver_api *api =
(const struct i2c_driver_api *)dev->api;
if (api->target_register == NULL) {
return -ENOSYS;
}
return api->target_register(dev, cfg);
}
/**
* @brief Unregisters the provided config as Target device
*
* This routine disables I2C target mode for the 'dev' I2C bus driver using
* the provided 'config' struct containing the functions and parameters
* to send bus events.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in target mode.
* @param cfg Config struct with functions and parameters used by the I2C driver
* to send bus events
*
* @retval 0 Is successful
* @retval -EINVAL If parameters are invalid
* @retval -ENOSYS If target mode is not implemented
*/
static inline int i2c_target_unregister(const struct device *dev,
struct i2c_target_config *cfg)
{
const struct i2c_driver_api *api =
(const struct i2c_driver_api *)dev->api;
if (api->target_unregister == NULL) {
return -ENOSYS;
}
return api->target_unregister(dev, cfg);
}
/**
* @brief Instructs the I2C Target device to register itself to the I2C Controller
*
* This routine instructs the I2C Target device to register itself to the I2C
* Controller via its parent controller's i2c_target_register() API.
*
* @param dev Pointer to the device structure for the I2C target
* device (not itself an I2C controller).
*
* @retval 0 Is successful
* @retval -EINVAL If parameters are invalid
* @retval -EIO General input / output error.
*/
__syscall int i2c_target_driver_register(const struct device *dev);
static inline int z_impl_i2c_target_driver_register(const struct device *dev)
{
const struct i2c_target_driver_api *api =
(const struct i2c_target_driver_api *)dev->api;
return api->driver_register(dev);
}
/**
* @brief Instructs the I2C Target device to unregister itself from the I2C
* Controller
*
* This routine instructs the I2C Target device to unregister itself from the I2C
* Controller via its parent controller's i2c_target_register() API.
*
* @param dev Pointer to the device structure for the I2C target
* device (not itself an I2C controller).
*
* @retval 0 Is successful
* @retval -EINVAL If parameters are invalid
*/
__syscall int i2c_target_driver_unregister(const struct device *dev);
static inline int z_impl_i2c_target_driver_unregister(const struct device *dev)
{
const struct i2c_target_driver_api *api =
(const struct i2c_target_driver_api *)dev->api;
return api->driver_unregister(dev);
}
/*
* Derived i2c APIs -- all implemented in terms of i2c_transfer()
*/
/**
* @brief Write a set amount of data to an I2C device.
*
* This routine writes a set amount of data synchronously.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param buf Memory pool from which the data is transferred.
* @param num_bytes Number of bytes to write.
* @param addr Address to the target I2C device for writing.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
static inline int i2c_write(const struct device *dev, const uint8_t *buf,
uint32_t num_bytes, uint16_t addr)
{
struct i2c_msg msg;
msg.buf = (uint8_t *)buf;
msg.len = num_bytes;
msg.flags = I2C_MSG_WRITE | I2C_MSG_STOP;
return i2c_transfer(dev, &msg, 1, addr);
}
/**
* @brief Write a set amount of data to an I2C device.
*
* This is equivalent to:
*
* i2c_write(spec->bus, buf, num_bytes, spec->addr);
*
* @param spec I2C specification from devicetree.
* @param buf Memory pool from which the data is transferred.
* @param num_bytes Number of bytes to write.
*
* @return a value from i2c_write()
*/
static inline int i2c_write_dt(const struct i2c_dt_spec *spec,
const uint8_t *buf, uint32_t num_bytes)
{
return i2c_write(spec->bus, buf, num_bytes, spec->addr);
}
/**
* @brief Read a set amount of data from an I2C device.
*
* This routine reads a set amount of data synchronously.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param buf Memory pool that stores the retrieved data.
* @param num_bytes Number of bytes to read.
* @param addr Address of the I2C device being read.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
static inline int i2c_read(const struct device *dev, uint8_t *buf,
uint32_t num_bytes, uint16_t addr)
{
struct i2c_msg msg;
msg.buf = buf;
msg.len = num_bytes;
msg.flags = I2C_MSG_READ | I2C_MSG_STOP;
return i2c_transfer(dev, &msg, 1, addr);
}
/**
* @brief Read a set amount of data from an I2C device.
*
* This is equivalent to:
*
* i2c_read(spec->bus, buf, num_bytes, spec->addr);
*
* @param spec I2C specification from devicetree.
* @param buf Memory pool that stores the retrieved data.
* @param num_bytes Number of bytes to read.
*
* @return a value from i2c_read()
*/
static inline int i2c_read_dt(const struct i2c_dt_spec *spec,
uint8_t *buf, uint32_t num_bytes)
{
return i2c_read(spec->bus, buf, num_bytes, spec->addr);
}
/**
* @brief Write then read data from an I2C device.
*
* This supports the common operation "this is what I want", "now give
* it to me" transaction pair through a combined write-then-read bus
* transaction.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param addr Address of the I2C device
* @param write_buf Pointer to the data to be written
* @param num_write Number of bytes to write
* @param read_buf Pointer to storage for read data
* @param num_read Number of bytes to read
*
* @retval 0 if successful
* @retval negative on error.
*/
static inline int i2c_write_read(const struct device *dev, uint16_t addr,
const void *write_buf, size_t num_write,
void *read_buf, size_t num_read)
{
struct i2c_msg msg[2];
msg[0].buf = (uint8_t *)write_buf;
msg[0].len = num_write;
msg[0].flags = I2C_MSG_WRITE;
msg[1].buf = (uint8_t *)read_buf;
msg[1].len = num_read;
msg[1].flags = I2C_MSG_RESTART | I2C_MSG_READ | I2C_MSG_STOP;
return i2c_transfer(dev, msg, 2, addr);
}
/**
* @brief Write then read data from an I2C device.
*
* This is equivalent to:
*
* i2c_write_read(spec->bus, spec->addr,
* write_buf, num_write,
* read_buf, num_read);
*
* @param spec I2C specification from devicetree.
* @param write_buf Pointer to the data to be written
* @param num_write Number of bytes to write
* @param read_buf Pointer to storage for read data
* @param num_read Number of bytes to read
*
* @return a value from i2c_write_read()
*/
static inline int i2c_write_read_dt(const struct i2c_dt_spec *spec,
const void *write_buf, size_t num_write,
void *read_buf, size_t num_read)
{
return i2c_write_read(spec->bus, spec->addr,
write_buf, num_write,
read_buf, num_read);
}
/**
* @brief Read multiple bytes from an internal address of an I2C device.
*
* This routine reads multiple bytes from an internal address of an
* I2C device synchronously.
*
* Instances of this may be replaced by i2c_write_read().
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param dev_addr Address of the I2C device for reading.
* @param start_addr Internal address from which the data is being read.
* @param buf Memory pool that stores the retrieved data.
* @param num_bytes Number of bytes being read.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
static inline int i2c_burst_read(const struct device *dev,
uint16_t dev_addr,
uint8_t start_addr,
uint8_t *buf,
uint32_t num_bytes)
{
return i2c_write_read(dev, dev_addr,
&start_addr, sizeof(start_addr),
buf, num_bytes);
}
/**
* @brief Read multiple bytes from an internal address of an I2C device.
*
* This is equivalent to:
*
* i2c_burst_read(spec->bus, spec->addr, start_addr, buf, num_bytes);
*
* @param spec I2C specification from devicetree.
* @param start_addr Internal address from which the data is being read.
* @param buf Memory pool that stores the retrieved data.
* @param num_bytes Number of bytes to read.
*
* @return a value from i2c_burst_read()
*/
static inline int i2c_burst_read_dt(const struct i2c_dt_spec *spec,
uint8_t start_addr,
uint8_t *buf,
uint32_t num_bytes)
{
return i2c_burst_read(spec->bus, spec->addr,
start_addr, buf, num_bytes);
}
/**
* @brief Write multiple bytes to an internal address of an I2C device.
*
* This routine writes multiple bytes to an internal address of an
* I2C device synchronously.
*
* @warning The combined write synthesized by this API may not be
* supported on all I2C devices. Uses of this API may be made more
* portable by replacing them with calls to i2c_write() passing a
* buffer containing the combined address and data.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param dev_addr Address of the I2C device for writing.
* @param start_addr Internal address to which the data is being written.
* @param buf Memory pool from which the data is transferred.
* @param num_bytes Number of bytes being written.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
static inline int i2c_burst_write(const struct device *dev,
uint16_t dev_addr,
uint8_t start_addr,
const uint8_t *buf,
uint32_t num_bytes)
{
struct i2c_msg msg[2];
msg[0].buf = &start_addr;
msg[0].len = 1U;
msg[0].flags = I2C_MSG_WRITE;
msg[1].buf = (uint8_t *)buf;
msg[1].len = num_bytes;
msg[1].flags = I2C_MSG_WRITE | I2C_MSG_STOP;
return i2c_transfer(dev, msg, 2, dev_addr);
}
/**
* @brief Write multiple bytes to an internal address of an I2C device.
*
* This is equivalent to:
*
* i2c_burst_write(spec->bus, spec->addr, start_addr, buf, num_bytes);
*
* @param spec I2C specification from devicetree.
* @param start_addr Internal address to which the data is being written.
* @param buf Memory pool from which the data is transferred.
* @param num_bytes Number of bytes being written.
*
* @return a value from i2c_burst_write()
*/
static inline int i2c_burst_write_dt(const struct i2c_dt_spec *spec,
uint8_t start_addr,
const uint8_t *buf,
uint32_t num_bytes)
{
return i2c_burst_write(spec->bus, spec->addr,
start_addr, buf, num_bytes);
}
/**
* @brief Read internal register of an I2C device.
*
* This routine reads the value of an 8-bit internal register of an I2C
* device synchronously.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param dev_addr Address of the I2C device for reading.
* @param reg_addr Address of the internal register being read.
* @param value Memory pool that stores the retrieved register value.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
static inline int i2c_reg_read_byte(const struct device *dev,
uint16_t dev_addr,
uint8_t reg_addr, uint8_t *value)
{
return i2c_write_read(dev, dev_addr,
®_addr, sizeof(reg_addr),
value, sizeof(*value));
}
/**
* @brief Read internal register of an I2C device.
*
* This is equivalent to:
*
* i2c_reg_read_byte(spec->bus, spec->addr, reg_addr, value);
*
* @param spec I2C specification from devicetree.
* @param reg_addr Address of the internal register being read.
* @param value Memory pool that stores the retrieved register value.
*
* @return a value from i2c_reg_read_byte()
*/
static inline int i2c_reg_read_byte_dt(const struct i2c_dt_spec *spec,
uint8_t reg_addr, uint8_t *value)
{
return i2c_reg_read_byte(spec->bus, spec->addr, reg_addr, value);
}
/**
* @brief Write internal register of an I2C device.
*
* This routine writes a value to an 8-bit internal register of an I2C
* device synchronously.
*
* @note This function internally combines the register and value into
* a single bus transaction.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param dev_addr Address of the I2C device for writing.
* @param reg_addr Address of the internal register being written.
* @param value Value to be written to internal register.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
static inline int i2c_reg_write_byte(const struct device *dev,
uint16_t dev_addr,
uint8_t reg_addr, uint8_t value)
{
uint8_t tx_buf[2] = {reg_addr, value};
return i2c_write(dev, tx_buf, 2, dev_addr);
}
/**
* @brief Write internal register of an I2C device.
*
* This is equivalent to:
*
* i2c_reg_write_byte(spec->bus, spec->addr, reg_addr, value);
*
* @param spec I2C specification from devicetree.
* @param reg_addr Address of the internal register being written.
* @param value Value to be written to internal register.
*
* @return a value from i2c_reg_write_byte()
*/
static inline int i2c_reg_write_byte_dt(const struct i2c_dt_spec *spec,
uint8_t reg_addr, uint8_t value)
{
return i2c_reg_write_byte(spec->bus, spec->addr, reg_addr, value);
}
/**
* @brief Update internal register of an I2C device.
*
* This routine updates the value of a set of bits from an 8-bit internal
* register of an I2C device synchronously.
*
* @note If the calculated new register value matches the value that
* was read this function will not generate a write operation.
*
* @param dev Pointer to the device structure for an I2C controller
* driver configured in controller mode.
* @param dev_addr Address of the I2C device for updating.
* @param reg_addr Address of the internal register being updated.
* @param mask Bitmask for updating internal register.
* @param value Value for updating internal register.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
static inline int i2c_reg_update_byte(const struct device *dev,
uint8_t dev_addr,
uint8_t reg_addr, uint8_t mask,
uint8_t value)
{
uint8_t old_value, new_value;
int rc;
rc = i2c_reg_read_byte(dev, dev_addr, reg_addr, &old_value);
if (rc != 0) {
return rc;
}
new_value = (old_value & ~mask) | (value & mask);
if (new_value == old_value) {
return 0;
}
return i2c_reg_write_byte(dev, dev_addr, reg_addr, new_value);
}
/**
* @brief Update internal register of an I2C device.
*
* This is equivalent to:
*
* i2c_reg_update_byte(spec->bus, spec->addr, reg_addr, mask, value);
*
* @param spec I2C specification from devicetree.
* @param reg_addr Address of the internal register being updated.
* @param mask Bitmask for updating internal register.
* @param value Value for updating internal register.
*
* @return a value from i2c_reg_update_byte()
*/
static inline int i2c_reg_update_byte_dt(const struct i2c_dt_spec *spec,
uint8_t reg_addr, uint8_t mask,
uint8_t value)
{
return i2c_reg_update_byte(spec->bus, spec->addr,
reg_addr, mask, value);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/i2c.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_I2C_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/i2c.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 13,619 |
```objective-c
/*
*
*/
/**
* @file
* @brief EDAC API header file
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_EDAC_H_
#define ZEPHYR_INCLUDE_DRIVERS_EDAC_H_
#include <errno.h>
#include <sys/types.h>
/**
* @defgroup edac EDAC API
* @since 2.5
* @version 0.8.0
* @ingroup io_interfaces
* @{
*/
/**
* @brief EDAC error type
*/
enum edac_error_type {
/** Correctable error type */
EDAC_ERROR_TYPE_DRAM_COR = BIT(0),
/** Uncorrectable error type */
EDAC_ERROR_TYPE_DRAM_UC = BIT(1)
};
/**
* @cond INTERNAL_HIDDEN
*
* For internal use only, skip these in public documentation.
*/
typedef void (*edac_notify_callback_f)(const struct device *dev, void *data);
/**
* @brief EDAC driver API
*
* This is the mandatory API any EDAC driver needs to expose.
*/
__subsystem struct edac_driver_api {
/* Error Injection API is disabled by default */
int (*inject_set_param1)(const struct device *dev, uint64_t value);
int (*inject_get_param1)(const struct device *dev, uint64_t *value);
int (*inject_set_param2)(const struct device *dev, uint64_t value);
int (*inject_get_param2)(const struct device *dev, uint64_t *value);
int (*inject_set_error_type)(const struct device *dev, uint32_t value);
int (*inject_get_error_type)(const struct device *dev, uint32_t *value);
int (*inject_error_trigger)(const struct device *dev);
/* Error Logging API */
int (*ecc_error_log_get)(const struct device *dev, uint64_t *value);
int (*ecc_error_log_clear)(const struct device *dev);
int (*parity_error_log_get)(const struct device *dev, uint64_t *value);
int (*parity_error_log_clear)(const struct device *dev);
/* Error stats API */
int (*errors_cor_get)(const struct device *dev);
int (*errors_uc_get)(const struct device *dev);
/* Notification callback API */
int (*notify_cb_set)(const struct device *dev,
edac_notify_callback_f cb);
};
/**
* INTERNAL_HIDDEN @endcond
*/
/**
* @name Optional interfaces
* @{
*
* EDAC Optional Interfaces
*/
/**
* @brief Set injection parameter param1
*
* Set first error injection parameter value.
*
* @param dev Pointer to the device structure
* @param value First injection parameter
*
* @retval -ENOSYS if the optional interface is not implemented
* @retval 0 on success, other error code otherwise
*/
static inline int edac_inject_set_param1(const struct device *dev,
uint64_t value)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->inject_set_param1 == NULL) {
return -ENOSYS;
}
return api->inject_set_param1(dev, value);
}
/**
* @brief Get injection parameter param1
*
* Get first error injection parameter value.
*
* @param dev Pointer to the device structure
* @param value Pointer to the first injection parameter
*
* @retval -ENOSYS if the optional interface is not implemented
* @retval 0 on success, error code otherwise
*/
static inline int edac_inject_get_param1(const struct device *dev,
uint64_t *value)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->inject_get_param1 == NULL) {
return -ENOSYS;
}
return api->inject_get_param1(dev, value);
}
/**
* @brief Set injection parameter param2
*
* Set second error injection parameter value.
*
* @param dev Pointer to the device structure
* @param value Second injection parameter
*
* @retval -ENOSYS if the optional interface is not implemented
* @retval 0 on success, error code otherwise
*/
static inline int edac_inject_set_param2(const struct device *dev,
uint64_t value)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->inject_set_param2 == NULL) {
return -ENOSYS;
}
return api->inject_set_param2(dev, value);
}
/**
* @brief Get injection parameter param2
*
* @param dev Pointer to the device structure
* @param value Pointer to the second injection parameter
*
* @retval -ENOSYS if the optional interface is not implemented
* @retval 0 on success, error code otherwise
*/
static inline int edac_inject_get_param2(const struct device *dev,
uint64_t *value)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->inject_get_param2 == NULL) {
return -ENOSYS;
}
return api->inject_get_param2(dev, value);
}
/**
* @brief Set error type value
*
* Set the value of error type to be injected
*
* @param dev Pointer to the device structure
* @param error_type Error type value
*
* @retval -ENOSYS if the optional interface is not implemented
* @retval 0 on success, error code otherwise
*/
static inline int edac_inject_set_error_type(const struct device *dev,
uint32_t error_type)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->inject_set_error_type == NULL) {
return -ENOSYS;
}
return api->inject_set_error_type(dev, error_type);
}
/**
* @brief Get error type value
*
* Get the value of error type to be injected
*
* @param dev Pointer to the device structure
* @param error_type Pointer to error type value
*
* @retval -ENOSYS if the optional interface is not implemented
* @retval 0 on success, error code otherwise
*/
static inline int edac_inject_get_error_type(const struct device *dev,
uint32_t *error_type)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->inject_get_error_type == NULL) {
return -ENOSYS;
}
return api->inject_get_error_type(dev, error_type);
}
/**
* @brief Set injection control
*
* Trigger error injection.
*
* @param dev Pointer to the device structure
*
* @retval -ENOSYS if the optional interface is not implemented
* @retval 0 on success, error code otherwise
*/
static inline int edac_inject_error_trigger(const struct device *dev)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->inject_error_trigger == NULL) {
return -ENOSYS;
}
return api->inject_error_trigger(dev);
}
/** @} */ /* End of EDAC Optional Interfaces */
/**
* @name Mandatory interfaces
* @{
*
* EDAC Mandatory Interfaces
*/
/**
* @brief Get ECC Error Log
*
* Read value of ECC Error Log.
*
* @param dev Pointer to the device structure
* @param value Pointer to the ECC Error Log value
*
* @retval 0 on success, error code otherwise
* @retval -ENOSYS if the mandatory interface is not implemented
*/
static inline int edac_ecc_error_log_get(const struct device *dev,
uint64_t *value)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->ecc_error_log_get == NULL) {
return -ENOSYS;
}
return api->ecc_error_log_get(dev, value);
}
/**
* @brief Clear ECC Error Log
*
* Clear value of ECC Error Log.
*
* @param dev Pointer to the device structure
*
* @retval 0 on success, error code otherwise
* @retval -ENOSYS if the mandatory interface is not implemented
*/
static inline int edac_ecc_error_log_clear(const struct device *dev)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->ecc_error_log_clear == NULL) {
return -ENOSYS;
}
return api->ecc_error_log_clear(dev);
}
/**
* @brief Get Parity Error Log
*
* Read value of Parity Error Log.
*
* @param dev Pointer to the device structure
* @param value Pointer to the parity Error Log value
*
* @retval 0 on success, error code otherwise
* @retval -ENOSYS if the mandatory interface is not implemented
*/
static inline int edac_parity_error_log_get(const struct device *dev,
uint64_t *value)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->parity_error_log_get == NULL) {
return -ENOSYS;
}
return api->parity_error_log_get(dev, value);
}
/**
* @brief Clear Parity Error Log
*
* Clear value of Parity Error Log.
*
* @param dev Pointer to the device structure
*
* @retval 0 on success, error code otherwise
* @retval -ENOSYS if the mandatory interface is not implemented
*/
static inline int edac_parity_error_log_clear(const struct device *dev)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->parity_error_log_clear == NULL) {
return -ENOSYS;
}
return api->parity_error_log_clear(dev);
}
/**
* @brief Get number of correctable errors
*
* @param dev Pointer to the device structure
*
* @retval num Number of correctable errors
* @retval -ENOSYS if the mandatory interface is not implemented
*/
static inline int edac_errors_cor_get(const struct device *dev)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->errors_cor_get == NULL) {
return -ENOSYS;
}
return api->errors_cor_get(dev);
}
/**
* @brief Get number of uncorrectable errors
*
* @param dev Pointer to the device structure
*
* @retval num Number of uncorrectable errors
* @retval -ENOSYS if the mandatory interface is not implemented
*/
static inline int edac_errors_uc_get(const struct device *dev)
{
const struct edac_driver_api *api =
(const struct edac_driver_api *)dev->api;
if (api->errors_uc_get == NULL) {
return -ENOSYS;
}
return api->errors_uc_get(dev);
}
/**
* Register callback function for memory error exception
*
* This callback runs in interrupt context
*
* @param dev EDAC driver device to install callback
* @param cb Callback function pointer
*
* @retval 0 on success, error code otherwise
* @retval -ENOSYS if the mandatory interface is not implemented
*/
static inline int edac_notify_callback_set(const struct device *dev,
edac_notify_callback_f cb)
{
const struct edac_driver_api *api = (const struct edac_driver_api *)dev->api;
if (api->notify_cb_set == NULL) {
return -ENOSYS;
}
return api->notify_cb_set(dev, cb);
}
/** @} */ /* End of EDAC Mandatory Interfaces */
/** @} */ /* End of EDAC API */
#endif /* ZEPHYR_INCLUDE_DRIVERS_EDAC_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/edac.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,512 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public LED driver APIs
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_LED_H_
#define ZEPHYR_INCLUDE_DRIVERS_LED_H_
/**
* @brief LED Interface
* @defgroup led_interface LED Interface
* @since 1.12
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief LED information structure
*
* This structure gathers useful information about LED controller.
*/
struct led_info {
/** LED label */
const char *label;
/** Index of the LED on the controller */
uint32_t index;
/** Number of colors per LED */
uint8_t num_colors;
/** Mapping of the LED colors */
const uint8_t *color_mapping;
};
/**
* @typedef led_api_blink()
* @brief Callback API for blinking an LED
*
* @see led_blink() for argument descriptions.
*/
typedef int (*led_api_blink)(const struct device *dev, uint32_t led,
uint32_t delay_on, uint32_t delay_off);
/**
* @typedef led_api_get_info()
* @brief Optional API callback to get LED information
*
* @see led_get_info() for argument descriptions.
*/
typedef int (*led_api_get_info)(const struct device *dev, uint32_t led,
const struct led_info **info);
/**
* @typedef led_api_set_brightness()
* @brief Callback API for setting brightness of an LED
*
* @see led_set_brightness() for argument descriptions.
*/
typedef int (*led_api_set_brightness)(const struct device *dev, uint32_t led,
uint8_t value);
/**
* @typedef led_api_set_color()
* @brief Optional API callback to set the colors of a LED.
*
* @see led_set_color() for argument descriptions.
*/
typedef int (*led_api_set_color)(const struct device *dev, uint32_t led,
uint8_t num_colors, const uint8_t *color);
/**
* @typedef led_api_on()
* @brief Callback API for turning on an LED
*
* @see led_on() for argument descriptions.
*/
typedef int (*led_api_on)(const struct device *dev, uint32_t led);
/**
* @typedef led_api_off()
* @brief Callback API for turning off an LED
*
* @see led_off() for argument descriptions.
*/
typedef int (*led_api_off)(const struct device *dev, uint32_t led);
/**
* @typedef led_api_write_channels()
* @brief Callback API for writing a strip of LED channels
*
* @see led_api_write_channels() for arguments descriptions.
*/
typedef int (*led_api_write_channels)(const struct device *dev,
uint32_t start_channel,
uint32_t num_channels,
const uint8_t *buf);
/**
* @brief LED driver API
*/
__subsystem struct led_driver_api {
/* Mandatory callbacks. */
led_api_on on;
led_api_off off;
/* Optional callbacks. */
led_api_blink blink;
led_api_get_info get_info;
led_api_set_brightness set_brightness;
led_api_set_color set_color;
led_api_write_channels write_channels;
};
/**
* @brief Blink an LED
*
* This optional routine starts blinking a LED forever with the given time
* period.
*
* @param dev LED device
* @param led LED number
* @param delay_on Time period (in milliseconds) an LED should be ON
* @param delay_off Time period (in milliseconds) an LED should be OFF
* @return 0 on success, negative on error
*/
__syscall int led_blink(const struct device *dev, uint32_t led,
uint32_t delay_on, uint32_t delay_off);
static inline int z_impl_led_blink(const struct device *dev, uint32_t led,
uint32_t delay_on, uint32_t delay_off)
{
const struct led_driver_api *api =
(const struct led_driver_api *)dev->api;
if (api->blink == NULL) {
return -ENOSYS;
}
return api->blink(dev, led, delay_on, delay_off);
}
/**
* @brief Get LED information
*
* This optional routine provides information about a LED.
*
* @param dev LED device
* @param led LED number
* @param info Pointer to a pointer filled with LED information
* @return 0 on success, negative on error
*/
__syscall int led_get_info(const struct device *dev, uint32_t led,
const struct led_info **info);
static inline int z_impl_led_get_info(const struct device *dev, uint32_t led,
const struct led_info **info)
{
const struct led_driver_api *api =
(const struct led_driver_api *)dev->api;
if (api->get_info == NULL) {
*info = NULL;
return -ENOSYS;
}
return api->get_info(dev, led, info);
}
/**
* @brief Set LED brightness
*
* This optional routine sets the brightness of a LED to the given value.
* Calling this function after led_blink() won't affect blinking.
*
* LEDs which can only be turned on or off may provide this function.
* These should simply turn the LED on if @p value is nonzero, and off
* if @p value is zero.
*
* @param dev LED device
* @param led LED number
* @param value Brightness value to set in percent
* @return 0 on success, negative on error
*/
__syscall int led_set_brightness(const struct device *dev, uint32_t led,
uint8_t value);
static inline int z_impl_led_set_brightness(const struct device *dev,
uint32_t led,
uint8_t value)
{
const struct led_driver_api *api =
(const struct led_driver_api *)dev->api;
if (api->set_brightness == NULL) {
return -ENOSYS;
}
return api->set_brightness(dev, led, value);
}
/**
* @brief Write/update a strip of LED channels
*
* This optional routine writes a strip of LED channels to the given array of
* levels. Therefore it can be used to configure several LEDs at the same time.
*
* Calling this function after led_blink() won't affect blinking.
*
* @param dev LED device
* @param start_channel Absolute number (i.e. not relative to a LED) of the
* first channel to update.
* @param num_channels The number of channels to write/update.
* @param buf array of values to configure the channels with. num_channels
* entries must be provided.
* @return 0 on success, negative on error
*/
__syscall int led_write_channels(const struct device *dev,
uint32_t start_channel,
uint32_t num_channels, const uint8_t *buf);
static inline int
z_impl_led_write_channels(const struct device *dev, uint32_t start_channel,
uint32_t num_channels, const uint8_t *buf)
{
const struct led_driver_api *api =
(const struct led_driver_api *)dev->api;
if (api->write_channels == NULL) {
return -ENOSYS;
}
return api->write_channels(dev, start_channel, num_channels, buf);
}
/**
* @brief Set a single LED channel
*
* This optional routine sets a single LED channel to the given value.
*
* Calling this function after led_blink() won't affect blinking.
*
* @param dev LED device
* @param channel Absolute channel number (i.e. not relative to a LED)
* @param value Value to configure the channel with
* @return 0 on success, negative on error
*/
__syscall int led_set_channel(const struct device *dev,
uint32_t channel, uint8_t value);
static inline int z_impl_led_set_channel(const struct device *dev,
uint32_t channel, uint8_t value)
{
return z_impl_led_write_channels(dev, channel, 1, &value);
}
/**
* @brief Set LED color
*
* This routine configures all the color channels of a LED with the given
* color array.
*
* Calling this function after led_blink() won't affect blinking.
*
* @param dev LED device
* @param led LED number
* @param num_colors Number of colors in the array.
* @param color Array of colors. It must be ordered following the color
* mapping of the LED controller. See the color_mapping member
* in struct led_info.
* @return 0 on success, negative on error
*/
__syscall int led_set_color(const struct device *dev, uint32_t led,
uint8_t num_colors, const uint8_t *color);
static inline int z_impl_led_set_color(const struct device *dev, uint32_t led,
uint8_t num_colors, const uint8_t *color)
{
const struct led_driver_api *api =
(const struct led_driver_api *)dev->api;
if (api->set_color == NULL) {
return -ENOSYS;
}
return api->set_color(dev, led, num_colors, color);
}
/**
* @brief Turn on an LED
*
* This routine turns on an LED
*
* @param dev LED device
* @param led LED number
* @return 0 on success, negative on error
*/
__syscall int led_on(const struct device *dev, uint32_t led);
static inline int z_impl_led_on(const struct device *dev, uint32_t led)
{
const struct led_driver_api *api =
(const struct led_driver_api *)dev->api;
return api->on(dev, led);
}
/**
* @brief Turn off an LED
*
* This routine turns off an LED
*
* @param dev LED device
* @param led LED number
* @return 0 on success, negative on error
*/
__syscall int led_off(const struct device *dev, uint32_t led);
static inline int z_impl_led_off(const struct device *dev, uint32_t led)
{
const struct led_driver_api *api =
(const struct led_driver_api *)dev->api;
return api->off(dev, led);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/led.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_LED_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/led.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,214 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public LoRa driver APIs
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_LORA_H_
#define ZEPHYR_INCLUDE_DRIVERS_LORA_H_
/**
* @file
* @brief Public LoRa APIs
* @defgroup lora_api LoRa APIs
* @since 2.2
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#include <stdint.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief LoRa signal bandwidth
*/
enum lora_signal_bandwidth {
BW_125_KHZ = 0,
BW_250_KHZ,
BW_500_KHZ,
};
/**
* @brief LoRa data-rate
*/
enum lora_datarate {
SF_6 = 6,
SF_7,
SF_8,
SF_9,
SF_10,
SF_11,
SF_12,
};
/**
* @brief LoRa coding rate
*/
enum lora_coding_rate {
CR_4_5 = 1,
CR_4_6 = 2,
CR_4_7 = 3,
CR_4_8 = 4,
};
/**
* @struct lora_modem_config
* Structure containing the configuration of a LoRa modem
*/
struct lora_modem_config {
/** Frequency in Hz to use for transceiving */
uint32_t frequency;
/** The bandwidth to use for transceiving */
enum lora_signal_bandwidth bandwidth;
/** The data-rate to use for transceiving */
enum lora_datarate datarate;
/** The coding rate to use for transceiving */
enum lora_coding_rate coding_rate;
/** Length of the preamble */
uint16_t preamble_len;
/** TX-power in dBm to use for transmission */
int8_t tx_power;
/** Set to true for transmission, false for receiving */
bool tx;
/**
* Invert the In-Phase and Quadrature (IQ) signals. Normally this
* should be set to false. In advanced use-cases where a
* differentation is needed between "uplink" and "downlink" traffic,
* the IQ can be inverted to create two different channels on the
* same frequency
*/
bool iq_inverted;
/**
* Sets the sync-byte to use:
* - false: for using the private network sync-byte
* - true: for using the public network sync-byte
* The public network sync-byte is only intended for advanced usage.
* Normally the private network sync-byte should be used for peer
* to peer communications and the LoRaWAN APIs should be used for
* interacting with a public network.
*/
bool public_network;
};
/**
* @cond INTERNAL_HIDDEN
*
* For internal driver use only, skip these in public documentation.
*/
/**
* @typedef lora_recv_cb()
* @brief Callback API for receiving data asynchronously
*
* @see lora_recv() for argument descriptions.
*/
typedef void (*lora_recv_cb)(const struct device *dev, uint8_t *data, uint16_t size,
int16_t rssi, int8_t snr);
/**
* @typedef lora_api_config()
* @brief Callback API for configuring the LoRa module
*
* @see lora_config() for argument descriptions.
*/
typedef int (*lora_api_config)(const struct device *dev,
struct lora_modem_config *config);
/**
* @typedef lora_api_send()
* @brief Callback API for sending data over LoRa
*
* @see lora_send() for argument descriptions.
*/
typedef int (*lora_api_send)(const struct device *dev,
uint8_t *data, uint32_t data_len);
/**
* @typedef lora_api_send_async()
* @brief Callback API for sending data asynchronously over LoRa
*
* @see lora_send_async() for argument descriptions.
*/
typedef int (*lora_api_send_async)(const struct device *dev,
uint8_t *data, uint32_t data_len,
struct k_poll_signal *async);
/**
* @typedef lora_api_recv()
* @brief Callback API for receiving data over LoRa
*
* @see lora_recv() for argument descriptions.
*/
typedef int (*lora_api_recv)(const struct device *dev, uint8_t *data,
uint8_t size,
k_timeout_t timeout, int16_t *rssi, int8_t *snr);
/**
* @typedef lora_api_recv_async()
* @brief Callback API for receiving data asynchronously over LoRa
*
* @param dev Modem to receive data on.
* @param cb Callback to run on receiving data.
*/
typedef int (*lora_api_recv_async)(const struct device *dev, lora_recv_cb cb);
/**
* @typedef lora_api_test_cw()
* @brief Callback API for transmitting a continuous wave
*
* @see lora_test_cw() for argument descriptions.
*/
typedef int (*lora_api_test_cw)(const struct device *dev, uint32_t frequency,
int8_t tx_power, uint16_t duration);
__subsystem struct lora_driver_api {
lora_api_config config;
lora_api_send send;
lora_api_send_async send_async;
lora_api_recv recv;
lora_api_recv_async recv_async;
lora_api_test_cw test_cw;
};
/** @endcond */
/**
* @brief Configure the LoRa modem
*
* @param dev LoRa device
* @param config Data structure containing the intended configuration for the
modem
* @return 0 on success, negative on error
*/
static inline int lora_config(const struct device *dev,
struct lora_modem_config *config)
{
const struct lora_driver_api *api =
(const struct lora_driver_api *)dev->api;
return api->config(dev, config);
}
/**
* @brief Send data over LoRa
*
* @note This blocks until transmission is complete.
*
* @param dev LoRa device
* @param data Data to be sent
* @param data_len Length of the data to be sent
* @return 0 on success, negative on error
*/
static inline int lora_send(const struct device *dev,
uint8_t *data, uint32_t data_len)
{
const struct lora_driver_api *api =
(const struct lora_driver_api *)dev->api;
return api->send(dev, data, data_len);
}
/**
* @brief Asynchronously send data over LoRa
*
* @note This returns immediately after starting transmission, and locks
* the LoRa modem until the transmission completes.
*
* @param dev LoRa device
* @param data Data to be sent
* @param data_len Length of the data to be sent
* @param async A pointer to a valid and ready to be signaled
* struct k_poll_signal. (Note: if NULL this function will not
* notify the end of the transmission).
* @return 0 on success, negative on error
*/
static inline int lora_send_async(const struct device *dev,
uint8_t *data, uint32_t data_len,
struct k_poll_signal *async)
{
const struct lora_driver_api *api =
(const struct lora_driver_api *)dev->api;
return api->send_async(dev, data, data_len, async);
}
/**
* @brief Receive data over LoRa
*
* @note This is a blocking call.
*
* @param dev LoRa device
* @param data Buffer to hold received data
* @param size Size of the buffer to hold the received data. Max size
allowed is 255.
* @param timeout Duration to wait for a packet.
* @param rssi RSSI of received data
* @param snr SNR of received data
* @return Length of the data received on success, negative on error
*/
static inline int lora_recv(const struct device *dev, uint8_t *data,
uint8_t size,
k_timeout_t timeout, int16_t *rssi, int8_t *snr)
{
const struct lora_driver_api *api =
(const struct lora_driver_api *)dev->api;
return api->recv(dev, data, size, timeout, rssi, snr);
}
/**
* @brief Receive data asynchronously over LoRa
*
* Receive packets continuously under the configuration previously setup
* by @ref lora_config.
*
* Reception is cancelled by calling this function again with @p cb = NULL.
* This can be done within the callback handler.
*
* @param dev Modem to receive data on.
* @param cb Callback to run on receiving data. If NULL, any pending
* asynchronous receptions will be cancelled.
* @return 0 when reception successfully setup, negative on error
*/
static inline int lora_recv_async(const struct device *dev, lora_recv_cb cb)
{
const struct lora_driver_api *api =
(const struct lora_driver_api *)dev->api;
return api->recv_async(dev, cb);
}
/**
* @brief Transmit an unmodulated continuous wave at a given frequency
*
* @note Only use this functionality in a test setup where the
* transmission does not interfere with other devices.
*
* @param dev LoRa device
* @param frequency Output frequency (Hertz)
* @param tx_power TX power (dBm)
* @param duration Transmission duration in seconds.
* @return 0 on success, negative on error
*/
static inline int lora_test_cw(const struct device *dev, uint32_t frequency,
int8_t tx_power, uint16_t duration)
{
const struct lora_driver_api *api =
(const struct lora_driver_api *)dev->api;
if (api->test_cw == NULL) {
return -ENOSYS;
}
return api->test_cw(dev, frequency, tx_power, duration);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_LORA_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/lora.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,179 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_BBRAM_H
#define ZEPHYR_INCLUDE_DRIVERS_BBRAM_H
#include <errno.h>
#include <zephyr/device.h>
/**
* @brief BBRAM Interface
* @defgroup bbram_interface BBRAM Interface
* @ingroup io_interfaces
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* @typedef bbram_api_check_invalid_t
* @brief API template to check if the BBRAM is invalid.
*
* @see bbram_check_invalid
*/
typedef int (*bbram_api_check_invalid_t)(const struct device *dev);
/**
* @typedef bbram_api_check_standby_power_t
* @brief API template to check for standby power failure.
*
* @see bbram_check_standby_power
*/
typedef int (*bbram_api_check_standby_power_t)(const struct device *dev);
/**
* @typedef bbram_api_check_power_t
* @brief API template to check for V CC1 power failure.
*
* @see bbram_check_power
*/
typedef int (*bbram_api_check_power_t)(const struct device *dev);
/**
* @typedef bbram_api_get_size_t
* @brief API template to check the size of the BBRAM
*
* @see bbram_get_size
*/
typedef int (*bbram_api_get_size_t)(const struct device *dev, size_t *size);
/**
* @typedef bbram_api_read_t
* @brief API template to read from BBRAM.
*
* @see bbram_read
*/
typedef int (*bbram_api_read_t)(const struct device *dev, size_t offset, size_t size,
uint8_t *data);
/**
* @typedef bbram_api_write_t
* @brief API template to write to BBRAM.
*
* @see bbram_write
*/
typedef int (*bbram_api_write_t)(const struct device *dev, size_t offset, size_t size,
const uint8_t *data);
__subsystem struct bbram_driver_api {
bbram_api_check_invalid_t check_invalid;
bbram_api_check_standby_power_t check_standby_power;
bbram_api_check_power_t check_power;
bbram_api_get_size_t get_size;
bbram_api_read_t read;
bbram_api_write_t write;
};
/**
* @brief Check if BBRAM is invalid
*
* Check if "Invalid Battery-Backed RAM" status is set then reset the status bit. This may occur as
* a result to low voltage at the VBAT pin.
*
* @param[in] dev BBRAM device pointer.
* @return 0 if the Battery-Backed RAM data is valid, -EFAULT otherwise.
*/
__syscall int bbram_check_invalid(const struct device *dev);
static inline int z_impl_bbram_check_invalid(const struct device *dev)
{
const struct bbram_driver_api *api =
(const struct bbram_driver_api *)dev->api;
if (!api->check_invalid) {
return -ENOTSUP;
}
return api->check_invalid(dev);
}
/**
* @brief Check for standby (Volt SBY) power failure.
*
* Check if the V standby power domain is turned on after it was off then reset the status bit.
*
* @param[in] dev BBRAM device pointer.
* @return 0 if V SBY power domain is in normal operation.
*/
__syscall int bbram_check_standby_power(const struct device *dev);
static inline int z_impl_bbram_check_standby_power(const struct device *dev)
{
const struct bbram_driver_api *api =
(const struct bbram_driver_api *)dev->api;
if (!api->check_standby_power) {
return -ENOTSUP;
}
return api->check_standby_power(dev);
}
/**
* @brief Check for V CC1 power failure.
*
* This will return an error if the V CC1 power domain is turned on after it was off and reset the
* status bit.
*
* @param[in] dev BBRAM device pointer.
* @return 0 if the V CC1 power domain is in normal operation, -EFAULT otherwise.
*/
__syscall int bbram_check_power(const struct device *dev);
static inline int z_impl_bbram_check_power(const struct device *dev)
{
const struct bbram_driver_api *api =
(const struct bbram_driver_api *)dev->api;
if (!api->check_power) {
return -ENOTSUP;
}
return api->check_power(dev);
}
/**
* @brief Get the size of the BBRAM (in bytes).
*
* @param[in] dev BBRAM device pointer.
* @param[out] size Pointer to write the size to.
* @return 0 for success, -EFAULT otherwise.
*/
__syscall int bbram_get_size(const struct device *dev, size_t *size);
static inline int z_impl_bbram_get_size(const struct device *dev, size_t *size)
{
const struct bbram_driver_api *api =
(const struct bbram_driver_api *)dev->api;
if (!api->get_size) {
return -ENOTSUP;
}
return api->get_size(dev, size);
}
/**
* @brief Read bytes from BBRAM.
*
* @param[in] dev The BBRAM device pointer to read from.
* @param[in] offset The offset into the RAM address to start reading from.
* @param[in] size The number of bytes to read.
* @param[out] data The buffer to load the data into.
* @return 0 on success, -EFAULT if the address range is out of bounds.
*/
__syscall int bbram_read(const struct device *dev, size_t offset, size_t size,
uint8_t *data);
static inline int z_impl_bbram_read(const struct device *dev, size_t offset,
size_t size, uint8_t *data)
{
const struct bbram_driver_api *api =
(const struct bbram_driver_api *)dev->api;
if (!api->read) {
return -ENOTSUP;
}
return api->read(dev, offset, size, data);
}
/**
* @brief Write bytes to BBRAM.
*
* @param[in] dev The BBRAM device pointer to write to.
* @param[in] offset The offset into the RAM address to start writing to.
* @param[in] size The number of bytes to write.
* @param[out] data Pointer to the start of data to write.
* @return 0 on success, -EFAULT if the address range is out of bounds.
*/
__syscall int bbram_write(const struct device *dev, size_t offset, size_t size,
const uint8_t *data);
static inline int z_impl_bbram_write(const struct device *dev, size_t offset,
size_t size, const uint8_t *data)
{
const struct bbram_driver_api *api =
(const struct bbram_driver_api *)dev->api;
if (!api->write) {
return -ENOTSUP;
}
return api->write(dev, offset, size, data);
}
/**
* @brief Set the emulated BBRAM driver's invalid state
*
* Calling this will affect the emulated behavior of bbram_check_invalid().
*
* @param[in] dev The emulated device to modify
* @param[in] is_invalid The new invalid state
* @return 0 on success, negative values on error.
*/
int bbram_emul_set_invalid(const struct device *dev, bool is_invalid);
/**
* @brief Set the emulated BBRAM driver's standby power state
*
* Calling this will affect the emulated behavior of bbram_check_standby_power().
*
* @param[in] dev The emulated device to modify
* @param[in] failure Whether or not standby power failure should be emulated
* @return 0 on success, negative values on error.
*/
int bbram_emul_set_standby_power_state(const struct device *dev, bool failure);
/**
* @brief Set the emulated BBRAM driver's power state
*
* Calling this will affect the emulated behavior of bbram_check_power().
*
* @param[in] dev The emulated device to modify
* @param[in] failure Whether or not a power failure should be emulated
* @return 0 on success, negative values on error.
*/
int bbram_emul_set_power_state(const struct device *dev, bool failure);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/bbram.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_BBRAM_H */
``` | /content/code_sandbox/include/zephyr/drivers/bbram.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,877 |
```objective-c
/*
*/
/**
* @file
* Public APIs for pin control drivers
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_PINCTRL_H_
#define ZEPHYR_INCLUDE_DRIVERS_PINCTRL_H_
/**
* @brief Pin Controller Interface
* @defgroup pinctrl_interface Pin Controller Interface
* @since 3.0
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/devicetree/pinctrl.h>
#include <pinctrl_soc.h>
#include <zephyr/sys/util.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name Pin control states
* @anchor PINCTRL_STATES
* @{
*/
/** Default state (state used when the device is in operational state). */
#define PINCTRL_STATE_DEFAULT 0U
/** Sleep state (state used when the device is in low power mode). */
#define PINCTRL_STATE_SLEEP 1U
/** This and higher values refer to custom private states. */
#define PINCTRL_STATE_PRIV_START 2U
/** @} */
/** Pin control state configuration. */
struct pinctrl_state {
/** Pin configurations. */
const pinctrl_soc_pin_t *pins;
/** Number of pin configurations. */
uint8_t pin_cnt;
/** State identifier (see @ref PINCTRL_STATES). */
uint8_t id;
};
/** Pin controller configuration for a given device. */
struct pinctrl_dev_config {
#if defined(CONFIG_PINCTRL_STORE_REG) || defined(__DOXYGEN__)
/**
* Device address (only available if @kconfig{CONFIG_PINCTRL_STORE_REG}
* is enabled).
*/
uintptr_t reg;
#endif /* defined(CONFIG_PINCTRL_STORE_REG) || defined(__DOXYGEN__) */
/** List of state configurations. */
const struct pinctrl_state *states;
/** Number of state configurations. */
uint8_t state_cnt;
};
/** Utility macro to indicate no register is used. */
#define PINCTRL_REG_NONE 0U
/** @cond INTERNAL_HIDDEN */
#if !defined(CONFIG_PM) && !defined(CONFIG_PM_DEVICE)
/** Out of power management configurations, ignore "sleep" state. */
#define PINCTRL_SKIP_SLEEP 1
#endif
/**
* @brief Obtain the state identifier for the given node and state index.
*
* @param state_idx State index.
* @param node_id Node identifier.
*/
#define Z_PINCTRL_STATE_ID(state_idx, node_id) \
_CONCAT(PINCTRL_STATE_, \
DT_PINCTRL_IDX_TO_NAME_UPPER_TOKEN(node_id, state_idx))
/**
* @brief Obtain the variable name storing pinctrl config for the given DT node
* identifier.
*
* @param node_id Node identifier.
*/
#define Z_PINCTRL_DEV_CONFIG_NAME(node_id) \
_CONCAT(__pinctrl_dev_config, DEVICE_DT_NAME_GET(node_id))
/**
* @brief Obtain the variable name storing pinctrl states for the given DT node
* identifier.
*
* @param node_id Node identifier.
*/
#define Z_PINCTRL_STATES_NAME(node_id) \
_CONCAT(__pinctrl_states, DEVICE_DT_NAME_GET(node_id))
/**
* @brief Obtain the variable name storing pinctrl pins for the given DT node
* identifier and state index.
*
* @param state_idx State index.
* @param node_id Node identifier.
*/
#define Z_PINCTRL_STATE_PINS_NAME(state_idx, node_id) \
_CONCAT(__pinctrl_state_pins_ ## state_idx, DEVICE_DT_NAME_GET(node_id))
/**
* @brief Utility macro to check if given state has to be skipped.
*
* If a certain state has to be skipped, a macro named PINCTRL_SKIP_<STATE>
* can be defined evaluating to 1. This can be useful, for example, to
* automatically ignore the sleep state if no device power management is
* enabled.
*
* @param state_idx State index.
* @param node_id Node identifier.
*/
#define Z_PINCTRL_SKIP_STATE(state_idx, node_id) \
_CONCAT(PINCTRL_SKIP_, \
DT_PINCTRL_IDX_TO_NAME_UPPER_TOKEN(node_id, state_idx))
/**
* @brief Helper macro to define pins for a given pin control state.
*
* @param state_idx State index.
* @param node_id Node identifier.
*/
#define Z_PINCTRL_STATE_PINS_DEFINE(state_idx, node_id) \
COND_CODE_1(Z_PINCTRL_SKIP_STATE(state_idx, node_id), (), \
(static const pinctrl_soc_pin_t \
Z_PINCTRL_STATE_PINS_NAME(state_idx, node_id)[] = \
Z_PINCTRL_STATE_PINS_INIT(node_id, pinctrl_ ## state_idx)))
/**
* @brief Helper macro to initialize a pin control state.
*
* @param state_idx State index.
* @param node_id Node identifier.
*/
#define Z_PINCTRL_STATE_INIT(state_idx, node_id) \
COND_CODE_1(Z_PINCTRL_SKIP_STATE(state_idx, node_id), (), \
({ \
.id = Z_PINCTRL_STATE_ID(state_idx, node_id), \
.pins = Z_PINCTRL_STATE_PINS_NAME(state_idx, node_id), \
.pin_cnt = ARRAY_SIZE(Z_PINCTRL_STATE_PINS_NAME(state_idx, \
node_id)) \
}))
/**
* @brief Define all the states for the given node identifier.
*
* @param node_id Node identifier.
*/
#define Z_PINCTRL_STATES_DEFINE(node_id) \
static const struct pinctrl_state \
Z_PINCTRL_STATES_NAME(node_id)[] = { \
LISTIFY(DT_NUM_PINCTRL_STATES(node_id), \
Z_PINCTRL_STATE_INIT, (,), node_id) \
};
#ifdef CONFIG_PINCTRL_STORE_REG
/**
* @brief Helper macro to initialize pin control config.
*
* @param node_id Node identifier.
*/
#define Z_PINCTRL_DEV_CONFIG_INIT(node_id) \
{ \
.reg = DT_REG_ADDR(node_id), \
.states = Z_PINCTRL_STATES_NAME(node_id), \
.state_cnt = ARRAY_SIZE(Z_PINCTRL_STATES_NAME(node_id)), \
}
#else
#define Z_PINCTRL_DEV_CONFIG_INIT(node_id) \
{ \
.states = Z_PINCTRL_STATES_NAME(node_id), \
.state_cnt = ARRAY_SIZE(Z_PINCTRL_STATES_NAME(node_id)), \
}
#endif
#ifdef CONFIG_PINCTRL_NON_STATIC
#define Z_PINCTRL_DEV_CONFIG_STATIC
#else
#define Z_PINCTRL_DEV_CONFIG_STATIC static
#endif
#ifdef CONFIG_PINCTRL_DYNAMIC
#define Z_PINCTRL_DEV_CONFIG_CONST
#else
#define Z_PINCTRL_DEV_CONFIG_CONST const
#endif
/** @endcond */
#if defined(CONFIG_PINCTRL_NON_STATIC) || defined(__DOXYGEN__)
/**
* @brief Declare pin control configuration for a given node identifier.
*
* This macro should be used by tests or applications using runtime pin control
* to declare the pin control configuration for a device.
* #PINCTRL_DT_DEV_CONFIG_GET can later be used to obtain a reference to such
* configuration.
*
* Only available if @kconfig{CONFIG_PINCTRL_NON_STATIC} is selected.
*
* @param node_id Node identifier.
*/
#define PINCTRL_DT_DEV_CONFIG_DECLARE(node_id) \
extern Z_PINCTRL_DEV_CONFIG_CONST struct pinctrl_dev_config \
Z_PINCTRL_DEV_CONFIG_NAME(node_id)
#endif /* defined(CONFIG_PINCTRL_NON_STATIC) || defined(__DOXYGEN__) */
/**
* @brief Define all pin control information for the given node identifier.
*
* This helper macro should be called together with device definition. It
* defines and initializes the pin control configuration for the device
* represented by node_id. Each pin control state (pinctrl-0, ..., pinctrl-N) is
* also defined and initialized. Note that states marked to be skipped will not
* be defined (refer to Z_PINCTRL_SKIP_STATE for more details).
*
* @param node_id Node identifier.
*/
#define PINCTRL_DT_DEFINE(node_id) \
LISTIFY(DT_NUM_PINCTRL_STATES(node_id), \
Z_PINCTRL_STATE_PINS_DEFINE, (;), node_id); \
Z_PINCTRL_STATES_DEFINE(node_id) \
Z_PINCTRL_DEV_CONFIG_STATIC Z_PINCTRL_DEV_CONFIG_CONST \
struct pinctrl_dev_config Z_PINCTRL_DEV_CONFIG_NAME(node_id) = \
Z_PINCTRL_DEV_CONFIG_INIT(node_id)
/**
* @brief Define all pin control information for the given compatible index.
*
* @param inst Instance number.
*
* @see #PINCTRL_DT_DEFINE
*/
#define PINCTRL_DT_INST_DEFINE(inst) PINCTRL_DT_DEFINE(DT_DRV_INST(inst))
/**
* @brief Obtain a reference to the pin control configuration given a node
* identifier.
*
* @param node_id Node identifier.
*/
#define PINCTRL_DT_DEV_CONFIG_GET(node_id) &Z_PINCTRL_DEV_CONFIG_NAME(node_id)
/**
* @brief Obtain a reference to the pin control configuration given current
* compatible instance number.
*
* @param inst Instance number.
*
* @see #PINCTRL_DT_DEV_CONFIG_GET
*/
#define PINCTRL_DT_INST_DEV_CONFIG_GET(inst) \
PINCTRL_DT_DEV_CONFIG_GET(DT_DRV_INST(inst))
/**
* @brief Find the state configuration for the given state id.
*
* @param config Pin controller configuration.
* @param id Pin controller state id (see @ref PINCTRL_STATES).
* @param state Found state.
*
* @retval 0 If state has been found.
* @retval -ENOENT If the state has not been found.
*/
int pinctrl_lookup_state(const struct pinctrl_dev_config *config, uint8_t id,
const struct pinctrl_state **state);
/**
* @brief Configure a set of pins.
*
* This function will configure the necessary hardware blocks to make the
* configuration immediately effective.
*
* @warning This function must never be used to configure pins used by an
* instantiated device driver.
*
* @param pins List of pins to be configured.
* @param pin_cnt Number of pins.
* @param reg Device register (optional, use #PINCTRL_REG_NONE if not used).
*
* @retval 0 If succeeded
* @retval -errno Negative errno for other failures.
*/
int pinctrl_configure_pins(const pinctrl_soc_pin_t *pins, uint8_t pin_cnt,
uintptr_t reg);
/**
* @brief Apply a state directly from the provided state configuration.
*
* @param config Pin control configuration.
* @param state State.
*
* @retval 0 If succeeded
* @retval -errno Negative errno for other failures.
*/
static inline int pinctrl_apply_state_direct(
const struct pinctrl_dev_config *config,
const struct pinctrl_state *state)
{
uintptr_t reg;
#ifdef CONFIG_PINCTRL_STORE_REG
reg = config->reg;
#else
ARG_UNUSED(config);
reg = PINCTRL_REG_NONE;
#endif
return pinctrl_configure_pins(state->pins, state->pin_cnt, reg);
}
/**
* @brief Apply a state from the given device configuration.
*
* @param config Pin control configuration.
* @param id Id of the state to be applied (see @ref PINCTRL_STATES).
*
* @retval 0 If succeeded.
* @retval -ENOENT If given state id does not exist.
* @retval -errno Negative errno for other failures.
*/
static inline int pinctrl_apply_state(const struct pinctrl_dev_config *config,
uint8_t id)
{
int ret;
const struct pinctrl_state *state;
ret = pinctrl_lookup_state(config, id, &state);
if (ret < 0) {
return ret;
}
return pinctrl_apply_state_direct(config, state);
}
#if defined(CONFIG_PINCTRL_DYNAMIC) || defined(__DOXYGEN__)
/**
* @defgroup pinctrl_interface_dynamic Dynamic Pin Control
* @{
*/
/**
* @brief Helper macro to define the pins of a pin control state from
* Devicetree.
*
* The name of the defined state pins variable is the same used by @p prop. This
* macro is expected to be used in conjunction with #PINCTRL_DT_STATE_INIT.
*
* @param node_id Node identifier containing @p prop.
* @param prop Property within @p node_id containing state configuration.
*
* @see #PINCTRL_DT_STATE_INIT
*/
#define PINCTRL_DT_STATE_PINS_DEFINE(node_id, prop) \
static const pinctrl_soc_pin_t prop ## _pins[] = \
Z_PINCTRL_STATE_PINS_INIT(node_id, prop); \
/**
* @brief Utility macro to initialize a pin control state.
*
* This macro should be used in conjunction with #PINCTRL_DT_STATE_PINS_DEFINE
* when using dynamic pin control to define an alternative state configuration
* stored in Devicetree.
*
* Example:
*
* @code{.devicetree}
* // board.dts
*
* /{
* zephyr,user {
* // uart0_alt_default node contains alternative pin config
* uart0_alt_default = <&uart0_alt_default>;
* };
* };
* @endcode
*
* @code{.c}
* // application
*
* PINCTRL_DT_STATE_PINS_DEFINE(DT_PATH(zephyr_user), uart0_alt_default);
*
* static const struct pinctrl_state uart0_alt[] = {
* PINCTRL_DT_STATE_INIT(uart0_alt_default, PINCTRL_STATE_DEFAULT)
* };
* @endcode
*
* @param prop Property name in Devicetree containing state configuration.
* @param state State represented by @p prop (see @ref PINCTRL_STATES).
*
* @see #PINCTRL_DT_STATE_PINS_DEFINE
*/
#define PINCTRL_DT_STATE_INIT(prop, state) \
{ \
.id = state, \
.pins = prop ## _pins, \
.pin_cnt = ARRAY_SIZE(prop ## _pins) \
}
/**
* @brief Update states with a new set.
*
* @note In order to guarantee device drivers correct operation the same states
* have to be provided. For example, if @c default and @c sleep are in the
* current list of states, it is expected that the new array of states also
* contains both.
*
* @param config Pin control configuration.
* @param states New states to be set.
* @param state_cnt Number of new states to be set.
*
* @retval -EINVAL If the new configuration does not contain the same states as
* the current active configuration.
* @retval -ENOSYS If the functionality is not available.
* @retval 0 On success.
*/
int pinctrl_update_states(struct pinctrl_dev_config *config,
const struct pinctrl_state *states,
uint8_t state_cnt);
/** @} */
#else
static inline int pinctrl_update_states(
struct pinctrl_dev_config *config,
const struct pinctrl_state *states, uint8_t state_cnt)
{
ARG_UNUSED(config);
ARG_UNUSED(states);
ARG_UNUSED(state_cnt);
return -ENOSYS;
}
#endif /* defined(CONFIG_PINCTRL_DYNAMIC) || defined(__DOXYGEN__) */
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_PINCTRL_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/pinctrl.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 3,233 |
```objective-c
/** @file
* @brief Bluetooth HCI driver API.
*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_BLUETOOTH_H_
#define ZEPHYR_INCLUDE_DRIVERS_BLUETOOTH_H_
/**
* @brief Bluetooth HCI APIs
* @defgroup bt_hci_api Bluetooth HCI APIs
*
* @since 3.7
* @version 0.2.0
*
* @ingroup bluetooth
* @{
*/
#include <stdbool.h>
#include <stdint.h>
#include <zephyr/net/buf.h>
#include <zephyr/bluetooth/buf.h>
#include <zephyr/bluetooth/addr.h>
#include <zephyr/bluetooth/hci_vs.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
struct bt_hci_setup_params {
/** The public identity address to give to the controller. This field is used when the
* driver selects @kconfig{CONFIG_BT_HCI_SET_PUBLIC_ADDR} to indicate that it supports
* setting the controller's public address.
*/
bt_addr_t public_addr;
};
enum {
/* The host should never send HCI_Reset */
BT_HCI_QUIRK_NO_RESET = BIT(0),
/* The controller does not auto-initiate a DLE procedure when the
* initial connection data length parameters are not equal to the
* default data length parameters. Therefore the host should initiate
* the DLE procedure after connection establishment.
*/
BT_HCI_QUIRK_NO_AUTO_DLE = BIT(1),
};
/** Possible values for the 'bus' member of the bt_hci_driver struct */
enum bt_hci_bus {
BT_HCI_BUS_VIRTUAL = 0,
BT_HCI_BUS_USB = 1,
BT_HCI_BUS_PCCARD = 2,
BT_HCI_BUS_UART = 3,
BT_HCI_BUS_RS232 = 4,
BT_HCI_BUS_PCI = 5,
BT_HCI_BUS_SDIO = 6,
BT_HCI_BUS_SPI = 7,
BT_HCI_BUS_I2C = 8,
BT_HCI_BUS_IPM = 9,
};
#define BT_DT_HCI_QUIRK_OR(node_id, prop, idx) DT_STRING_TOKEN_BY_IDX(node_id, prop, idx)
#define BT_DT_HCI_QUIRKS_GET(node_id) COND_CODE_1(DT_NODE_HAS_PROP(node_id, bt_hci_quirks), \
(DT_FOREACH_PROP_ELEM_SEP(node_id, \
bt_hci_quirks, \
BT_DT_HCI_QUIRK_OR, \
(|))), \
(0))
#define BT_DT_HCI_QUIRKS_INST_GET(inst) BT_DT_HCI_QUIRKS_GET(DT_DRV_INST(inst))
#define BT_DT_HCI_NAME_GET(node_id) DT_PROP_OR(node_id, bt_hci_name, "HCI")
#define BT_DT_HCI_NAME_INST_GET(inst) BT_DT_HCI_NAME_GET(DT_DRV_INST(inst))
#define BT_DT_HCI_BUS_GET(node_id) DT_STRING_TOKEN_OR(node_id, bt_hci_bus, BT_HCI_BUS_VIRTUAL)
#define BT_DT_HCI_BUS_INST_GET(inst) BT_DT_HCI_BUS_GET(DT_DRV_INST(inst))
typedef int (*bt_hci_recv_t)(const struct device *dev, struct net_buf *buf);
__subsystem struct bt_hci_driver_api {
int (*open)(const struct device *dev, bt_hci_recv_t recv);
int (*close)(const struct device *dev);
int (*send)(const struct device *dev, struct net_buf *buf);
#if defined(CONFIG_BT_HCI_SETUP)
int (*setup)(const struct device *dev,
const struct bt_hci_setup_params *param);
#endif /* defined(CONFIG_BT_HCI_SETUP) */
};
/**
* @brief Open the HCI transport.
*
* Opens the HCI transport for operation. This function must not
* return until the transport is ready for operation, meaning it
* is safe to start calling the send() handler.
*
* @param dev HCI device
* @param recv This is callback through which the HCI driver provides the
* host with data from the controller. The buffer passed to
* the callback will have its type set with bt_buf_set_type().
* The callback is expected to be called from thread context.
*
* @return 0 on success or negative POSIX error number on failure.
*/
static inline int bt_hci_open(const struct device *dev, bt_hci_recv_t recv)
{
const struct bt_hci_driver_api *api = (const struct bt_hci_driver_api *)dev->api;
return api->open(dev, recv);
}
/**
* @brief Close the HCI transport.
*
* Closes the HCI transport. This function must not return until the
* transport is closed.
*
* @param dev HCI device
*
* @return 0 on success or negative POSIX error number on failure.
*/
static inline int bt_hci_close(const struct device *dev)
{
const struct bt_hci_driver_api *api = (const struct bt_hci_driver_api *)dev->api;
if (api->close == NULL) {
return -ENOSYS;
}
return api->close(dev);
}
/**
* @brief Send HCI buffer to controller.
*
* Send an HCI packet to the controller. The packet type of the buffer
* must be set using bt_buf_set_type().
*
* @note This function must only be called from a cooperative thread.
*
* @param dev HCI device
* @param buf Buffer containing data to be sent to the controller.
*
* @return 0 on success or negative POSIX error number on failure.
*/
static inline int bt_hci_send(const struct device *dev, struct net_buf *buf)
{
const struct bt_hci_driver_api *api = (const struct bt_hci_driver_api *)dev->api;
return api->send(dev, buf);
}
#if defined(CONFIG_BT_HCI_SETUP) || defined(__DOXYGEN__)
/**
* @brief HCI vendor-specific setup
*
* Executes vendor-specific commands sequence to initialize
* BT Controller before BT Host executes Reset sequence. This is normally
* called directly after bt_hci_open().
*
* @note @kconfig{CONFIG_BT_HCI_SETUP} must be selected for this
* field to be available.
*
* @return 0 on success or negative POSIX error number on failure.
*/
static inline int bt_hci_setup(const struct device *dev, struct bt_hci_setup_params *params)
{
const struct bt_hci_driver_api *api = (const struct bt_hci_driver_api *)dev->api;
if (api->setup == NULL) {
return -ENOSYS;
}
return api->setup(dev, params);
}
#endif
/**
* @}
*/
/* The following functions are not strictly part of the HCI driver API, in that
* they do not take as input a struct device which implements the HCI driver API.
*/
/**
* @brief Setup the HCI transport, which usually means to reset the
* Bluetooth IC.
*
* @note A weak version of this function is included in the H4 driver, so
* defining it is optional per board.
*
* @param dev The device structure for the bus connecting to the IC
*
* @return 0 on success, negative error value on failure
*/
int bt_hci_transport_setup(const struct device *dev);
/**
* @brief Teardown the HCI transport.
*
* @note A weak version of this function is included in the IPC driver, so
* defining it is optional. NRF5340 includes support to put network core
* in reset state.
*
* @param dev The device structure for the bus connecting to the IC
*
* @return 0 on success, negative error value on failure
*/
int bt_hci_transport_teardown(const struct device *dev);
/** Allocate an HCI event buffer.
*
* This function allocates a new buffer for an HCI event. It is given the
* event code and the total length of the parameters. Upon successful return
* the buffer is ready to have the parameters encoded into it.
*
* @param evt HCI event OpCode.
* @param len Length of event parameters.
*
* @return Newly allocated buffer.
*/
struct net_buf *bt_hci_evt_create(uint8_t evt, uint8_t len);
/** Allocate an HCI Command Complete event buffer.
*
* This function allocates a new buffer for HCI Command Complete event.
* It is given the OpCode (encoded e.g. using the BT_OP macro) and the total
* length of the parameters. Upon successful return the buffer is ready to have
* the parameters encoded into it.
*
* @param op HCI command OpCode.
* @param plen Length of command parameters.
*
* @return Newly allocated buffer.
*/
struct net_buf *bt_hci_cmd_complete_create(uint16_t op, uint8_t plen);
/** Allocate an HCI Command Status event buffer.
*
* This function allocates a new buffer for HCI Command Status event.
* It is given the OpCode (encoded e.g. using the BT_OP macro) and the status
* code. Upon successful return the buffer is ready to have the parameters
* encoded into it.
*
* @param op HCI command OpCode.
* @param status Status code.
*
* @return Newly allocated buffer.
*/
struct net_buf *bt_hci_cmd_status_create(uint16_t op, uint8_t status);
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_BLUETOOTH_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/bluetooth.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,019 |
```objective-c
/**
* @file
*
* @brief Public APIs for the DMA drivers.
*/
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_DMA_H_
#define ZEPHYR_INCLUDE_DRIVERS_DMA_H_
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief DMA Interface
* @defgroup dma_interface DMA Interface
* @since 1.5
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
/**
* @brief DMA channel direction
*/
enum dma_channel_direction {
/** Memory to memory */
MEMORY_TO_MEMORY = 0x0,
/** Memory to peripheral */
MEMORY_TO_PERIPHERAL,
/** Peripheral to memory */
PERIPHERAL_TO_MEMORY,
/** Peripheral to peripheral */
PERIPHERAL_TO_PERIPHERAL,
/** Host to memory */
HOST_TO_MEMORY,
/** Memory to host */
MEMORY_TO_HOST,
/**
* Number of all common channel directions.
*/
DMA_CHANNEL_DIRECTION_COMMON_COUNT,
/**
* This and higher values are dma controller or soc specific.
* Refer to the specified dma driver header file.
*/
DMA_CHANNEL_DIRECTION_PRIV_START = DMA_CHANNEL_DIRECTION_COMMON_COUNT,
/**
* Maximum allowed value (3 bit field!)
*/
DMA_CHANNEL_DIRECTION_MAX = 0x7
};
/**
* @brief DMA address adjustment
*
* Valid values for @a source_addr_adj and @a dest_addr_adj
*/
enum dma_addr_adj {
/** Increment the address */
DMA_ADDR_ADJ_INCREMENT,
/** Decrement the address */
DMA_ADDR_ADJ_DECREMENT,
/** No change the address */
DMA_ADDR_ADJ_NO_CHANGE,
};
/**
* @brief DMA channel attributes
*/
enum dma_channel_filter {
DMA_CHANNEL_NORMAL, /* normal DMA channel */
DMA_CHANNEL_PERIODIC, /* can be triggered by periodic sources */
};
/**
* @brief DMA attributes
*/
enum dma_attribute_type {
DMA_ATTR_BUFFER_ADDRESS_ALIGNMENT,
DMA_ATTR_BUFFER_SIZE_ALIGNMENT,
DMA_ATTR_COPY_ALIGNMENT,
DMA_ATTR_MAX_BLOCK_COUNT,
};
/**
* @struct dma_block_config
* @brief DMA block configuration structure.
*
* Aside from source address, destination address, and block size many of these options are hardware
* and driver dependent.
*/
struct dma_block_config {
#ifdef CONFIG_DMA_64BIT
/** block starting address at source */
uint64_t source_address;
/** block starting address at destination */
uint64_t dest_address;
#else
/** block starting address at source */
uint32_t source_address;
/** block starting address at destination */
uint32_t dest_address;
#endif
/** Address adjustment at gather boundary */
uint32_t source_gather_interval;
/** Address adjustment at scatter boundary */
uint32_t dest_scatter_interval;
/** Continuous transfer count between scatter boundaries */
uint16_t dest_scatter_count;
/** Continuous transfer count between gather boundaries */
uint16_t source_gather_count;
/** Number of bytes to be transferred for this block */
uint32_t block_size;
/** Pointer to next block in a transfer list */
struct dma_block_config *next_block;
/** Enable source gathering when set to 1 */
uint16_t source_gather_en : 1;
/** Enable destination scattering when set to 1 */
uint16_t dest_scatter_en : 1;
/**
* Source address adjustment option
*
* - 0b00 increment
* - 0b01 decrement
* - 0b10 no change
*/
uint16_t source_addr_adj : 2;
/**
* Destination address adjustment
*
* - 0b00 increment
* - 0b01 decrement
* - 0b10 no change
*/
uint16_t dest_addr_adj : 2;
/** Reload source address at the end of block transfer */
uint16_t source_reload_en : 1;
/** Reload destination address at the end of block transfer */
uint16_t dest_reload_en : 1;
/** FIFO fill before starting transfer, HW specific meaning */
uint16_t fifo_mode_control : 4;
/**
* Transfer flow control mode
*
* - 0b0 source request service upon data availability
* - 0b1 source request postponed until destination request happens
*/
uint16_t flow_control_mode : 1;
uint16_t _reserved : 3;
};
/** The DMA callback event has occurred at the completion of a transfer list */
#define DMA_STATUS_COMPLETE 0
/** The DMA callback has occurred at the completion of a single transfer block in a transfer list */
#define DMA_STATUS_BLOCK 1
/**
* @typedef dma_callback_t
* @brief Callback function for DMA transfer completion
*
* If enabled, callback function will be invoked at transfer or block completion,
* or when an error happens.
* In circular mode, @p status indicates that the DMA device has reached either
* the end of the buffer (DMA_STATUS_COMPLETE) or a water mark (DMA_STATUS_BLOCK).
*
* @param dev Pointer to the DMA device calling the callback.
* @param user_data A pointer to some user data or NULL
* @param channel The channel number
* @param status Status of the transfer
* - DMA_STATUS_COMPLETE buffer fully consumed
* - DMA_STATUS_BLOCK buffer consumption reached a configured block
* or water mark
* - A negative errno otherwise
*/
typedef void (*dma_callback_t)(const struct device *dev, void *user_data,
uint32_t channel, int status);
/**
* @struct dma_config
* @brief DMA configuration structure.
*/
struct dma_config {
/** Which peripheral and direction, HW specific */
uint32_t dma_slot : 8;
/**
* Direction the transfers are occurring
*
* - 0b000 memory to memory,
* - 0b001 memory to peripheral,
* - 0b010 peripheral to memory,
* - 0b011 peripheral to peripheral,
* - 0b100 host to memory
* - 0b101 memory to host
* - others hardware specific
*/
uint32_t channel_direction : 3;
/**
* Completion callback enable
*
* - 0b0 callback invoked at transfer list completion only
* - 0b1 callback invoked at completion of each block
*/
uint32_t complete_callback_en : 1;
/**
* Error callback disable
*
* - 0b0 error callback enabled
* - 0b1 error callback disabled
*/
uint32_t error_callback_dis : 1;
/**
* Source handshake, HW specific
*
* - 0b0 HW
* - 0b1 SW
*/
uint32_t source_handshake : 1;
/**
* Destination handshake, HW specific
*
* - 0b0 HW
* - 0b1 SW
*/
uint32_t dest_handshake : 1;
/**
* Channel priority for arbitration, HW specific
*/
uint32_t channel_priority : 4;
/** Source chaining enable, HW specific */
uint32_t source_chaining_en : 1;
/** Destination chaining enable, HW specific */
uint32_t dest_chaining_en : 1;
/** Linked channel, HW specific */
uint32_t linked_channel : 7;
/** Cyclic transfer list, HW specific */
uint32_t cyclic : 1;
uint32_t _reserved : 3;
/** Width of source data (in bytes) */
uint32_t source_data_size : 16;
/** Width of destination data (in bytes) */
uint32_t dest_data_size : 16;
/** Source burst length in bytes */
uint32_t source_burst_length : 16;
/** Destination burst length in bytes */
uint32_t dest_burst_length : 16;
/** Number of blocks in transfer list */
uint32_t block_count;
/** Pointer to the first block in the transfer list */
struct dma_block_config *head_block;
/** Optional attached user data for callbacks */
void *user_data;
/** Optional callback for completion and error events */
dma_callback_t dma_callback;
};
/**
* DMA runtime status structure
*/
struct dma_status {
/** Is the current DMA transfer busy or idle */
bool busy;
/** Direction for the transfer */
enum dma_channel_direction dir;
/** Pending length to be transferred in bytes, HW specific */
uint32_t pending_length;
/** Available buffers space, HW specific */
uint32_t free;
/** Write position in circular DMA buffer, HW specific */
uint32_t write_position;
/** Read position in circular DMA buffer, HW specific */
uint32_t read_position;
/** Total copied, HW specific */
uint64_t total_copied;
};
/**
* DMA context structure
* Note: the dma_context shall be the first member
* of DMA client driver Data, got by dev->data
*/
struct dma_context {
/** magic code to identify the context */
int32_t magic;
/** number of dma channels */
int dma_channels;
/** atomic holding bit flags for each channel to mark as used/unused */
atomic_t *atomic;
};
/** Magic code to identify context content */
#define DMA_MAGIC 0x47494749
/**
* @cond INTERNAL_HIDDEN
*
* These are for internal use only, so skip these in
* public documentation.
*/
typedef int (*dma_api_config)(const struct device *dev, uint32_t channel,
struct dma_config *config);
#ifdef CONFIG_DMA_64BIT
typedef int (*dma_api_reload)(const struct device *dev, uint32_t channel,
uint64_t src, uint64_t dst, size_t size);
#else
typedef int (*dma_api_reload)(const struct device *dev, uint32_t channel,
uint32_t src, uint32_t dst, size_t size);
#endif
typedef int (*dma_api_start)(const struct device *dev, uint32_t channel);
typedef int (*dma_api_stop)(const struct device *dev, uint32_t channel);
typedef int (*dma_api_suspend)(const struct device *dev, uint32_t channel);
typedef int (*dma_api_resume)(const struct device *dev, uint32_t channel);
typedef int (*dma_api_get_status)(const struct device *dev, uint32_t channel,
struct dma_status *status);
typedef int (*dma_api_get_attribute)(const struct device *dev, uint32_t type, uint32_t *value);
/**
* @typedef dma_chan_filter
* @brief channel filter function call
*
* filter function that is used to find the matched internal dma channel
* provide by caller
*
* @param dev Pointer to the DMA device instance
* @param channel the channel id to use
* @param filter_param filter function parameter, can be NULL
*
* @retval True on filter matched otherwise return False.
*/
typedef bool (*dma_api_chan_filter)(const struct device *dev,
int channel, void *filter_param);
__subsystem struct dma_driver_api {
dma_api_config config;
dma_api_reload reload;
dma_api_start start;
dma_api_stop stop;
dma_api_suspend suspend;
dma_api_resume resume;
dma_api_get_status get_status;
dma_api_get_attribute get_attribute;
dma_api_chan_filter chan_filter;
};
/**
* @endcond
*/
/**
* @brief Configure individual channel for DMA transfer.
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel Numeric identification of the channel to configure
* @param config Data structure containing the intended configuration for the
* selected channel
*
* @retval 0 if successful.
* @retval Negative errno code if failure.
*/
static inline int dma_config(const struct device *dev, uint32_t channel,
struct dma_config *config)
{
const struct dma_driver_api *api =
(const struct dma_driver_api *)dev->api;
return api->config(dev, channel, config);
}
/**
* @brief Reload buffer(s) for a DMA channel
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel Numeric identification of the channel to configure
* selected channel
* @param src source address for the DMA transfer
* @param dst destination address for the DMA transfer
* @param size size of DMA transfer
*
* @retval 0 if successful.
* @retval Negative errno code if failure.
*/
#ifdef CONFIG_DMA_64BIT
static inline int dma_reload(const struct device *dev, uint32_t channel,
uint64_t src, uint64_t dst, size_t size)
#else
static inline int dma_reload(const struct device *dev, uint32_t channel,
uint32_t src, uint32_t dst, size_t size)
#endif
{
const struct dma_driver_api *api =
(const struct dma_driver_api *)dev->api;
if (api->reload) {
return api->reload(dev, channel, src, dst, size);
}
return -ENOSYS;
}
/**
* @brief Enables DMA channel and starts the transfer, the channel must be
* configured beforehand.
*
* Implementations must check the validity of the channel ID passed in and
* return -EINVAL if it is invalid.
*
* Start is allowed on channels that have already been started and must report
* success.
*
* @funcprops \isr_ok
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel Numeric identification of the channel where the transfer will
* be processed
*
* @retval 0 if successful.
* @retval Negative errno code if failure.
*/
__syscall int dma_start(const struct device *dev, uint32_t channel);
static inline int z_impl_dma_start(const struct device *dev, uint32_t channel)
{
const struct dma_driver_api *api =
(const struct dma_driver_api *)dev->api;
return api->start(dev, channel);
}
/**
* @brief Stops the DMA transfer and disables the channel.
*
* Implementations must check the validity of the channel ID passed in and
* return -EINVAL if it is invalid.
*
* Stop is allowed on channels that have already been stopped and must report
* success.
*
* @funcprops \isr_ok
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel Numeric identification of the channel where the transfer was
* being processed
*
* @retval 0 if successful.
* @retval Negative errno code if failure.
*/
__syscall int dma_stop(const struct device *dev, uint32_t channel);
static inline int z_impl_dma_stop(const struct device *dev, uint32_t channel)
{
const struct dma_driver_api *api =
(const struct dma_driver_api *)dev->api;
return api->stop(dev, channel);
}
/**
* @brief Suspend a DMA channel transfer
*
* Implementations must check the validity of the channel state and ID passed
* in and return -EINVAL if either are invalid.
*
* @funcprops \isr_ok
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel Numeric identification of the channel to suspend
*
* @retval 0 If successful.
* @retval -ENOSYS If not implemented.
* @retval -EINVAL If invalid channel id or state.
* @retval -errno Other negative errno code failure.
*/
__syscall int dma_suspend(const struct device *dev, uint32_t channel);
static inline int z_impl_dma_suspend(const struct device *dev, uint32_t channel)
{
const struct dma_driver_api *api = (const struct dma_driver_api *)dev->api;
if (api->suspend == NULL) {
return -ENOSYS;
}
return api->suspend(dev, channel);
}
/**
* @brief Resume a DMA channel transfer
*
* Implementations must check the validity of the channel state and ID passed
* in and return -EINVAL if either are invalid.
*
* @funcprops \isr_ok
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel Numeric identification of the channel to resume
*
* @retval 0 If successful.
* @retval -ENOSYS If not implemented
* @retval -EINVAL If invalid channel id or state.
* @retval -errno Other negative errno code failure.
*/
__syscall int dma_resume(const struct device *dev, uint32_t channel);
static inline int z_impl_dma_resume(const struct device *dev, uint32_t channel)
{
const struct dma_driver_api *api = (const struct dma_driver_api *)dev->api;
if (api->resume == NULL) {
return -ENOSYS;
}
return api->resume(dev, channel);
}
/**
* @brief request DMA channel.
*
* request DMA channel resources
* return -EINVAL if there is no valid channel available.
*
* @funcprops \isr_ok
*
* @param dev Pointer to the device structure for the driver instance.
* @param filter_param filter function parameter
*
* @retval dma channel if successful.
* @retval Negative errno code if failure.
*/
__syscall int dma_request_channel(const struct device *dev,
void *filter_param);
static inline int z_impl_dma_request_channel(const struct device *dev,
void *filter_param)
{
int i = 0;
int channel = -EINVAL;
const struct dma_driver_api *api =
(const struct dma_driver_api *)dev->api;
/* dma_context shall be the first one in dev data */
struct dma_context *dma_ctx = (struct dma_context *)dev->data;
if (dma_ctx->magic != DMA_MAGIC) {
return channel;
}
for (i = 0; i < dma_ctx->dma_channels; i++) {
if (!atomic_test_and_set_bit(dma_ctx->atomic, i)) {
if (api->chan_filter &&
!api->chan_filter(dev, i, filter_param)) {
atomic_clear_bit(dma_ctx->atomic, i);
continue;
}
channel = i;
break;
}
}
return channel;
}
/**
* @brief release DMA channel.
*
* release DMA channel resources
*
* @funcprops \isr_ok
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel channel number
*
*/
__syscall void dma_release_channel(const struct device *dev,
uint32_t channel);
static inline void z_impl_dma_release_channel(const struct device *dev,
uint32_t channel)
{
struct dma_context *dma_ctx = (struct dma_context *)dev->data;
if (dma_ctx->magic != DMA_MAGIC) {
return;
}
if ((int)channel < dma_ctx->dma_channels) {
atomic_clear_bit(dma_ctx->atomic, channel);
}
}
/**
* @brief DMA channel filter.
*
* filter channel by attribute
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel channel number
* @param filter_param filter attribute
*
* @retval Negative errno code if not support
*
*/
__syscall int dma_chan_filter(const struct device *dev,
int channel, void *filter_param);
static inline int z_impl_dma_chan_filter(const struct device *dev,
int channel, void *filter_param)
{
const struct dma_driver_api *api =
(const struct dma_driver_api *)dev->api;
if (api->chan_filter) {
return api->chan_filter(dev, channel, filter_param);
}
return -ENOSYS;
}
/**
* @brief get current runtime status of DMA transfer
*
* Implementations must check the validity of the channel ID passed in and
* return -EINVAL if it is invalid or -ENOSYS if not supported.
*
* @funcprops \isr_ok
*
* @param dev Pointer to the device structure for the driver instance.
* @param channel Numeric identification of the channel where the transfer was
* being processed
* @param stat a non-NULL dma_status object for storing DMA status
*
* @retval non-negative if successful.
* @retval Negative errno code if failure.
*/
static inline int dma_get_status(const struct device *dev, uint32_t channel,
struct dma_status *stat)
{
const struct dma_driver_api *api =
(const struct dma_driver_api *)dev->api;
if (api->get_status) {
return api->get_status(dev, channel, stat);
}
return -ENOSYS;
}
/**
* @brief get attribute of a dma controller
*
* This function allows to get a device specific static or runtime attribute like required address
* and size alignment of a buffer.
* Implementations must check the validity of the type passed in and
* return -EINVAL if it is invalid or -ENOSYS if not supported.
*
* @funcprops \isr_ok
*
* @param dev Pointer to the device structure for the driver instance.
* @param type Numeric identification of the attribute
* @param value A non-NULL pointer to the variable where the read value is to be placed
*
* @retval non-negative if successful.
* @retval Negative errno code if failure.
*/
static inline int dma_get_attribute(const struct device *dev, uint32_t type, uint32_t *value)
{
const struct dma_driver_api *api = (const struct dma_driver_api *)dev->api;
if (api->get_attribute) {
return api->get_attribute(dev, type, value);
}
return -ENOSYS;
}
/**
* @brief Look-up generic width index to be used in registers
*
* @warning This look-up works for most controllers, but *may* not work for
* yours. Ensure your controller expects the most common register
* bit values before using this convenience function. If your
* controller does not support these values, you will have to write
* your own look-up inside the controller driver.
*
* @param size: width of bus (in bytes)
*
* @retval common DMA index to be placed into registers.
*/
static inline uint32_t dma_width_index(uint32_t size)
{
/* Check boundaries (max supported width is 32 Bytes) */
if (size < 1 || size > 32) {
return 0; /* Zero is the default (8 Bytes) */
}
/* Ensure size is a power of 2 */
if (!is_power_of_two(size)) {
return 0; /* Zero is the default (8 Bytes) */
}
/* Convert to bit pattern for writing to a register */
return find_msb_set(size);
}
/**
* @brief Look-up generic burst index to be used in registers
*
* @warning This look-up works for most controllers, but *may* not work for
* yours. Ensure your controller expects the most common register
* bit values before using this convenience function. If your
* controller does not support these values, you will have to write
* your own look-up inside the controller driver.
*
* @param burst: number of bytes to be sent in a single burst
*
* @retval common DMA index to be placed into registers.
*/
static inline uint32_t dma_burst_index(uint32_t burst)
{
/* Check boundaries (max supported burst length is 256) */
if (burst < 1 || burst > 256) {
return 0; /* Zero is the default (1 burst length) */
}
/* Ensure burst is a power of 2 */
if (!(burst & (burst - 1))) {
return 0; /* Zero is the default (1 burst length) */
}
/* Convert to bit pattern for writing to a register */
return find_msb_set(burst);
}
/**
* @brief Get the device tree property describing the buffer address alignment
*
* Useful when statically defining or allocating buffers for DMA usage where
* memory alignment often matters.
*
* @param node Node identifier, e.g. DT_NODELABEL(dma_0)
* @return alignment Memory byte alignment required for DMA buffers
*/
#define DMA_BUF_ADDR_ALIGNMENT(node) DT_PROP(node, dma_buf_addr_alignment)
/**
* @brief Get the device tree property describing the buffer size alignment
*
* Useful when statically defining or allocating buffers for DMA usage where
* memory alignment often matters.
*
* @param node Node identifier, e.g. DT_NODELABEL(dma_0)
* @return alignment Memory byte alignment required for DMA buffers
*/
#define DMA_BUF_SIZE_ALIGNMENT(node) DT_PROP(node, dma_buf_size_alignment)
/**
* @brief Get the device tree property describing the minimal chunk of data possible to be copied
*
* @param node Node identifier, e.g. DT_NODELABEL(dma_0)
* @return minimal Minimal chunk of data possible to be copied
*/
#define DMA_COPY_ALIGNMENT(node) DT_PROP(node, dma_copy_alignment)
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/dma.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_DMA_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/dma.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 5,347 |
```objective-c
/**
* @file
*
* @brief Public APIs for Video.
*/
/*
*
*/
#ifndef ZEPHYR_INCLUDE_VIDEO_CONTROLS_H_
#define ZEPHYR_INCLUDE_VIDEO_CONTROLS_H_
/**
* @brief Video controls
* @defgroup video_controls Video Controls
* @ingroup io_interfaces
* @{
*/
#include <zephyr/device.h>
#include <stddef.h>
#include <zephyr/kernel.h>
#include <zephyr/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name Control classes
* @{
*/
#define VIDEO_CTRL_CLASS_GENERIC 0x00000000 /**< Generic class controls */
#define VIDEO_CTRL_CLASS_CAMERA 0x00010000 /**< Camera class controls */
#define VIDEO_CTRL_CLASS_MPEG 0x00020000 /**< MPEG-compression controls */
#define VIDEO_CTRL_CLASS_JPEG 0x00030000 /**< JPEG-compression controls */
#define VIDEO_CTRL_CLASS_VENDOR 0xFFFF0000 /**< Vendor-specific class controls */
/**
* @}
*/
/**
* @name Generic class control IDs
* @{
*/
/** Mirror the picture horizontally */
#define VIDEO_CID_HFLIP (VIDEO_CTRL_CLASS_GENERIC + 0)
/** Mirror the picture vertically */
#define VIDEO_CID_VFLIP (VIDEO_CTRL_CLASS_GENERIC + 1)
/**
* @}
*/
/**
* @name Camera class control IDs
* @{
*/
#define VIDEO_CID_CAMERA_EXPOSURE (VIDEO_CTRL_CLASS_CAMERA + 0)
#define VIDEO_CID_CAMERA_GAIN (VIDEO_CTRL_CLASS_CAMERA + 1)
#define VIDEO_CID_CAMERA_ZOOM (VIDEO_CTRL_CLASS_CAMERA + 2)
#define VIDEO_CID_CAMERA_BRIGHTNESS (VIDEO_CTRL_CLASS_CAMERA + 3)
#define VIDEO_CID_CAMERA_SATURATION (VIDEO_CTRL_CLASS_CAMERA + 4)
#define VIDEO_CID_CAMERA_WHITE_BAL (VIDEO_CTRL_CLASS_CAMERA + 5)
#define VIDEO_CID_CAMERA_CONTRAST (VIDEO_CTRL_CLASS_CAMERA + 6)
#define VIDEO_CID_CAMERA_COLORBAR (VIDEO_CTRL_CLASS_CAMERA + 7)
#define VIDEO_CID_CAMERA_QUALITY (VIDEO_CTRL_CLASS_CAMERA + 8)
/**
* @}
*/
#ifdef __cplusplus
}
#endif
/* Controls */
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_VIDEO_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/video-controls.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 468 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public API for retained memory drivers
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_RETAINED_MEM_
#define ZEPHYR_INCLUDE_DRIVERS_RETAINED_MEM_
#include <stdint.h>
#include <stddef.h>
#include <sys/types.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/types.h>
#include <zephyr/sys/math_extras.h>
#ifdef __cplusplus
extern "C" {
#endif
BUILD_ASSERT(!(sizeof(off_t) > sizeof(size_t)),
"Size of off_t must be equal or less than size of size_t");
/**
* @brief Retained memory driver interface
* @defgroup retained_mem_interface Retained memory driver interface
* @since 3.4
* @version 0.8.0
* @ingroup io_interfaces
* @{
*/
/**
* @typedef retained_mem_size_api
* @brief Callback API to get size of retained memory area.
* See retained_mem_size() for argument description.
*/
typedef ssize_t (*retained_mem_size_api)(const struct device *dev);
/**
* @typedef retained_mem_read_api
* @brief Callback API to read from retained memory area.
* See retained_mem_read() for argument description.
*/
typedef int (*retained_mem_read_api)(const struct device *dev, off_t offset, uint8_t *buffer,
size_t size);
/**
* @typedef retained_mem_write_api
* @brief Callback API to write to retained memory area.
* See retained_mem_write() for argument description.
*/
typedef int (*retained_mem_write_api)(const struct device *dev, off_t offset,
const uint8_t *buffer, size_t size);
/**
* @typedef retained_mem_clear_api
* @brief Callback API to clear retained memory area (reset all data to 0x00).
* See retained_mem_clear() for argument description.
*/
typedef int (*retained_mem_clear_api)(const struct device *dev);
/**
* @brief Retained memory driver API
* API which can be used by a device to store data in a retained memory area. Retained memory is
* memory that is retained while the device is powered but is lost when power to the device is
* lost (note that low power modes in some devices may clear the data also). This may be in a
* non-initialised RAM region, or in specific registers, but is not reset when a different
* application begins execution or the device is rebooted (without power loss). It must support
* byte-level reading and writing without a need to erase data before writing.
*
* Note that drivers must implement all functions, none of the functions are optional.
*/
__subsystem struct retained_mem_driver_api {
retained_mem_size_api size;
retained_mem_read_api read;
retained_mem_write_api write;
retained_mem_clear_api clear;
};
/**
* @brief Returns the size of the retained memory area.
*
* @param dev Retained memory device to use.
*
* @retval Positive value indicating size in bytes on success, else negative errno
* code.
*/
__syscall ssize_t retained_mem_size(const struct device *dev);
static inline ssize_t z_impl_retained_mem_size(const struct device *dev)
{
struct retained_mem_driver_api *api = (struct retained_mem_driver_api *)dev->api;
return api->size(dev);
}
/**
* @brief Reads data from the Retained memory area.
*
* @param dev Retained memory device to use.
* @param offset Offset to read data from.
* @param buffer Buffer to store read data in.
* @param size Size of data to read.
*
* @retval 0 on success else negative errno code.
*/
__syscall int retained_mem_read(const struct device *dev, off_t offset, uint8_t *buffer,
size_t size);
static inline int z_impl_retained_mem_read(const struct device *dev, off_t offset,
uint8_t *buffer, size_t size)
{
struct retained_mem_driver_api *api = (struct retained_mem_driver_api *)dev->api;
size_t area_size;
/* Validate user-supplied parameters */
if (size == 0) {
return 0;
}
area_size = api->size(dev);
if (offset < 0 || size > area_size || (area_size - size) < (size_t)offset) {
return -EINVAL;
}
return api->read(dev, offset, buffer, size);
}
/**
* @brief Writes data to the Retained memory area - underlying data does not need to
* be cleared prior to writing.
*
* @param dev Retained memory device to use.
* @param offset Offset to write data to.
* @param buffer Data to write.
* @param size Size of data to be written.
*
* @retval 0 on success else negative errno code.
*/
__syscall int retained_mem_write(const struct device *dev, off_t offset, const uint8_t *buffer,
size_t size);
static inline int z_impl_retained_mem_write(const struct device *dev, off_t offset,
const uint8_t *buffer, size_t size)
{
struct retained_mem_driver_api *api = (struct retained_mem_driver_api *)dev->api;
size_t area_size;
/* Validate user-supplied parameters */
if (size == 0) {
return 0;
}
area_size = api->size(dev);
if (offset < 0 || size > area_size || (area_size - size) < (size_t)offset) {
return -EINVAL;
}
return api->write(dev, offset, buffer, size);
}
/**
* @brief Clears data in the retained memory area by setting it to 0x00.
*
* @param dev Retained memory device to use.
*
* @retval 0 on success else negative errno code.
*/
__syscall int retained_mem_clear(const struct device *dev);
static inline int z_impl_retained_mem_clear(const struct device *dev)
{
struct retained_mem_driver_api *api = (struct retained_mem_driver_api *)dev->api;
return api->clear(dev);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/retained_mem.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_RETAINED_MEM_ */
``` | /content/code_sandbox/include/zephyr/drivers/retained_mem.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,347 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public APIs for UART drivers
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_UART_H_
#define ZEPHYR_INCLUDE_DRIVERS_UART_H_
/**
* @brief UART Interface
* @defgroup uart_interface UART Interface
* @since 1.0
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <stddef.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @brief Line control signals. */
enum uart_line_ctrl {
UART_LINE_CTRL_BAUD_RATE = BIT(0), /**< Baud rate */
UART_LINE_CTRL_RTS = BIT(1), /**< Request To Send (RTS) */
UART_LINE_CTRL_DTR = BIT(2), /**< Data Terminal Ready (DTR) */
UART_LINE_CTRL_DCD = BIT(3), /**< Data Carrier Detect (DCD) */
UART_LINE_CTRL_DSR = BIT(4), /**< Data Set Ready (DSR) */
};
/**
* @brief Reception stop reasons.
*
* Values that correspond to events or errors responsible for stopping
* receiving.
*/
enum uart_rx_stop_reason {
/** @brief Overrun error */
UART_ERROR_OVERRUN = (1 << 0),
/** @brief Parity error */
UART_ERROR_PARITY = (1 << 1),
/** @brief Framing error */
UART_ERROR_FRAMING = (1 << 2),
/**
* @brief Break interrupt
*
* A break interrupt was received. This happens when the serial input
* is held at a logic '0' state for longer than the sum of
* start time + data bits + parity + stop bits.
*/
UART_BREAK = (1 << 3),
/**
* @brief Collision error
*
* This error is raised when transmitted data does not match
* received data. Typically this is useful in scenarios where
* the TX and RX lines maybe connected together such as
* RS-485 half-duplex. This error is only valid on UARTs that
* support collision checking.
*/
UART_ERROR_COLLISION = (1 << 4),
/** @brief Noise error */
UART_ERROR_NOISE = (1 << 5),
};
/** @brief Parity modes */
enum uart_config_parity {
UART_CFG_PARITY_NONE, /**< No parity */
UART_CFG_PARITY_ODD, /**< Odd parity */
UART_CFG_PARITY_EVEN, /**< Even parity */
UART_CFG_PARITY_MARK, /**< Mark parity */
UART_CFG_PARITY_SPACE, /**< Space parity */
};
/** @brief Number of stop bits. */
enum uart_config_stop_bits {
UART_CFG_STOP_BITS_0_5, /**< 0.5 stop bit */
UART_CFG_STOP_BITS_1, /**< 1 stop bit */
UART_CFG_STOP_BITS_1_5, /**< 1.5 stop bits */
UART_CFG_STOP_BITS_2, /**< 2 stop bits */
};
/** @brief Number of data bits. */
enum uart_config_data_bits {
UART_CFG_DATA_BITS_5, /**< 5 data bits */
UART_CFG_DATA_BITS_6, /**< 6 data bits */
UART_CFG_DATA_BITS_7, /**< 7 data bits */
UART_CFG_DATA_BITS_8, /**< 8 data bits */
UART_CFG_DATA_BITS_9, /**< 9 data bits */
};
/**
* @brief Hardware flow control options.
*
* With flow control set to none, any operations related to flow control
* signals can be managed by user with uart_line_ctrl functions.
* In other cases, flow control is managed by hardware/driver.
*/
enum uart_config_flow_control {
UART_CFG_FLOW_CTRL_NONE, /**< No flow control */
UART_CFG_FLOW_CTRL_RTS_CTS, /**< RTS/CTS flow control */
UART_CFG_FLOW_CTRL_DTR_DSR, /**< DTR/DSR flow control */
UART_CFG_FLOW_CTRL_RS485, /**< RS485 flow control */
};
/**
* @brief UART controller configuration structure
*/
struct uart_config {
uint32_t baudrate; /**< Baudrate setting in bps */
uint8_t parity; /**< Parity bit, use @ref uart_config_parity */
uint8_t stop_bits; /**< Stop bits, use @ref uart_config_stop_bits */
uint8_t data_bits; /**< Data bits, use @ref uart_config_data_bits */
uint8_t flow_ctrl; /**< Flow control setting, use @ref uart_config_flow_control */
};
/**
* @defgroup uart_interrupt Interrupt-driven UART API
* @{
*/
/**
* @brief Define the application callback function signature for
* uart_irq_callback_user_data_set() function.
*
* @param dev UART device instance.
* @param user_data Arbitrary user data.
*/
typedef void (*uart_irq_callback_user_data_t)(const struct device *dev,
void *user_data);
/**
* @brief For configuring IRQ on each individual UART device.
*
* @param dev UART device instance.
*/
typedef void (*uart_irq_config_func_t)(const struct device *dev);
/**
* @}
*
* @defgroup uart_async Async UART API
* @since 1.14
* @version 0.8.0
* @{
*/
/**
* @brief Types of events passed to callback in UART_ASYNC_API
*
* Receiving:
* 1. To start receiving, uart_rx_enable has to be called with first buffer
* 2. When receiving starts to current buffer,
* #UART_RX_BUF_REQUEST will be generated, in response to that user can
* either:
*
* - Provide second buffer using uart_rx_buf_rsp, when first buffer is
* filled, receiving will automatically start to second buffer.
* - Ignore the event, this way when current buffer is filled
* #UART_RX_RDY event will be generated and receiving will be stopped.
*
* 3. If some data was received and timeout occurred #UART_RX_RDY event will be
* generated. It can happen multiples times for the same buffer. RX timeout
* is counted from last byte received i.e. if no data was received, there
* won't be any timeout event.
* 4. #UART_RX_BUF_RELEASED event will be generated when the current buffer is
* no longer used by the driver. It will immediately follow #UART_RX_RDY event.
* Depending on the implementation buffer may be released when it is completely
* or partially filled.
* 5. If there was second buffer provided, it will become current buffer and
* we start again at point 2.
* If no second buffer was specified receiving is stopped and
* #UART_RX_DISABLED event is generated. After that whole process can be
* repeated.
*
* Any time during reception #UART_RX_STOPPED event can occur. if there is any
* data received, #UART_RX_RDY event will be generated. It will be followed by
* #UART_RX_BUF_RELEASED event for every buffer currently passed to driver and
* finally by #UART_RX_DISABLED event.
*
* Receiving can be disabled using uart_rx_disable, after calling that
* function, if there is any data received, #UART_RX_RDY event will be
* generated. #UART_RX_BUF_RELEASED event will be generated for every buffer
* currently passed to driver and finally #UART_RX_DISABLED event will occur.
*
* Transmitting:
* 1. Transmitting starts by uart_tx function.
* 2. If whole buffer was transmitted #UART_TX_DONE is generated. If timeout
* occurred #UART_TX_ABORTED will be generated.
*
* Transmitting can be aborted using @ref uart_tx_abort, after calling that
* function #UART_TX_ABORTED event will be generated.
*
*/
enum uart_event_type {
/** @brief Whole TX buffer was transmitted. */
UART_TX_DONE,
/**
* @brief Transmitting aborted due to timeout or uart_tx_abort call
*
* When flow control is enabled, there is a possibility that TX transfer
* won't finish in the allotted time. Some data may have been
* transferred, information about it can be found in event data.
*/
UART_TX_ABORTED,
/**
* @brief Received data is ready for processing.
*
* This event is generated in the following cases:
* - When RX timeout occurred, and data was stored in provided buffer.
* This can happen multiple times in the same buffer.
* - When provided buffer is full.
* - After uart_rx_disable().
* - After stopping due to external event (#UART_RX_STOPPED).
*/
UART_RX_RDY,
/**
* @brief Driver requests next buffer for continuous reception.
*
* This event is triggered when receiving has started for a new buffer,
* i.e. it's time to provide a next buffer for a seamless switchover to
* it. For continuous reliable receiving, user should provide another RX
* buffer in response to this event, using uart_rx_buf_rsp function
*
* If uart_rx_buf_rsp is not called before current buffer
* is filled up, receiving will stop.
*/
UART_RX_BUF_REQUEST,
/**
* @brief Buffer is no longer used by UART driver.
*/
UART_RX_BUF_RELEASED,
/**
* @brief RX has been disabled and can be reenabled.
*
* This event is generated whenever receiver has been stopped, disabled
* or finished its operation and can be enabled again using
* uart_rx_enable
*/
UART_RX_DISABLED,
/**
* @brief RX has stopped due to external event.
*
* Reason is one of uart_rx_stop_reason.
*/
UART_RX_STOPPED,
};
/** @brief UART TX event data. */
struct uart_event_tx {
/** @brief Pointer to current buffer. */
const uint8_t *buf;
/** @brief Number of bytes sent. */
size_t len;
};
/**
* @brief UART RX event data.
*
* The data represented by the event is stored in rx.buf[rx.offset] to
* rx.buf[rx.offset+rx.len]. That is, the length is relative to the offset.
*/
struct uart_event_rx {
/** @brief Pointer to current buffer. */
uint8_t *buf;
/** @brief Currently received data offset in bytes. */
size_t offset;
/** @brief Number of new bytes received. */
size_t len;
};
/** @brief UART RX buffer released event data. */
struct uart_event_rx_buf {
/** @brief Pointer to buffer that is no longer in use. */
uint8_t *buf;
};
/** @brief UART RX stopped data. */
struct uart_event_rx_stop {
/** @brief Reason why receiving stopped */
enum uart_rx_stop_reason reason;
/** @brief Last received data. */
struct uart_event_rx data;
};
/** @brief Structure containing information about current event. */
struct uart_event {
/** @brief Type of event */
enum uart_event_type type;
/** @brief Event data */
union uart_event_data {
/** @brief #UART_TX_DONE and #UART_TX_ABORTED events data. */
struct uart_event_tx tx;
/** @brief #UART_RX_RDY event data. */
struct uart_event_rx rx;
/** @brief #UART_RX_BUF_RELEASED event data. */
struct uart_event_rx_buf rx_buf;
/** @brief #UART_RX_STOPPED event data. */
struct uart_event_rx_stop rx_stop;
} data;
};
/**
* @typedef uart_callback_t
* @brief Define the application callback function signature for
* uart_callback_set() function.
*
* @param dev UART device instance.
* @param evt Pointer to uart_event instance.
* @param user_data Pointer to data specified by user.
*/
typedef void (*uart_callback_t)(const struct device *dev,
struct uart_event *evt, void *user_data);
/**
* @}
*/
/**
* @cond INTERNAL_HIDDEN
*
* For internal driver use only, skip these in public documentation.
*/
/** @brief Driver API structure. */
__subsystem struct uart_driver_api {
#ifdef CONFIG_UART_ASYNC_API
int (*callback_set)(const struct device *dev,
uart_callback_t callback,
void *user_data);
int (*tx)(const struct device *dev, const uint8_t *buf, size_t len,
int32_t timeout);
int (*tx_abort)(const struct device *dev);
int (*rx_enable)(const struct device *dev, uint8_t *buf, size_t len,
int32_t timeout);
int (*rx_buf_rsp)(const struct device *dev, uint8_t *buf, size_t len);
int (*rx_disable)(const struct device *dev);
#ifdef CONFIG_UART_WIDE_DATA
int (*tx_u16)(const struct device *dev, const uint16_t *buf,
size_t len, int32_t timeout);
int (*rx_enable_u16)(const struct device *dev, uint16_t *buf,
size_t len, int32_t timeout);
int (*rx_buf_rsp_u16)(const struct device *dev, uint16_t *buf,
size_t len);
#endif
#endif
/** Console I/O function */
int (*poll_in)(const struct device *dev, unsigned char *p_char);
void (*poll_out)(const struct device *dev, unsigned char out_char);
#ifdef CONFIG_UART_WIDE_DATA
int (*poll_in_u16)(const struct device *dev, uint16_t *p_u16);
void (*poll_out_u16)(const struct device *dev, uint16_t out_u16);
#endif
/** Console I/O function */
int (*err_check)(const struct device *dev);
#ifdef CONFIG_UART_USE_RUNTIME_CONFIGURE
/** UART configuration functions */
int (*configure)(const struct device *dev,
const struct uart_config *cfg);
int (*config_get)(const struct device *dev, struct uart_config *cfg);
#endif
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
/** Interrupt driven FIFO fill function */
int (*fifo_fill)(const struct device *dev, const uint8_t *tx_data,
int len);
#ifdef CONFIG_UART_WIDE_DATA
int (*fifo_fill_u16)(const struct device *dev, const uint16_t *tx_data,
int len);
#endif
/** Interrupt driven FIFO read function */
int (*fifo_read)(const struct device *dev, uint8_t *rx_data,
const int size);
#ifdef CONFIG_UART_WIDE_DATA
int (*fifo_read_u16)(const struct device *dev, uint16_t *rx_data,
const int size);
#endif
/** Interrupt driven transfer enabling function */
void (*irq_tx_enable)(const struct device *dev);
/** Interrupt driven transfer disabling function */
void (*irq_tx_disable)(const struct device *dev);
/** Interrupt driven transfer ready function */
int (*irq_tx_ready)(const struct device *dev);
/** Interrupt driven receiver enabling function */
void (*irq_rx_enable)(const struct device *dev);
/** Interrupt driven receiver disabling function */
void (*irq_rx_disable)(const struct device *dev);
/** Interrupt driven transfer complete function */
int (*irq_tx_complete)(const struct device *dev);
/** Interrupt driven receiver ready function */
int (*irq_rx_ready)(const struct device *dev);
/** Interrupt driven error enabling function */
void (*irq_err_enable)(const struct device *dev);
/** Interrupt driven error disabling function */
void (*irq_err_disable)(const struct device *dev);
/** Interrupt driven pending status function */
int (*irq_is_pending)(const struct device *dev);
/** Interrupt driven interrupt update function */
int (*irq_update)(const struct device *dev);
/** Set the irq callback function */
void (*irq_callback_set)(const struct device *dev,
uart_irq_callback_user_data_t cb,
void *user_data);
#endif
#ifdef CONFIG_UART_LINE_CTRL
int (*line_ctrl_set)(const struct device *dev, uint32_t ctrl,
uint32_t val);
int (*line_ctrl_get)(const struct device *dev, uint32_t ctrl,
uint32_t *val);
#endif
#ifdef CONFIG_UART_DRV_CMD
int (*drv_cmd)(const struct device *dev, uint32_t cmd, uint32_t p);
#endif
};
/** @endcond */
/**
* @brief Check whether an error was detected.
*
* @param dev UART device instance.
*
* @retval 0 If no error was detected.
* @retval err Error flags as defined in @ref uart_rx_stop_reason
* @retval -ENOSYS If not implemented.
*/
__syscall int uart_err_check(const struct device *dev);
static inline int z_impl_uart_err_check(const struct device *dev)
{
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->err_check == NULL) {
return -ENOSYS;
}
return api->err_check(dev);
}
/**
* @defgroup uart_polling Polling UART API
* @{
*/
/**
* @brief Read a character from the device for input.
*
* This routine checks if the receiver has valid data. When the
* receiver has valid data, it reads a character from the device,
* stores to the location pointed to by p_char, and returns 0 to the
* calling thread. It returns -1, otherwise. This function is a
* non-blocking call.
*
* @param dev UART device instance.
* @param p_char Pointer to character.
*
* @retval 0 If a character arrived.
* @retval -1 If no character was available to read (i.e. the UART
* input buffer was empty).
* @retval -ENOSYS If the operation is not implemented.
* @retval -EBUSY If async reception was enabled using @ref uart_rx_enable
*/
__syscall int uart_poll_in(const struct device *dev, unsigned char *p_char);
static inline int z_impl_uart_poll_in(const struct device *dev,
unsigned char *p_char)
{
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->poll_in == NULL) {
return -ENOSYS;
}
return api->poll_in(dev, p_char);
}
/**
* @brief Read a 16-bit datum from the device for input.
*
* This routine checks if the receiver has valid data. When the
* receiver has valid data, it reads a 16-bit datum from the device,
* stores to the location pointed to by p_u16, and returns 0 to the
* calling thread. It returns -1, otherwise. This function is a
* non-blocking call.
*
* @param dev UART device instance.
* @param p_u16 Pointer to 16-bit data.
*
* @retval 0 If data arrived.
* @retval -1 If no data was available to read (i.e., the UART
* input buffer was empty).
* @retval -ENOTSUP If API is not enabled.
* @retval -ENOSYS If the function is not implemented.
* @retval -EBUSY If async reception was enabled using @ref uart_rx_enable
*/
__syscall int uart_poll_in_u16(const struct device *dev, uint16_t *p_u16);
static inline int z_impl_uart_poll_in_u16(const struct device *dev,
uint16_t *p_u16)
{
#ifdef CONFIG_UART_WIDE_DATA
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->poll_in_u16 == NULL) {
return -ENOSYS;
}
return api->poll_in_u16(dev, p_u16);
#else
ARG_UNUSED(dev);
ARG_UNUSED(p_u16);
return -ENOTSUP;
#endif
}
/**
* @brief Write a character to the device for output.
*
* This routine checks if the transmitter is full. When the
* transmitter is not full, it writes a character to the data
* register. It waits and blocks the calling thread, otherwise. This
* function is a blocking call.
*
* To send a character when hardware flow control is enabled, the handshake
* signal CTS must be asserted.
*
* @param dev UART device instance.
* @param out_char Character to send.
*/
__syscall void uart_poll_out(const struct device *dev,
unsigned char out_char);
static inline void z_impl_uart_poll_out(const struct device *dev,
unsigned char out_char)
{
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
api->poll_out(dev, out_char);
}
/**
* @brief Write a 16-bit datum to the device for output.
*
* This routine checks if the transmitter is full. When the
* transmitter is not full, it writes a 16-bit datum to the data
* register. It waits and blocks the calling thread, otherwise. This
* function is a blocking call.
*
* To send a datum when hardware flow control is enabled, the handshake
* signal CTS must be asserted.
*
* @param dev UART device instance.
* @param out_u16 Wide data to send.
*/
__syscall void uart_poll_out_u16(const struct device *dev, uint16_t out_u16);
static inline void z_impl_uart_poll_out_u16(const struct device *dev,
uint16_t out_u16)
{
#ifdef CONFIG_UART_WIDE_DATA
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
api->poll_out_u16(dev, out_u16);
#else
ARG_UNUSED(dev);
ARG_UNUSED(out_u16);
#endif
}
/**
* @}
*/
/**
* @brief Set UART configuration.
*
* Sets UART configuration using data from *cfg.
*
* @param dev UART device instance.
* @param cfg UART configuration structure.
*
* @retval 0 If successful.
* @retval -errno Negative errno code in case of failure.
* @retval -ENOSYS If configuration is not supported by device
* or driver does not support setting configuration in runtime.
* @retval -ENOTSUP If API is not enabled.
*/
__syscall int uart_configure(const struct device *dev,
const struct uart_config *cfg);
static inline int z_impl_uart_configure(const struct device *dev,
const struct uart_config *cfg)
{
#ifdef CONFIG_UART_USE_RUNTIME_CONFIGURE
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->configure == NULL) {
return -ENOSYS;
}
return api->configure(dev, cfg);
#else
ARG_UNUSED(dev);
ARG_UNUSED(cfg);
return -ENOTSUP;
#endif
}
/**
* @brief Get UART configuration.
*
* Stores current UART configuration to *cfg, can be used to retrieve initial
* configuration after device was initialized using data from DTS.
*
* @param dev UART device instance.
* @param cfg UART configuration structure.
*
* @retval 0 If successful.
* @retval -errno Negative errno code in case of failure.
* @retval -ENOSYS If driver does not support getting current configuration.
* @retval -ENOTSUP If API is not enabled.
*/
__syscall int uart_config_get(const struct device *dev,
struct uart_config *cfg);
static inline int z_impl_uart_config_get(const struct device *dev,
struct uart_config *cfg)
{
#ifdef CONFIG_UART_USE_RUNTIME_CONFIGURE
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->config_get == NULL) {
return -ENOSYS;
}
return api->config_get(dev, cfg);
#else
ARG_UNUSED(dev);
ARG_UNUSED(cfg);
return -ENOTSUP;
#endif
}
/**
* @addtogroup uart_interrupt
* @{
*/
/**
* @brief Fill FIFO with data.
*
* @details This function is expected to be called from UART
* interrupt handler (ISR), if uart_irq_tx_ready() returns true.
* Result of calling this function not from an ISR is undefined
* (hardware-dependent). Likewise, *not* calling this function
* from an ISR if uart_irq_tx_ready() returns true may lead to
* undefined behavior, e.g. infinite interrupt loops. It's
* mandatory to test return value of this function, as different
* hardware has different FIFO depth (oftentimes just 1).
*
* @param dev UART device instance.
* @param tx_data Data to transmit.
* @param size Number of bytes to send.
*
* @return Number of bytes sent.
* @retval -ENOSYS if this function is not supported
* @retval -ENOTSUP If API is not enabled.
*/
static inline int uart_fifo_fill(const struct device *dev,
const uint8_t *tx_data,
int size)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->fifo_fill == NULL) {
return -ENOSYS;
}
return api->fifo_fill(dev, tx_data, size);
#else
ARG_UNUSED(dev);
ARG_UNUSED(tx_data);
ARG_UNUSED(size);
return -ENOTSUP;
#endif
}
/**
* @brief Fill FIFO with wide data.
*
* @details This function is expected to be called from UART
* interrupt handler (ISR), if uart_irq_tx_ready() returns true.
* Result of calling this function not from an ISR is undefined
* (hardware-dependent). Likewise, *not* calling this function
* from an ISR if uart_irq_tx_ready() returns true may lead to
* undefined behavior, e.g. infinite interrupt loops. It's
* mandatory to test return value of this function, as different
* hardware has different FIFO depth (oftentimes just 1).
*
* @param dev UART device instance.
* @param tx_data Wide data to transmit.
* @param size Number of datum to send.
*
* @return Number of datum sent.
* @retval -ENOSYS If this function is not implemented
* @retval -ENOTSUP If API is not enabled.
*/
static inline int uart_fifo_fill_u16(const struct device *dev,
const uint16_t *tx_data,
int size)
{
#if defined(CONFIG_UART_INTERRUPT_DRIVEN) && defined(CONFIG_UART_WIDE_DATA)
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->fifo_fill_u16 == NULL) {
return -ENOSYS;
}
return api->fifo_fill_u16(dev, tx_data, size);
#else
ARG_UNUSED(dev);
ARG_UNUSED(tx_data);
ARG_UNUSED(size);
return -ENOTSUP;
#endif
}
/**
* @brief Read data from FIFO.
*
* @details This function is expected to be called from UART
* interrupt handler (ISR), if uart_irq_rx_ready() returns true.
* Result of calling this function not from an ISR is undefined
* (hardware-dependent). It's unspecified whether "RX ready"
* condition as returned by uart_irq_rx_ready() is level- or
* edge- triggered. That means that once uart_irq_rx_ready() is
* detected, uart_fifo_read() must be called until it reads all
* available data in the FIFO (i.e. until it returns less data
* than was requested).
*
* @param dev UART device instance.
* @param rx_data Data container.
* @param size Container size.
*
* @return Number of bytes read.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
*/
static inline int uart_fifo_read(const struct device *dev, uint8_t *rx_data,
const int size)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->fifo_read == NULL) {
return -ENOSYS;
}
return api->fifo_read(dev, rx_data, size);
#else
ARG_UNUSED(dev);
ARG_UNUSED(rx_data);
ARG_UNUSED(size);
return -ENOTSUP;
#endif
}
/**
* @brief Read wide data from FIFO.
*
* @details This function is expected to be called from UART
* interrupt handler (ISR), if uart_irq_rx_ready() returns true.
* Result of calling this function not from an ISR is undefined
* (hardware-dependent). It's unspecified whether "RX ready"
* condition as returned by uart_irq_rx_ready() is level- or
* edge- triggered. That means that once uart_irq_rx_ready() is
* detected, uart_fifo_read() must be called until it reads all
* available data in the FIFO (i.e. until it returns less data
* than was requested).
*
* @param dev UART device instance.
* @param rx_data Wide data container.
* @param size Container size.
*
* @return Number of datum read.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
*/
static inline int uart_fifo_read_u16(const struct device *dev,
uint16_t *rx_data,
const int size)
{
#if defined(CONFIG_UART_INTERRUPT_DRIVEN) && defined(CONFIG_UART_WIDE_DATA)
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->fifo_read_u16 == NULL) {
return -ENOSYS;
}
return api->fifo_read_u16(dev, rx_data, size);
#else
ARG_UNUSED(dev);
ARG_UNUSED(rx_data);
ARG_UNUSED(size);
return -ENOTSUP;
#endif
}
/**
* @brief Enable TX interrupt in IER.
*
* @param dev UART device instance.
*/
__syscall void uart_irq_tx_enable(const struct device *dev);
static inline void z_impl_uart_irq_tx_enable(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_tx_enable != NULL) {
api->irq_tx_enable(dev);
}
#else
ARG_UNUSED(dev);
#endif
}
/**
* @brief Disable TX interrupt in IER.
*
* @param dev UART device instance.
*/
__syscall void uart_irq_tx_disable(const struct device *dev);
static inline void z_impl_uart_irq_tx_disable(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_tx_disable != NULL) {
api->irq_tx_disable(dev);
}
#else
ARG_UNUSED(dev);
#endif
}
/**
* @brief Check if UART TX buffer can accept a new char
*
* @details Check if UART TX buffer can accept at least one character
* for transmission (i.e. uart_fifo_fill() will succeed and return
* non-zero). This function must be called in a UART interrupt
* handler, or its result is undefined. Before calling this function
* in the interrupt handler, uart_irq_update() must be called once per
* the handler invocation.
*
* @param dev UART device instance.
*
* @retval 1 If TX interrupt is enabled and at least one char can be
* written to UART.
* @retval 0 If device is not ready to write a new byte.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
*/
static inline int uart_irq_tx_ready(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_tx_ready == NULL) {
return -ENOSYS;
}
return api->irq_tx_ready(dev);
#else
ARG_UNUSED(dev);
return -ENOTSUP;
#endif
}
/**
* @brief Enable RX interrupt.
*
* @param dev UART device instance.
*/
__syscall void uart_irq_rx_enable(const struct device *dev);
static inline void z_impl_uart_irq_rx_enable(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_rx_enable != NULL) {
api->irq_rx_enable(dev);
}
#else
ARG_UNUSED(dev);
#endif
}
/**
* @brief Disable RX interrupt.
*
* @param dev UART device instance.
*/
__syscall void uart_irq_rx_disable(const struct device *dev);
static inline void z_impl_uart_irq_rx_disable(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_rx_disable != NULL) {
api->irq_rx_disable(dev);
}
#else
ARG_UNUSED(dev);
#endif
}
/**
* @brief Check if UART TX block finished transmission
*
* @details Check if any outgoing data buffered in UART TX block was
* fully transmitted and TX block is idle. When this condition is
* true, UART device (or whole system) can be power off. Note that
* this function is *not* useful to check if UART TX can accept more
* data, use uart_irq_tx_ready() for that. This function must be called
* in a UART interrupt handler, or its result is undefined. Before
* calling this function in the interrupt handler, uart_irq_update()
* must be called once per the handler invocation.
*
* @param dev UART device instance.
*
* @retval 1 If nothing remains to be transmitted.
* @retval 0 If transmission is not completed.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
*/
static inline int uart_irq_tx_complete(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_tx_complete == NULL) {
return -ENOSYS;
}
return api->irq_tx_complete(dev);
#else
ARG_UNUSED(dev);
return -ENOTSUP;
#endif
}
/**
* @brief Check if UART RX buffer has a received char
*
* @details Check if UART RX buffer has at least one pending character
* (i.e. uart_fifo_read() will succeed and return non-zero). This function
* must be called in a UART interrupt handler, or its result is undefined.
* Before calling this function in the interrupt handler, uart_irq_update()
* must be called once per the handler invocation. It's unspecified whether
* condition as returned by this function is level- or edge- triggered (i.e.
* if this function returns true when RX FIFO is non-empty, or when a new
* char was received since last call to it). See description of
* uart_fifo_read() for implication of this.
*
* @param dev UART device instance.
*
* @retval 1 If a received char is ready.
* @retval 0 If a received char is not ready.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
*/
static inline int uart_irq_rx_ready(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_rx_ready == NULL) {
return -ENOSYS;
}
return api->irq_rx_ready(dev);
#else
ARG_UNUSED(dev);
return -ENOTSUP;
#endif
}
/**
* @brief Enable error interrupt.
*
* @param dev UART device instance.
*/
__syscall void uart_irq_err_enable(const struct device *dev);
static inline void z_impl_uart_irq_err_enable(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_err_enable) {
api->irq_err_enable(dev);
}
#else
ARG_UNUSED(dev);
#endif
}
/**
* @brief Disable error interrupt.
*
* @param dev UART device instance.
*/
__syscall void uart_irq_err_disable(const struct device *dev);
static inline void z_impl_uart_irq_err_disable(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_err_disable) {
api->irq_err_disable(dev);
}
#else
ARG_UNUSED(dev);
#endif
}
/**
* @brief Check if any IRQs is pending.
*
* @param dev UART device instance.
*
* @retval 1 If an IRQ is pending.
* @retval 0 If an IRQ is not pending.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
*/
__syscall int uart_irq_is_pending(const struct device *dev);
static inline int z_impl_uart_irq_is_pending(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_is_pending == NULL) {
return -ENOSYS;
}
return api->irq_is_pending(dev);
#else
ARG_UNUSED(dev);
return -ENOTSUP;
#endif
}
/**
* @brief Start processing interrupts in ISR.
*
* This function should be called the first thing in the ISR. Calling
* uart_irq_rx_ready(), uart_irq_tx_ready(), uart_irq_tx_complete()
* allowed only after this.
*
* The purpose of this function is:
*
* * For devices with auto-acknowledge of interrupt status on register
* read to cache the value of this register (rx_ready, etc. then use
* this case).
* * For devices with explicit acknowledgment of interrupts, to ack
* any pending interrupts and likewise to cache the original value.
* * For devices with implicit acknowledgment, this function will be
* empty. But the ISR must perform the actions needs to ack the
* interrupts (usually, call uart_fifo_read() on rx_ready, and
* uart_fifo_fill() on tx_ready).
*
* @param dev UART device instance.
*
* @retval 1 On success.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
*/
__syscall int uart_irq_update(const struct device *dev);
static inline int z_impl_uart_irq_update(const struct device *dev)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->irq_update == NULL) {
return -ENOSYS;
}
return api->irq_update(dev);
#else
ARG_UNUSED(dev);
return -ENOTSUP;
#endif
}
/**
* @brief Set the IRQ callback function pointer.
*
* This sets up the callback for IRQ. When an IRQ is triggered,
* the specified function will be called with specified user data.
* See description of uart_irq_update() for the requirements on ISR.
*
* @param dev UART device instance.
* @param cb Pointer to the callback function.
* @param user_data Data to pass to callback function.
*
* @retval 0 On success.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
*/
static inline int uart_irq_callback_user_data_set(const struct device *dev,
uart_irq_callback_user_data_t cb,
void *user_data)
{
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if ((api != NULL) && (api->irq_callback_set != NULL)) {
api->irq_callback_set(dev, cb, user_data);
return 0;
} else {
return -ENOSYS;
}
#else
ARG_UNUSED(dev);
ARG_UNUSED(cb);
ARG_UNUSED(user_data);
return -ENOTSUP;
#endif
}
/**
* @brief Set the IRQ callback function pointer (legacy).
*
* This sets up the callback for IRQ. When an IRQ is triggered,
* the specified function will be called with the device pointer.
*
* @param dev UART device instance.
* @param cb Pointer to the callback function.
*
* @retval 0 On success.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
*/
static inline int uart_irq_callback_set(const struct device *dev,
uart_irq_callback_user_data_t cb)
{
return uart_irq_callback_user_data_set(dev, cb, NULL);
}
/**
* @}
*/
/**
* @addtogroup uart_async
* @{
*/
/**
* @brief Set event handler function.
*
* Since it is mandatory to set callback to use other asynchronous functions,
* it can be used to detect if the device supports asynchronous API. Remaining
* API does not have that detection.
*
* @param dev UART device instance.
* @param callback Event handler.
* @param user_data Data to pass to event handler function.
*
* @retval 0 If successful.
* @retval -ENOSYS If not supported by the device.
* @retval -ENOTSUP If API not enabled.
*/
static inline int uart_callback_set(const struct device *dev,
uart_callback_t callback,
void *user_data)
{
#ifdef CONFIG_UART_ASYNC_API
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->callback_set == NULL) {
return -ENOSYS;
}
return api->callback_set(dev, callback, user_data);
#else
ARG_UNUSED(dev);
ARG_UNUSED(callback);
ARG_UNUSED(user_data);
return -ENOTSUP;
#endif
}
/**
* @brief Send given number of bytes from buffer through UART.
*
* Function returns immediately and event handler,
* set using @ref uart_callback_set, is called after transfer is finished.
*
* @param dev UART device instance.
* @param buf Pointer to transmit buffer.
* @param len Length of transmit buffer.
* @param timeout Timeout in microseconds. Valid only if flow control is
* enabled. @ref SYS_FOREVER_US disables timeout.
*
* @retval 0 If successful.
* @retval -ENOTSUP If API is not enabled.
* @retval -EBUSY If There is already an ongoing transfer.
* @retval -errno Other negative errno value in case of failure.
*/
__syscall int uart_tx(const struct device *dev, const uint8_t *buf,
size_t len,
int32_t timeout);
static inline int z_impl_uart_tx(const struct device *dev, const uint8_t *buf,
size_t len, int32_t timeout)
{
#ifdef CONFIG_UART_ASYNC_API
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
return api->tx(dev, buf, len, timeout);
#else
ARG_UNUSED(dev);
ARG_UNUSED(buf);
ARG_UNUSED(len);
ARG_UNUSED(timeout);
return -ENOTSUP;
#endif
}
/**
* @brief Send given number of datum from buffer through UART.
*
* Function returns immediately and event handler,
* set using @ref uart_callback_set, is called after transfer is finished.
*
* @param dev UART device instance.
* @param buf Pointer to wide data transmit buffer.
* @param len Length of wide data transmit buffer.
* @param timeout Timeout in milliseconds. Valid only if flow control is
* enabled. @ref SYS_FOREVER_MS disables timeout.
*
* @retval 0 If successful.
* @retval -ENOTSUP If API is not enabled.
* @retval -EBUSY If there is already an ongoing transfer.
* @retval -errno Other negative errno value in case of failure.
*/
__syscall int uart_tx_u16(const struct device *dev, const uint16_t *buf,
size_t len, int32_t timeout);
static inline int z_impl_uart_tx_u16(const struct device *dev,
const uint16_t *buf,
size_t len, int32_t timeout)
{
#if defined(CONFIG_UART_ASYNC_API) && defined(CONFIG_UART_WIDE_DATA)
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
return api->tx_u16(dev, buf, len, timeout);
#else
ARG_UNUSED(dev);
ARG_UNUSED(buf);
ARG_UNUSED(len);
ARG_UNUSED(timeout);
return -ENOTSUP;
#endif
}
/**
* @brief Abort current TX transmission.
*
* #UART_TX_DONE event will be generated with amount of data sent.
*
* @param dev UART device instance.
*
* @retval 0 If successful.
* @retval -ENOTSUP If API is not enabled.
* @retval -EFAULT There is no active transmission.
* @retval -errno Other negative errno value in case of failure.
*/
__syscall int uart_tx_abort(const struct device *dev);
static inline int z_impl_uart_tx_abort(const struct device *dev)
{
#ifdef CONFIG_UART_ASYNC_API
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
return api->tx_abort(dev);
#else
ARG_UNUSED(dev);
return -ENOTSUP;
#endif
}
/**
* @brief Start receiving data through UART.
*
* Function sets given buffer as first buffer for receiving and returns
* immediately. After that event handler, set using @ref uart_callback_set,
* is called with #UART_RX_RDY or #UART_RX_BUF_REQUEST events.
*
* @param dev UART device instance.
* @param buf Pointer to receive buffer.
* @param len Buffer length.
* @param timeout Inactivity period after receiving at least a byte which
* triggers #UART_RX_RDY event. Given in microseconds.
* @ref SYS_FOREVER_US disables timeout. See @ref uart_event_type
* for details.
*
* @retval 0 If successful.
* @retval -ENOTSUP If API is not enabled.
* @retval -EBUSY RX already in progress.
* @retval -errno Other negative errno value in case of failure.
*
*/
__syscall int uart_rx_enable(const struct device *dev, uint8_t *buf,
size_t len,
int32_t timeout);
static inline int z_impl_uart_rx_enable(const struct device *dev,
uint8_t *buf,
size_t len, int32_t timeout)
{
#ifdef CONFIG_UART_ASYNC_API
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
return api->rx_enable(dev, buf, len, timeout);
#else
ARG_UNUSED(dev);
ARG_UNUSED(buf);
ARG_UNUSED(len);
ARG_UNUSED(timeout);
return -ENOTSUP;
#endif
}
/**
* @brief Start receiving wide data through UART.
*
* Function sets given buffer as first buffer for receiving and returns
* immediately. After that event handler, set using @ref uart_callback_set,
* is called with #UART_RX_RDY or #UART_RX_BUF_REQUEST events.
*
* @param dev UART device instance.
* @param buf Pointer to wide data receive buffer.
* @param len Buffer length.
* @param timeout Inactivity period after receiving at least a byte which
* triggers #UART_RX_RDY event. Given in milliseconds.
* @ref SYS_FOREVER_MS disables timeout. See
* @ref uart_event_type for details.
*
* @retval 0 If successful.
* @retval -ENOTSUP If API is not enabled.
* @retval -EBUSY RX already in progress.
* @retval -errno Other negative errno value in case of failure.
*
*/
__syscall int uart_rx_enable_u16(const struct device *dev, uint16_t *buf,
size_t len, int32_t timeout);
static inline int z_impl_uart_rx_enable_u16(const struct device *dev,
uint16_t *buf, size_t len,
int32_t timeout)
{
#if defined(CONFIG_UART_ASYNC_API) && defined(CONFIG_UART_WIDE_DATA)
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
return api->rx_enable_u16(dev, buf, len, timeout);
#else
ARG_UNUSED(dev);
ARG_UNUSED(buf);
ARG_UNUSED(len);
ARG_UNUSED(timeout);
return -ENOTSUP;
#endif
}
/**
* @brief Provide receive buffer in response to #UART_RX_BUF_REQUEST event.
*
* Provide pointer to RX buffer, which will be used when current buffer is
* filled.
*
* @note Providing buffer that is already in usage by driver leads to
* undefined behavior. Buffer can be reused when it has been released
* by driver.
*
* @param dev UART device instance.
* @param buf Pointer to receive buffer.
* @param len Buffer length.
*
* @retval 0 If successful.
* @retval -ENOTSUP If API is not enabled.
* @retval -EBUSY Next buffer already set.
* @retval -EACCES Receiver is already disabled (function called too late?).
* @retval -errno Other negative errno value in case of failure.
*/
static inline int uart_rx_buf_rsp(const struct device *dev, uint8_t *buf,
size_t len)
{
#ifdef CONFIG_UART_ASYNC_API
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
return api->rx_buf_rsp(dev, buf, len);
#else
ARG_UNUSED(dev);
ARG_UNUSED(buf);
ARG_UNUSED(len);
return -ENOTSUP;
#endif
}
/**
* @brief Provide wide data receive buffer in response to #UART_RX_BUF_REQUEST
* event.
*
* Provide pointer to RX buffer, which will be used when current buffer is
* filled.
*
* @note Providing buffer that is already in usage by driver leads to
* undefined behavior. Buffer can be reused when it has been released
* by driver.
*
* @param dev UART device instance.
* @param buf Pointer to wide data receive buffer.
* @param len Buffer length.
*
* @retval 0 If successful.
* @retval -ENOTSUP If API is not enabled
* @retval -EBUSY Next buffer already set.
* @retval -EACCES Receiver is already disabled (function called too late?).
* @retval -errno Other negative errno value in case of failure.
*/
static inline int uart_rx_buf_rsp_u16(const struct device *dev, uint16_t *buf,
size_t len)
{
#if defined(CONFIG_UART_ASYNC_API) && defined(CONFIG_UART_WIDE_DATA)
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
return api->rx_buf_rsp_u16(dev, buf, len);
#else
ARG_UNUSED(dev);
ARG_UNUSED(buf);
ARG_UNUSED(len);
return -ENOTSUP;
#endif
}
/**
* @brief Disable RX
*
* #UART_RX_BUF_RELEASED event will be generated for every buffer scheduled,
* after that #UART_RX_DISABLED event will be generated. Additionally, if there
* is any pending received data, the #UART_RX_RDY event for that data will be
* generated before the #UART_RX_BUF_RELEASED events.
*
* @param dev UART device instance.
*
* @retval 0 If successful.
* @retval -ENOTSUP If API is not enabled.
* @retval -EFAULT There is no active reception.
* @retval -errno Other negative errno value in case of failure.
*/
__syscall int uart_rx_disable(const struct device *dev);
static inline int z_impl_uart_rx_disable(const struct device *dev)
{
#ifdef CONFIG_UART_ASYNC_API
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
return api->rx_disable(dev);
#else
ARG_UNUSED(dev);
return -ENOTSUP;
#endif
}
/**
* @}
*/
/**
* @brief Manipulate line control for UART.
*
* @param dev UART device instance.
* @param ctrl The line control to manipulate (see enum uart_line_ctrl).
* @param val Value to set to the line control.
*
* @retval 0 If successful.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
* @retval -errno Other negative errno value in case of failure.
*/
__syscall int uart_line_ctrl_set(const struct device *dev,
uint32_t ctrl, uint32_t val);
static inline int z_impl_uart_line_ctrl_set(const struct device *dev,
uint32_t ctrl, uint32_t val)
{
#ifdef CONFIG_UART_LINE_CTRL
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->line_ctrl_set == NULL) {
return -ENOSYS;
}
return api->line_ctrl_set(dev, ctrl, val);
#else
ARG_UNUSED(dev);
ARG_UNUSED(ctrl);
ARG_UNUSED(val);
return -ENOTSUP;
#endif
}
/**
* @brief Retrieve line control for UART.
*
* @param dev UART device instance.
* @param ctrl The line control to retrieve (see enum uart_line_ctrl).
* @param val Pointer to variable where to store the line control value.
*
* @retval 0 If successful.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
* @retval -errno Other negative errno value in case of failure.
*/
__syscall int uart_line_ctrl_get(const struct device *dev, uint32_t ctrl,
uint32_t *val);
static inline int z_impl_uart_line_ctrl_get(const struct device *dev,
uint32_t ctrl, uint32_t *val)
{
#ifdef CONFIG_UART_LINE_CTRL
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->line_ctrl_get == NULL) {
return -ENOSYS;
}
return api->line_ctrl_get(dev, ctrl, val);
#else
ARG_UNUSED(dev);
ARG_UNUSED(ctrl);
ARG_UNUSED(val);
return -ENOTSUP;
#endif
}
/**
* @brief Send extra command to driver.
*
* Implementation and accepted commands are driver specific.
* Refer to the drivers for more information.
*
* @param dev UART device instance.
* @param cmd Command to driver.
* @param p Parameter to the command.
*
* @retval 0 If successful.
* @retval -ENOSYS If this function is not implemented.
* @retval -ENOTSUP If API is not enabled.
* @retval -errno Other negative errno value in case of failure.
*/
__syscall int uart_drv_cmd(const struct device *dev, uint32_t cmd, uint32_t p);
static inline int z_impl_uart_drv_cmd(const struct device *dev, uint32_t cmd,
uint32_t p)
{
#ifdef CONFIG_UART_DRV_CMD
const struct uart_driver_api *api =
(const struct uart_driver_api *)dev->api;
if (api->drv_cmd == NULL) {
return -ENOSYS;
}
return api->drv_cmd(dev, cmd, p);
#else
ARG_UNUSED(dev);
ARG_UNUSED(cmd);
ARG_UNUSED(p);
return -ENOTSUP;
#endif
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/uart.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_UART_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/uart.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 11,743 |
```objective-c
/*
*
*/
/**
* @file drivers/rtc.h
* @brief Public real time clock driver API
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_RTC_H_
#define ZEPHYR_INCLUDE_DRIVERS_RTC_H_
/**
* @brief RTC Interface
* @defgroup rtc_interface RTC Interface
* @since 3.4
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <errno.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Mask for alarm time fields to enable when setting alarm time
* @name RTC Alarm Time Mask
* @anchor RTC_ALARM_TIME_MASK
* @{
*/
#define RTC_ALARM_TIME_MASK_SECOND BIT(0)
#define RTC_ALARM_TIME_MASK_MINUTE BIT(1)
#define RTC_ALARM_TIME_MASK_HOUR BIT(2)
#define RTC_ALARM_TIME_MASK_MONTHDAY BIT(3)
#define RTC_ALARM_TIME_MASK_MONTH BIT(4)
#define RTC_ALARM_TIME_MASK_YEAR BIT(5)
#define RTC_ALARM_TIME_MASK_WEEKDAY BIT(6)
#define RTC_ALARM_TIME_MASK_YEARDAY BIT(7)
#define RTC_ALARM_TIME_MASK_NSEC BIT(8)
/**
* @}
*/
/**
* @brief Structure for storing date and time values with sub-second precision.
*
* @details The structure is 1-1 mapped to the struct tm for the members
* \p tm_sec to \p tm_isdst making it compatible with the standard time library.
*
* @note Use \ref rtc_time_to_tm() to safely cast from a \ref rtc_time
* pointer to a \ref tm pointer.
*/
struct rtc_time {
int tm_sec; /**< Seconds [0, 59] */
int tm_min; /**< Minutes [0, 59] */
int tm_hour; /**< Hours [0, 23] */
int tm_mday; /**< Day of the month [1, 31] */
int tm_mon; /**< Month [0, 11] */
int tm_year; /**< Year - 1900 */
int tm_wday; /**< Day of the week [0, 6] (Sunday = 0) (Unknown = -1) */
int tm_yday; /**< Day of the year [0, 365] (Unknown = -1) */
int tm_isdst; /**< Daylight saving time flag [-1] (Unknown = -1) */
int tm_nsec; /**< Nanoseconds [0, 999999999] (Unknown = 0) */
};
/**
* @typedef rtc_update_callback
* @brief RTC update event callback
*
* @param dev Device instance invoking the handler
* @param user_data Optional user data provided when update irq callback is set
*/
typedef void (*rtc_update_callback)(const struct device *dev, void *user_data);
/**
* @typedef rtc_alarm_callback
* @brief RTC alarm triggered callback
*
* @param dev Device instance invoking the handler
* @param id Alarm id
* @param user_data Optional user data passed with the alarm configuration
*/
typedef void (*rtc_alarm_callback)(const struct device *dev, uint16_t id, void *user_data);
/**
* @cond INTERNAL_HIDDEN
*
* For internal driver use only, skip these in public documentation.
*/
/**
* @typedef rtc_api_set_time
* @brief API for setting RTC time
*/
typedef int (*rtc_api_set_time)(const struct device *dev, const struct rtc_time *timeptr);
/**
* @typedef rtc_api_get_time
* @brief API for getting RTC time
*/
typedef int (*rtc_api_get_time)(const struct device *dev, struct rtc_time *timeptr);
/**
* @typedef rtc_api_alarm_get_supported_fields
* @brief API for getting the supported fields of the RTC alarm time
*/
typedef int (*rtc_api_alarm_get_supported_fields)(const struct device *dev, uint16_t id,
uint16_t *mask);
/**
* @typedef rtc_api_alarm_set_time
* @brief API for setting RTC alarm time
*/
typedef int (*rtc_api_alarm_set_time)(const struct device *dev, uint16_t id, uint16_t mask,
const struct rtc_time *timeptr);
/**
* @typedef rtc_api_alarm_get_time
* @brief API for getting RTC alarm time
*/
typedef int (*rtc_api_alarm_get_time)(const struct device *dev, uint16_t id, uint16_t *mask,
struct rtc_time *timeptr);
/**
* @typedef rtc_api_alarm_is_pending
* @brief API for testing if RTC alarm is pending
*/
typedef int (*rtc_api_alarm_is_pending)(const struct device *dev, uint16_t id);
/**
* @typedef rtc_api_alarm_set_callback
* @brief API for setting RTC alarm callback
*/
typedef int (*rtc_api_alarm_set_callback)(const struct device *dev, uint16_t id,
rtc_alarm_callback callback, void *user_data);
/**
* @typedef rtc_api_update_set_callback
* @brief API for setting RTC update callback
*/
typedef int (*rtc_api_update_set_callback)(const struct device *dev,
rtc_update_callback callback, void *user_data);
/**
* @typedef rtc_api_set_calibration
* @brief API for setting RTC calibration
*/
typedef int (*rtc_api_set_calibration)(const struct device *dev, int32_t calibration);
/**
* @typedef rtc_api_get_calibration
* @brief API for getting RTC calibration
*/
typedef int (*rtc_api_get_calibration)(const struct device *dev, int32_t *calibration);
/**
* @brief RTC driver API
*/
__subsystem struct rtc_driver_api {
rtc_api_set_time set_time;
rtc_api_get_time get_time;
#if defined(CONFIG_RTC_ALARM) || defined(__DOXYGEN__)
rtc_api_alarm_get_supported_fields alarm_get_supported_fields;
rtc_api_alarm_set_time alarm_set_time;
rtc_api_alarm_get_time alarm_get_time;
rtc_api_alarm_is_pending alarm_is_pending;
rtc_api_alarm_set_callback alarm_set_callback;
#endif /* CONFIG_RTC_ALARM */
#if defined(CONFIG_RTC_UPDATE) || defined(__DOXYGEN__)
rtc_api_update_set_callback update_set_callback;
#endif /* CONFIG_RTC_UPDATE */
#if defined(CONFIG_RTC_CALIBRATION) || defined(__DOXYGEN__)
rtc_api_set_calibration set_calibration;
rtc_api_get_calibration get_calibration;
#endif /* CONFIG_RTC_CALIBRATION */
};
/** @endcond */
/**
* @brief API for setting RTC time.
*
* @param dev Device instance
* @param timeptr The time to set
*
* @return 0 if successful
* @return -EINVAL if RTC time is invalid or exceeds hardware capabilities
* @return -errno code if failure
*/
__syscall int rtc_set_time(const struct device *dev, const struct rtc_time *timeptr);
static inline int z_impl_rtc_set_time(const struct device *dev, const struct rtc_time *timeptr)
{
const struct rtc_driver_api *api = (const struct rtc_driver_api *)dev->api;
return api->set_time(dev, timeptr);
}
/**
* @brief API for getting RTC time.
*
* @param dev Device instance
* @param timeptr Destination for the time
*
* @return 0 if successful
* @return -ENODATA if RTC time has not been set
* @return -errno code if failure
*/
__syscall int rtc_get_time(const struct device *dev, struct rtc_time *timeptr);
static inline int z_impl_rtc_get_time(const struct device *dev, struct rtc_time *timeptr)
{
const struct rtc_driver_api *api = (const struct rtc_driver_api *)dev->api;
return api->get_time(dev, timeptr);
}
/**
* @name RTC Interface Alarm
* @{
*/
#if defined(CONFIG_RTC_ALARM) || defined(__DOXYGEN__)
/**
* @brief API for getting the supported fields of the RTC alarm time.
*
* @param dev Device instance
* @param id Id of the alarm
* @param mask Mask of fields in the alarm time which are supported
*
* @note Bits in the mask param are defined here @ref RTC_ALARM_TIME_MASK.
*
* @return 0 if successful
* @return -EINVAL if id is out of range or time is invalid
* @return -ENOTSUP if API is not supported by hardware
* @return -errno code if failure
*/
__syscall int rtc_alarm_get_supported_fields(const struct device *dev, uint16_t id,
uint16_t *mask);
static inline int z_impl_rtc_alarm_get_supported_fields(const struct device *dev, uint16_t id,
uint16_t *mask)
{
const struct rtc_driver_api *api = (const struct rtc_driver_api *)dev->api;
if (api->alarm_get_supported_fields == NULL) {
return -ENOSYS;
}
return api->alarm_get_supported_fields(dev, id, mask);
}
/**
* @brief API for setting RTC alarm time.
*
* @details To enable an RTC alarm, one or more fields of the RTC alarm time
* must be enabled. The mask designates which fields of the RTC alarm time to
* enable. If the mask parameter is 0, the alarm will be disabled. The RTC
* alarm will trigger when all enabled fields of the alarm time match the RTC
* time.
*
* @param dev Device instance
* @param id Id of the alarm
* @param mask Mask of fields in the alarm time to enable
* @param timeptr The alarm time to set
*
* @note The timeptr param may be NULL if the mask param is 0
* @note Only the enabled fields in the timeptr param need to be configured
* @note Bits in the mask param are defined here @ref RTC_ALARM_TIME_MASK
*
* @return 0 if successful
* @return -EINVAL if id is out of range or time is invalid
* @return -ENOTSUP if API is not supported by hardware
* @return -errno code if failure
*/
__syscall int rtc_alarm_set_time(const struct device *dev, uint16_t id, uint16_t mask,
const struct rtc_time *timeptr);
static inline int z_impl_rtc_alarm_set_time(const struct device *dev, uint16_t id, uint16_t mask,
const struct rtc_time *timeptr)
{
const struct rtc_driver_api *api = (const struct rtc_driver_api *)dev->api;
if (api->alarm_set_time == NULL) {
return -ENOSYS;
}
return api->alarm_set_time(dev, id, mask, timeptr);
}
/**
* @brief API for getting RTC alarm time.
*
* @param dev Device instance
* @param id Id of the alarm
* @param mask Destination for mask of fields which are enabled in the alarm time
* @param timeptr Destination for the alarm time
*
* @note Bits in the mask param are defined here @ref RTC_ALARM_TIME_MASK
*
* @return 0 if successful
* @return -EINVAL if id is out of range
* @return -ENOTSUP if API is not supported by hardware
* @return -errno code if failure
*/
__syscall int rtc_alarm_get_time(const struct device *dev, uint16_t id, uint16_t *mask,
struct rtc_time *timeptr);
static inline int z_impl_rtc_alarm_get_time(const struct device *dev, uint16_t id, uint16_t *mask,
struct rtc_time *timeptr)
{
const struct rtc_driver_api *api = (const struct rtc_driver_api *)dev->api;
if (api->alarm_get_time == NULL) {
return -ENOSYS;
}
return api->alarm_get_time(dev, id, mask, timeptr);
}
/**
* @brief API for testing if RTC alarm is pending.
*
* @details Test whether or not the alarm with id is pending. If the alarm
* is pending, the pending status is cleared.
*
* @param dev Device instance
* @param id Id of the alarm to test
*
* @return 1 if alarm was pending
* @return 0 if alarm was not pending
* @return -EINVAL if id is out of range
* @return -ENOTSUP if API is not supported by hardware
* @return -errno code if failure
*/
__syscall int rtc_alarm_is_pending(const struct device *dev, uint16_t id);
static inline int z_impl_rtc_alarm_is_pending(const struct device *dev, uint16_t id)
{
const struct rtc_driver_api *api = (const struct rtc_driver_api *)dev->api;
if (api->alarm_is_pending == NULL) {
return -ENOSYS;
}
return api->alarm_is_pending(dev, id);
}
/**
* @brief API for setting alarm callback.
*
* @details Setting the alarm callback for an alarm, will enable the
* alarm callback. When the callback for an alarm is enabled, the
* alarm triggered event will invoke the callback, after which the
* alarm pending status will be cleared automatically. The alarm will
* remain enabled until manually disabled using
* \ref rtc_alarm_set_time().
*
* To disable the alarm callback for an alarm, the \p callback and
* \p user_data parameters must be set to NULL. When the alarm
* callback for an alarm is disabled, the alarm triggered event will
* set the alarm status to "pending". To check if the alarm status is
* "pending", use \ref rtc_alarm_is_pending().
*
* @param dev Device instance
* @param id Id of the alarm for which the callback shall be set
* @param callback Callback called when alarm occurs
* @param user_data Optional user data passed to callback
*
* @return 0 if successful
* @return -EINVAL if id is out of range
* @return -ENOTSUP if API is not supported by hardware
* @return -errno code if failure
*/
__syscall int rtc_alarm_set_callback(const struct device *dev, uint16_t id,
rtc_alarm_callback callback, void *user_data);
static inline int z_impl_rtc_alarm_set_callback(const struct device *dev, uint16_t id,
rtc_alarm_callback callback, void *user_data)
{
const struct rtc_driver_api *api = (const struct rtc_driver_api *)dev->api;
if (api->alarm_set_callback == NULL) {
return -ENOSYS;
}
return api->alarm_set_callback(dev, id, callback, user_data);
}
#endif /* CONFIG_RTC_ALARM */
/**
* @}
*/
/**
* @name RTC Interface Update
* @{
*/
#if defined(CONFIG_RTC_UPDATE) || defined(__DOXYGEN__)
/**
* @brief API for setting update callback.
*
* @details Setting the update callback will enable the update
* callback. The update callback will be invoked every time the
* RTC clock is updated by 1 second. It can be used to
* synchronize the RTC clock with other clock sources.
*
* To disable the update callback for the RTC clock, the
* \p callback and \p user_data parameters must be set to NULL.
*
* @param dev Device instance
* @param callback Callback called when update occurs
* @param user_data Optional user data passed to callback
*
* @return 0 if successful
* @return -ENOTSUP if API is not supported by hardware
* @return -errno code if failure
*/
__syscall int rtc_update_set_callback(const struct device *dev, rtc_update_callback callback,
void *user_data);
static inline int z_impl_rtc_update_set_callback(const struct device *dev,
rtc_update_callback callback, void *user_data)
{
const struct rtc_driver_api *api = (const struct rtc_driver_api *)dev->api;
if (api->update_set_callback == NULL) {
return -ENOSYS;
}
return api->update_set_callback(dev, callback, user_data);
}
#endif /* CONFIG_RTC_UPDATE */
/**
* @}
*/
/**
* @name RTC Interface Calibration
* @{
*/
#if defined(CONFIG_RTC_CALIBRATION) || defined(__DOXYGEN__)
/**
* @brief API for setting RTC calibration.
*
* @details Calibration is applied to the RTC clock input. A
* positive calibration value will increase the frequency of
* the RTC clock, a negative value will decrease the
* frequency of the RTC clock.
*
* @see rtc_calibration_from_frequency()
*
* @param dev Device instance
* @param calibration Calibration to set in parts per billion
*
* @return 0 if successful
* @return -EINVAL if calibration is out of range
* @return -ENOTSUP if API is not supported by hardware
* @return -errno code if failure
*/
__syscall int rtc_set_calibration(const struct device *dev, int32_t calibration);
static inline int z_impl_rtc_set_calibration(const struct device *dev, int32_t calibration)
{
const struct rtc_driver_api *api = (const struct rtc_driver_api *)dev->api;
if (api->set_calibration == NULL) {
return -ENOSYS;
}
return api->set_calibration(dev, calibration);
}
/**
* @brief API for getting RTC calibration.
*
* @param dev Device instance
* @param calibration Destination for calibration in parts per billion
*
* @return 0 if successful
* @return -ENOTSUP if API is not supported by hardware
* @return -errno code if failure
*/
__syscall int rtc_get_calibration(const struct device *dev, int32_t *calibration);
static inline int z_impl_rtc_get_calibration(const struct device *dev, int32_t *calibration)
{
const struct rtc_driver_api *api = (const struct rtc_driver_api *)dev->api;
if (api->get_calibration == NULL) {
return -ENOSYS;
}
return api->get_calibration(dev, calibration);
}
#endif /* CONFIG_RTC_CALIBRATION */
/**
* @}
*/
/**
* @name RTC Interface Helpers
* @{
*/
/**
* @brief Forward declaration of struct tm for \ref rtc_time_to_tm().
*/
struct tm;
/**
* @brief Convenience function for safely casting a \ref rtc_time pointer
* to a \ref tm pointer.
*/
static inline struct tm *rtc_time_to_tm(struct rtc_time *timeptr)
{
return (struct tm *)timeptr;
}
/**
* @brief Determine required calibration to 1 Hertz from frequency.
*
* @param frequency Frequency of the RTC in nano Hertz
*
* @return The required calibration in parts per billion
*/
static inline int32_t rtc_calibration_from_frequency(uint32_t frequency)
{
__ASSERT_NO_MSG(frequency > 0);
return (int32_t)((1000000000000000000LL / frequency) - 1000000000);
}
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/rtc.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_RTC_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/rtc.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 3,968 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public API for display drivers and applications
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_DISPLAY_H_
#define ZEPHYR_INCLUDE_DRIVERS_DISPLAY_H_
/**
* @brief Display Interface
* @defgroup display_interface Display Interface
* @since 1.14
* @version 0.8.0
* @ingroup io_interfaces
* @{
*/
#include <zephyr/device.h>
#include <errno.h>
#include <stddef.h>
#include <zephyr/types.h>
#include <zephyr/dt-bindings/display/panel.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Display pixel formats
*
* Display pixel format enumeration.
*
* In case a pixel format consists out of multiple bytes the byte order is
* big endian.
*/
enum display_pixel_format {
PIXEL_FORMAT_RGB_888 = BIT(0), /**< 24-bit RGB */
PIXEL_FORMAT_MONO01 = BIT(1), /**< Monochrome (0=Black 1=White) */
PIXEL_FORMAT_MONO10 = BIT(2), /**< Monochrome (1=Black 0=White) */
PIXEL_FORMAT_ARGB_8888 = BIT(3), /**< 32-bit ARGB */
PIXEL_FORMAT_RGB_565 = BIT(4), /**< 16-bit RGB */
PIXEL_FORMAT_BGR_565 = BIT(5), /**< 16-bit BGR */
};
/**
* @brief Bits required per pixel for display format
*
* This macro expands to the number of bits required for a given display
* format. It can be used to allocate a framebuffer based on a given
* display format type
*/
#define DISPLAY_BITS_PER_PIXEL(fmt) \
((((fmt & PIXEL_FORMAT_RGB_888) >> 0) * 24U) + \
(((fmt & PIXEL_FORMAT_MONO01) >> 1) * 1U) + \
(((fmt & PIXEL_FORMAT_MONO10) >> 2) * 1U) + \
(((fmt & PIXEL_FORMAT_ARGB_8888) >> 3) * 32U) + \
(((fmt & PIXEL_FORMAT_RGB_565) >> 4) * 16U) + \
(((fmt & PIXEL_FORMAT_BGR_565) >> 5) * 16U))
/**
* @brief Display screen information
*/
enum display_screen_info {
/**
* If selected, one octet represents 8 pixels ordered vertically,
* otherwise ordered horizontally.
*/
SCREEN_INFO_MONO_VTILED = BIT(0),
/**
* If selected, the MSB represents the first pixel,
* otherwise MSB represents the last pixel.
*/
SCREEN_INFO_MONO_MSB_FIRST = BIT(1),
/**
* Electrophoretic Display.
*/
SCREEN_INFO_EPD = BIT(2),
/**
* Screen has two alternating ram buffers
*/
SCREEN_INFO_DOUBLE_BUFFER = BIT(3),
/**
* Screen has x alignment constrained to width.
*/
SCREEN_INFO_X_ALIGNMENT_WIDTH = BIT(4),
};
/**
* @brief Enumeration with possible display orientation
*/
enum display_orientation {
DISPLAY_ORIENTATION_NORMAL, /**< No rotation */
DISPLAY_ORIENTATION_ROTATED_90, /**< Rotated 90 degrees clockwise */
DISPLAY_ORIENTATION_ROTATED_180, /**< Rotated 180 degrees clockwise */
DISPLAY_ORIENTATION_ROTATED_270, /**< Rotated 270 degrees clockwise */
};
/** @brief Structure holding display capabilities. */
struct display_capabilities {
/** Display resolution in the X direction */
uint16_t x_resolution;
/** Display resolution in the Y direction */
uint16_t y_resolution;
/** Bitwise or of pixel formats supported by the display */
uint32_t supported_pixel_formats;
/** Information about display panel */
uint32_t screen_info;
/** Currently active pixel format for the display */
enum display_pixel_format current_pixel_format;
/** Current display orientation */
enum display_orientation current_orientation;
};
/** @brief Structure to describe display data buffer layout */
struct display_buffer_descriptor {
/** Data buffer size in bytes */
uint32_t buf_size;
/** Data buffer row width in pixels */
uint16_t width;
/** Data buffer column height in pixels */
uint16_t height;
/** Number of pixels between consecutive rows in the data buffer */
uint16_t pitch;
};
/**
* @typedef display_blanking_on_api
* @brief Callback API to turn on display blanking
* See display_blanking_on() for argument description
*/
typedef int (*display_blanking_on_api)(const struct device *dev);
/**
* @typedef display_blanking_off_api
* @brief Callback API to turn off display blanking
* See display_blanking_off() for argument description
*/
typedef int (*display_blanking_off_api)(const struct device *dev);
/**
* @typedef display_write_api
* @brief Callback API for writing data to the display
* See display_write() for argument description
*/
typedef int (*display_write_api)(const struct device *dev, const uint16_t x,
const uint16_t y,
const struct display_buffer_descriptor *desc,
const void *buf);
/**
* @typedef display_read_api
* @brief Callback API for reading data from the display
* See display_read() for argument description
*/
typedef int (*display_read_api)(const struct device *dev, const uint16_t x,
const uint16_t y,
const struct display_buffer_descriptor *desc,
void *buf);
/**
* @typedef display_get_framebuffer_api
* @brief Callback API to get framebuffer pointer
* See display_get_framebuffer() for argument description
*/
typedef void *(*display_get_framebuffer_api)(const struct device *dev);
/**
* @typedef display_set_brightness_api
* @brief Callback API to set display brightness
* See display_set_brightness() for argument description
*/
typedef int (*display_set_brightness_api)(const struct device *dev,
const uint8_t brightness);
/**
* @typedef display_set_contrast_api
* @brief Callback API to set display contrast
* See display_set_contrast() for argument description
*/
typedef int (*display_set_contrast_api)(const struct device *dev,
const uint8_t contrast);
/**
* @typedef display_get_capabilities_api
* @brief Callback API to get display capabilities
* See display_get_capabilities() for argument description
*/
typedef void (*display_get_capabilities_api)(const struct device *dev,
struct display_capabilities *
capabilities);
/**
* @typedef display_set_pixel_format_api
* @brief Callback API to set pixel format used by the display
* See display_set_pixel_format() for argument description
*/
typedef int (*display_set_pixel_format_api)(const struct device *dev,
const enum display_pixel_format
pixel_format);
/**
* @typedef display_set_orientation_api
* @brief Callback API to set orientation used by the display
* See display_set_orientation() for argument description
*/
typedef int (*display_set_orientation_api)(const struct device *dev,
const enum display_orientation
orientation);
/**
* @brief Display driver API
* API which a display driver should expose
*/
__subsystem struct display_driver_api {
display_blanking_on_api blanking_on;
display_blanking_off_api blanking_off;
display_write_api write;
display_read_api read;
display_get_framebuffer_api get_framebuffer;
display_set_brightness_api set_brightness;
display_set_contrast_api set_contrast;
display_get_capabilities_api get_capabilities;
display_set_pixel_format_api set_pixel_format;
display_set_orientation_api set_orientation;
};
/**
* @brief Write data to display
*
* @param dev Pointer to device structure
* @param x x Coordinate of the upper left corner where to write the buffer
* @param y y Coordinate of the upper left corner where to write the buffer
* @param desc Pointer to a structure describing the buffer layout
* @param buf Pointer to buffer array
*
* @retval 0 on success else negative errno code.
*/
static inline int display_write(const struct device *dev, const uint16_t x,
const uint16_t y,
const struct display_buffer_descriptor *desc,
const void *buf)
{
struct display_driver_api *api =
(struct display_driver_api *)dev->api;
return api->write(dev, x, y, desc, buf);
}
/**
* @brief Read data from display
*
* @param dev Pointer to device structure
* @param x x Coordinate of the upper left corner where to read from
* @param y y Coordinate of the upper left corner where to read from
* @param desc Pointer to a structure describing the buffer layout
* @param buf Pointer to buffer array
*
* @retval 0 on success else negative errno code.
* @retval -ENOSYS if not implemented.
*/
static inline int display_read(const struct device *dev, const uint16_t x,
const uint16_t y,
const struct display_buffer_descriptor *desc,
void *buf)
{
struct display_driver_api *api =
(struct display_driver_api *)dev->api;
if (api->read == NULL) {
return -ENOSYS;
}
return api->read(dev, x, y, desc, buf);
}
/**
* @brief Get pointer to framebuffer for direct access
*
* @param dev Pointer to device structure
*
* @retval Pointer to frame buffer or NULL if direct framebuffer access
* is not supported
*
*/
static inline void *display_get_framebuffer(const struct device *dev)
{
struct display_driver_api *api =
(struct display_driver_api *)dev->api;
if (api->get_framebuffer == NULL) {
return NULL;
}
return api->get_framebuffer(dev);
}
/**
* @brief Turn display blanking on
*
* This function blanks the complete display.
* The content of the frame buffer will be retained while blanking is enabled
* and the frame buffer will be accessible for read and write operations.
*
* In case backlight control is supported by the driver the backlight is
* turned off. The backlight configuration is retained and accessible for
* configuration.
*
* In case the driver supports display blanking the initial state of the driver
* would be the same as if this function was called.
*
* @param dev Pointer to device structure
*
* @retval 0 on success else negative errno code.
* @retval -ENOSYS if not implemented.
*/
static inline int display_blanking_on(const struct device *dev)
{
struct display_driver_api *api =
(struct display_driver_api *)dev->api;
if (api->blanking_on == NULL) {
return -ENOSYS;
}
return api->blanking_on(dev);
}
/**
* @brief Turn display blanking off
*
* Restore the frame buffer content to the display.
* In case backlight control is supported by the driver the backlight
* configuration is restored.
*
* @param dev Pointer to device structure
*
* @retval 0 on success else negative errno code.
* @retval -ENOSYS if not implemented.
*/
static inline int display_blanking_off(const struct device *dev)
{
struct display_driver_api *api =
(struct display_driver_api *)dev->api;
if (api->blanking_off == NULL) {
return -ENOSYS;
}
return api->blanking_off(dev);
}
/**
* @brief Set the brightness of the display
*
* Set the brightness of the display in steps of 1/256, where 255 is full
* brightness and 0 is minimal.
*
* @param dev Pointer to device structure
* @param brightness Brightness in steps of 1/256
*
* @retval 0 on success else negative errno code.
* @retval -ENOSYS if not implemented.
*/
static inline int display_set_brightness(const struct device *dev,
uint8_t brightness)
{
struct display_driver_api *api =
(struct display_driver_api *)dev->api;
if (api->set_brightness == NULL) {
return -ENOSYS;
}
return api->set_brightness(dev, brightness);
}
/**
* @brief Set the contrast of the display
*
* Set the contrast of the display in steps of 1/256, where 255 is maximum
* difference and 0 is minimal.
*
* @param dev Pointer to device structure
* @param contrast Contrast in steps of 1/256
*
* @retval 0 on success else negative errno code.
* @retval -ENOSYS if not implemented.
*/
static inline int display_set_contrast(const struct device *dev, uint8_t contrast)
{
struct display_driver_api *api =
(struct display_driver_api *)dev->api;
if (api->set_contrast == NULL) {
return -ENOSYS;
}
return api->set_contrast(dev, contrast);
}
/**
* @brief Get display capabilities
*
* @param dev Pointer to device structure
* @param capabilities Pointer to capabilities structure to populate
*/
static inline void display_get_capabilities(const struct device *dev,
struct display_capabilities *
capabilities)
{
struct display_driver_api *api =
(struct display_driver_api *)dev->api;
api->get_capabilities(dev, capabilities);
}
/**
* @brief Set pixel format used by the display
*
* @param dev Pointer to device structure
* @param pixel_format Pixel format to be used by display
*
* @retval 0 on success else negative errno code.
* @retval -ENOSYS if not implemented.
*/
static inline int
display_set_pixel_format(const struct device *dev,
const enum display_pixel_format pixel_format)
{
struct display_driver_api *api =
(struct display_driver_api *)dev->api;
if (api->set_pixel_format == NULL) {
return -ENOSYS;
}
return api->set_pixel_format(dev, pixel_format);
}
/**
* @brief Set display orientation
*
* @param dev Pointer to device structure
* @param orientation Orientation to be used by display
*
* @retval 0 on success else negative errno code.
* @retval -ENOSYS if not implemented.
*/
static inline int display_set_orientation(const struct device *dev,
const enum display_orientation
orientation)
{
struct display_driver_api *api =
(struct display_driver_api *)dev->api;
if (api->set_orientation == NULL) {
return -ENOSYS;
}
return api->set_orientation(dev, orientation);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_DISPLAY_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/display.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 3,075 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public APIs for MIPI-DSI drivers
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_MIPI_DSI_H_
#define ZEPHYR_INCLUDE_DRIVERS_MIPI_DSI_H_
/**
* @brief MIPI-DSI driver APIs
* @defgroup mipi_dsi_interface MIPI-DSI driver APIs
* @since 3.1
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <sys/types.h>
#include <zephyr/device.h>
#include <zephyr/display/mipi_display.h>
#include <zephyr/dt-bindings/mipi_dsi/mipi_dsi.h>
#ifdef __cplusplus
extern "C" {
#endif
/** MIPI-DSI display timings. */
struct mipi_dsi_timings {
/** Horizontal active video. */
uint32_t hactive;
/** Horizontal front porch. */
uint32_t hfp;
/** Horizontal back porch. */
uint32_t hbp;
/** Horizontal sync length. */
uint32_t hsync;
/** Vertical active video. */
uint32_t vactive;
/** Vertical front porch. */
uint32_t vfp;
/** Vertical back porch. */
uint32_t vbp;
/** Vertical sync length. */
uint32_t vsync;
};
/**
* @name MIPI-DSI Device mode flags.
* @{
*/
/** Video mode */
#define MIPI_DSI_MODE_VIDEO BIT(0)
/** Video burst mode */
#define MIPI_DSI_MODE_VIDEO_BURST BIT(1)
/** Video pulse mode */
#define MIPI_DSI_MODE_VIDEO_SYNC_PULSE BIT(2)
/** Enable auto vertical count mode */
#define MIPI_DSI_MODE_VIDEO_AUTO_VERT BIT(3)
/** Enable hsync-end packets in vsync-pulse and v-porch area */
#define MIPI_DSI_MODE_VIDEO_HSE BIT(4)
/** Disable hfront-porch area */
#define MIPI_DSI_MODE_VIDEO_HFP BIT(5)
/** Disable hback-porch area */
#define MIPI_DSI_MODE_VIDEO_HBP BIT(6)
/** Disable hsync-active area */
#define MIPI_DSI_MODE_VIDEO_HSA BIT(7)
/** Flush display FIFO on vsync pulse */
#define MIPI_DSI_MODE_VSYNC_FLUSH BIT(8)
/** Disable EoT packets in HS mode */
#define MIPI_DSI_MODE_EOT_PACKET BIT(9)
/** Device supports non-continuous clock behavior (DSI spec 5.6.1) */
#define MIPI_DSI_CLOCK_NON_CONTINUOUS BIT(10)
/** Transmit data in low power */
#define MIPI_DSI_MODE_LPM BIT(11)
/** @} */
/** MIPI-DSI device. */
struct mipi_dsi_device {
/** Number of data lanes. */
uint8_t data_lanes;
/** Display timings. */
struct mipi_dsi_timings timings;
/** Pixel format. */
uint32_t pixfmt;
/** Mode flags. */
uint32_t mode_flags;
};
/*
* Per message flag to indicate the message must be sent
* using Low Power Mode instead of controller default.
*/
#define MIPI_DSI_MSG_USE_LPM BIT(0x0)
/** MIPI-DSI read/write message. */
struct mipi_dsi_msg {
/** Payload data type. */
uint8_t type;
/** Flags controlling message transmission. */
uint16_t flags;
/** Command (only for DCS) */
uint8_t cmd;
/** Transmission buffer length. */
size_t tx_len;
/** Transmission buffer. */
const void *tx_buf;
/** Reception buffer length. */
size_t rx_len;
/** Reception buffer. */
void *rx_buf;
};
/** MIPI-DSI host driver API. */
__subsystem struct mipi_dsi_driver_api {
int (*attach)(const struct device *dev, uint8_t channel,
const struct mipi_dsi_device *mdev);
ssize_t (*transfer)(const struct device *dev, uint8_t channel,
struct mipi_dsi_msg *msg);
int (*detach)(const struct device *dev, uint8_t channel,
const struct mipi_dsi_device *mdev);
};
/**
* @brief Attach a new device to the MIPI-DSI bus.
*
* @param dev MIPI-DSI host device.
* @param channel Device channel (VID).
* @param mdev MIPI-DSI device description.
*
* @return 0 on success, negative on error
*/
static inline int mipi_dsi_attach(const struct device *dev,
uint8_t channel,
const struct mipi_dsi_device *mdev)
{
const struct mipi_dsi_driver_api *api = (const struct mipi_dsi_driver_api *)dev->api;
return api->attach(dev, channel, mdev);
}
/**
* @brief Transfer data to/from a device attached to the MIPI-DSI bus.
*
* @param dev MIPI-DSI device.
* @param channel Device channel (VID).
* @param msg Message.
*
* @return Size of the transferred data on success, negative on error.
*/
static inline ssize_t mipi_dsi_transfer(const struct device *dev,
uint8_t channel,
struct mipi_dsi_msg *msg)
{
const struct mipi_dsi_driver_api *api = (const struct mipi_dsi_driver_api *)dev->api;
return api->transfer(dev, channel, msg);
}
/**
* @brief MIPI-DSI generic read.
*
* @param dev MIPI-DSI host device.
* @param channel Device channel (VID).
* @param params Buffer containing request parameters.
* @param nparams Number of parameters.
* @param buf Buffer where read data will be stored.
* @param len Length of the reception buffer.
*
* @return Size of the read data on success, negative on error.
*/
ssize_t mipi_dsi_generic_read(const struct device *dev, uint8_t channel,
const void *params, size_t nparams,
void *buf, size_t len);
/**
* @brief MIPI-DSI generic write.
*
* @param dev MIPI-DSI host device.
* @param channel Device channel (VID).
* @param buf Transmission buffer.
* @param len Length of the transmission buffer
*
* @return Size of the written data on success, negative on error.
*/
ssize_t mipi_dsi_generic_write(const struct device *dev, uint8_t channel,
const void *buf, size_t len);
/**
* @brief MIPI-DSI DCS read.
*
* @param dev MIPI-DSI host device.
* @param channel Device channel (VID).
* @param cmd DCS command.
* @param buf Buffer where read data will be stored.
* @param len Length of the reception buffer.
*
* @return Size of the read data on success, negative on error.
*/
ssize_t mipi_dsi_dcs_read(const struct device *dev, uint8_t channel,
uint8_t cmd, void *buf, size_t len);
/**
* @brief MIPI-DSI DCS write.
*
* @param dev MIPI-DSI host device.
* @param channel Device channel (VID).
* @param cmd DCS command.
* @param buf Transmission buffer.
* @param len Length of the transmission buffer
*
* @return Size of the written data on success, negative on error.
*/
ssize_t mipi_dsi_dcs_write(const struct device *dev, uint8_t channel,
uint8_t cmd, const void *buf, size_t len);
/**
* @brief Detach a device from the MIPI-DSI bus
*
* @param dev MIPI-DSI host device.
* @param channel Device channel (VID).
* @param mdev MIPI-DSI device description.
*
* @return 0 on success, negative on error
*/
static inline int mipi_dsi_detach(const struct device *dev,
uint8_t channel,
const struct mipi_dsi_device *mdev)
{
const struct mipi_dsi_driver_api *api = (const struct mipi_dsi_driver_api *)dev->api;
if (api->detach == NULL) {
return -ENOSYS;
}
return api->detach(dev, channel, mdev);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_MIPI_DSI_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/mipi_dsi.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,803 |
```objective-c
/*
*
*/
/**
* @file
* @brief SD Host Controller public API header file.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_SDHC_H_
#define ZEPHYR_INCLUDE_DRIVERS_SDHC_H_
#include <errno.h>
#include <zephyr/device.h>
#include <zephyr/sd/sd_spec.h>
/**
* @brief SDHC interface
* @defgroup sdhc_interface SDHC interface
* @since 3.1
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name SD command timeouts
* @{
*/
#define SDHC_TIMEOUT_FOREVER (-1)
/** @} */
/**
* @brief SD host controller command structure
*
* This command structure is used to send command requests to an SD
* host controller, which will be sent to SD devices.
*/
struct sdhc_command {
uint32_t opcode; /*!< SD Host specification CMD index */
uint32_t arg; /*!< SD host specification argument */
uint32_t response[4]; /*!< SD card response field */
uint32_t response_type; /*!< Expected SD response type */
unsigned int retries; /*!< Max number of retries */
int timeout_ms; /*!< Command timeout in milliseconds */
};
#define SDHC_NATIVE_RESPONSE_MASK 0xF
#define SDHC_SPI_RESPONSE_TYPE_MASK 0xF0
/**
* @brief SD host controller data structure
*
* This command structure is used to send data transfer requests to an SD
* host controller, which will be sent to SD devices.
*/
struct sdhc_data {
unsigned int block_addr; /*!< Block to start read from */
unsigned int block_size; /*!< Block size */
unsigned int blocks; /*!< Number of blocks */
unsigned int bytes_xfered; /*!< populated with number of bytes sent by SDHC */
void *data; /*!< Data to transfer or receive */
int timeout_ms; /*!< data timeout in milliseconds */
};
/**
* @brief SD bus mode.
*
* Most controllers will use push/pull, including spi, but
* SDHC controllers that implement SD host specification can support open
* drain mode
*/
enum sdhc_bus_mode {
SDHC_BUSMODE_OPENDRAIN = 1,
SDHC_BUSMODE_PUSHPULL = 2,
};
/**
* @brief SD host controller power
*
* Many host controllers can control power to attached SD cards.
* This enum allows applications to request the host controller power off
* the SD card.
*/
enum sdhc_power {
SDHC_POWER_OFF = 1,
SDHC_POWER_ON = 2,
};
/**
* @brief SD host controller bus width
*
* Only relevant in SD mode, SPI does not support bus width. UHS cards will
* use 4 bit data bus, all cards start in 1 bit mode
*/
enum sdhc_bus_width {
SDHC_BUS_WIDTH1BIT = 1U,
SDHC_BUS_WIDTH4BIT = 4U,
SDHC_BUS_WIDTH8BIT = 8U,
};
/**
* @brief SD host controller timing mode
*
* Used by SD host controller to determine the timing of the cards attached
* to the bus. Cards start with legacy timing, but UHS-II cards can go up to
* SDR104.
*/
enum sdhc_timing_mode {
SDHC_TIMING_LEGACY = 1U,
/*!< Legacy 3.3V Mode */
SDHC_TIMING_HS = 2U,
/*!< Legacy High speed mode (3.3V) */
SDHC_TIMING_SDR12 = 3U,
/*!< Identification mode & SDR12 */
SDHC_TIMING_SDR25 = 4U,
/*!< High speed mode & SDR25 */
SDHC_TIMING_SDR50 = 5U,
/*!< SDR49 mode*/
SDHC_TIMING_SDR104 = 6U,
/*!< SDR104 mode */
SDHC_TIMING_DDR50 = 7U,
/*!< DDR50 mode */
SDHC_TIMING_DDR52 = 8U,
/*!< DDR52 mode */
SDHC_TIMING_HS200 = 9U,
/*!< HS200 mode */
SDHC_TIMING_HS400 = 10U,
/*!< HS400 mode */
};
/**
* @brief SD voltage
*
* UHS cards can run with 1.8V signalling for improved power consumption. Legacy
* cards may support 3.0V signalling, and all cards start at 3.3V.
* Only relevant for SD controllers, not SPI ones.
*/
enum sd_voltage {
SD_VOL_3_3_V = 1U,
/*!< card operation voltage around 3.3v */
SD_VOL_3_0_V = 2U,
/*!< card operation voltage around 3.0v */
SD_VOL_1_8_V = 3U,
/*!< card operation voltage around 1.8v */
SD_VOL_1_2_V = 4U,
/*!< card operation voltage around 1.2v */
};
/**
* @brief SD host controller capabilities
*
* SD host controller capability flags. These flags should be set by the SDHC
* driver, using the @ref sdhc_get_host_props api.
*/
struct sdhc_host_caps {
unsigned int timeout_clk_freq: 5; /**< Timeout clock frequency */
unsigned int _rsvd_6: 1; /**< Reserved */
unsigned int timeout_clk_unit: 1; /**< Timeout clock unit */
unsigned int sd_base_clk: 8; /**< SD base clock frequency */
unsigned int max_blk_len: 2; /**< Max block length */
unsigned int bus_8_bit_support: 1; /**< 8-bit Support for embedded device */
unsigned int bus_4_bit_support: 1; /**< 4 bit bus support */
unsigned int adma_2_support: 1; /**< ADMA2 support */
unsigned int _rsvd_20: 1; /**< Reserved */
unsigned int high_spd_support: 1; /**< High speed support */
unsigned int sdma_support: 1; /**< SDMA support */
unsigned int suspend_res_support: 1; /**< Suspend/Resume support */
unsigned int vol_330_support: 1; /**< Voltage support 3.3V */
unsigned int vol_300_support: 1; /**< Voltage support 3.0V */
unsigned int vol_180_support: 1; /**< Voltage support 1.8V */
unsigned int address_64_bit_support_v4: 1; /**< 64-bit system address support for V4 */
unsigned int address_64_bit_support_v3: 1; /**< 64-bit system address support for V3 */
unsigned int sdio_async_interrupt_support: 1; /**< Asynchronous interrupt support */
unsigned int slot_type: 2; /**< Slot type */
unsigned int sdr50_support: 1; /**< SDR50 support */
unsigned int sdr104_support: 1; /**< SDR104 support */
unsigned int ddr50_support: 1; /**< DDR50 support */
unsigned int uhs_2_support: 1; /**< UHS-II support */
unsigned int drv_type_a_support: 1; /**< Driver type A support */
unsigned int drv_type_c_support: 1; /**< Driver type C support */
unsigned int drv_type_d_support: 1; /**< Driver type D support */
unsigned int _rsvd_39: 1; /**< Reserved */
unsigned int retune_timer_count: 4; /**< Timer count for re-tuning */
unsigned int sdr50_needs_tuning: 1; /**< Use tuning for SDR50 */
unsigned int retuning_mode: 2; /**< Re-tuning mode */
unsigned int clk_multiplier: 8; /**< Clock multiplier */
unsigned int _rsvd_56: 3; /**< Reserved */
unsigned int adma3_support: 1; /**< ADMA3 support */
unsigned int vdd2_180_support: 1; /**< 1.8V VDD2 support */
unsigned int _rsvd_61: 3; /**< Reserved */
unsigned int hs200_support: 1; /**< HS200 support */
unsigned int hs400_support: 1; /**< HS400 support */
};
/**
* @brief SD host controller I/O control structure
*
* Controls I/O settings for the SDHC. Note that only a subset of these settings
* apply to host controllers in SPI mode. Populate this struct, then call
* @ref sdhc_set_io to apply I/O settings
*/
struct sdhc_io {
enum sdhc_clock_speed clock; /*!< Clock rate */
enum sdhc_bus_mode bus_mode; /*!< command output mode */
enum sdhc_power power_mode; /*!< SD power supply mode */
enum sdhc_bus_width bus_width; /*!< SD bus width */
enum sdhc_timing_mode timing; /*!< SD bus timing */
enum sd_driver_type driver_type; /*!< SD driver type */
enum sd_voltage signal_voltage; /*!< IO signalling voltage (usually 1.8 or 3.3V) */
};
/**
* @brief SD host controller properties
*
* Populated by the host controller using @ref sdhc_get_host_props api.
*/
struct sdhc_host_props {
unsigned int f_max; /*!< Max bus frequency */
unsigned int f_min; /*!< Min bus frequency */
unsigned int power_delay; /*!< Delay to allow SD to power up or down (in ms) */
struct sdhc_host_caps host_caps; /*!< Host capability bitfield */
uint32_t max_current_330; /*!< Max current (in mA) at 3.3V */
uint32_t max_current_300; /*!< Max current (in mA) at 3.0V */
uint32_t max_current_180; /*!< Max current (in mA) at 1.8V */
bool is_spi; /*!< Is the host using SPI mode */
};
/**
* @brief SD host controller interrupt sources
*
* Interrupt sources for SD host controller.
*/
enum sdhc_interrupt_source {
SDHC_INT_SDIO = BIT(0), /*!< Card interrupt, used by SDIO cards */
SDHC_INT_INSERTED = BIT(1), /*!< Card was inserted into slot */
SDHC_INT_REMOVED = BIT(2), /*!< Card was removed from slot */
};
/**
* @typedef sdhc_interrupt_cb_t
* @brief SDHC card interrupt callback prototype
*
* Function prototype for SDHC card interrupt callback.
* @param dev: SDHC device that produced interrupt
* @param reason: one of @ref sdhc_interrupt_source values.
* @param user_data: User data, set via @ref sdhc_enable_interrupt
*/
typedef void (*sdhc_interrupt_cb_t)(const struct device *dev, int reason,
const void *user_data);
__subsystem struct sdhc_driver_api {
int (*reset)(const struct device *dev);
int (*request)(const struct device *dev,
struct sdhc_command *cmd,
struct sdhc_data *data);
int (*set_io)(const struct device *dev, struct sdhc_io *ios);
int (*get_card_present)(const struct device *dev);
int (*execute_tuning)(const struct device *dev);
int (*card_busy)(const struct device *dev);
int (*get_host_props)(const struct device *dev,
struct sdhc_host_props *props);
int (*enable_interrupt)(const struct device *dev,
sdhc_interrupt_cb_t callback,
int sources, void *user_data);
int (*disable_interrupt)(const struct device *dev, int sources);
};
/**
* @brief reset SDHC controller state
*
* Used when the SDHC has encountered an error. Resetting the SDHC controller
* should clear all errors on the SDHC, but does not necessarily reset I/O
* settings to boot (this can be done with @ref sdhc_set_io)
*
* @param dev: SD host controller device
* @retval 0 reset succeeded
* @retval -ETIMEDOUT: controller reset timed out
* @retval -EIO: reset failed
*/
__syscall int sdhc_hw_reset(const struct device *dev);
static inline int z_impl_sdhc_hw_reset(const struct device *dev)
{
const struct sdhc_driver_api *api = (const struct sdhc_driver_api *)dev->api;
if (!api->reset) {
return -ENOSYS;
}
return api->reset(dev);
}
/**
* @brief Send command to SDHC
*
* Sends a command to the SD host controller, which will send this command to
* attached SD cards.
* @param dev: SDHC device
* @param cmd: SDHC command
* @param data: SDHC data. Leave NULL to send SD command without data.
* @retval 0 command was sent successfully
* @retval -ETIMEDOUT command timed out while sending
* @retval -ENOTSUP host controller does not support command
* @retval -EIO: I/O error
*/
__syscall int sdhc_request(const struct device *dev, struct sdhc_command *cmd,
struct sdhc_data *data);
static inline int z_impl_sdhc_request(const struct device *dev,
struct sdhc_command *cmd,
struct sdhc_data *data)
{
const struct sdhc_driver_api *api = (const struct sdhc_driver_api *)dev->api;
if (!api->request) {
return -ENOSYS;
}
return api->request(dev, cmd, data);
}
/**
* @brief set I/O properties of SDHC
*
* I/O properties should be reconfigured when the card has been sent a command
* to change its own SD settings. This function can also be used to toggle
* power to the SD card.
* @param dev: SDHC device
* @param io: I/O properties
* @return 0 I/O was configured correctly
* @return -ENOTSUP controller does not support these I/O settings
* @return -EIO controller could not configure I/O settings
*/
__syscall int sdhc_set_io(const struct device *dev, struct sdhc_io *io);
static inline int z_impl_sdhc_set_io(const struct device *dev,
struct sdhc_io *io)
{
const struct sdhc_driver_api *api = (const struct sdhc_driver_api *)dev->api;
if (!api->set_io) {
return -ENOSYS;
}
return api->set_io(dev, io);
}
/**
* @brief check for SDHC card presence
*
* Checks if card is present on the SD bus. Note that if a controller
* requires cards be powered up to detect presence, it should do so in
* this function.
* @param dev: SDHC device
* @retval 1 card is present
* @retval 0 card is not present
* @retval -EIO I/O error
*/
__syscall int sdhc_card_present(const struct device *dev);
static inline int z_impl_sdhc_card_present(const struct device *dev)
{
const struct sdhc_driver_api *api = (const struct sdhc_driver_api *)dev->api;
if (!api->get_card_present) {
return -ENOSYS;
}
return api->get_card_present(dev);
}
/**
* @brief run SDHC tuning
*
* SD cards require signal tuning for UHS modes SDR104 and SDR50. This function
* allows an application to request the SD host controller to tune the card.
* @param dev: SDHC device
* @retval 0 tuning succeeded, card is ready for commands
* @retval -ETIMEDOUT: tuning failed after timeout
* @retval -ENOTSUP: controller does not support tuning
* @retval -EIO: I/O error while tuning
*/
__syscall int sdhc_execute_tuning(const struct device *dev);
static inline int z_impl_sdhc_execute_tuning(const struct device *dev)
{
const struct sdhc_driver_api *api = (const struct sdhc_driver_api *)dev->api;
if (!api->execute_tuning) {
return -ENOSYS;
}
return api->execute_tuning(dev);
}
/**
* @brief check if SD card is busy
*
* This check should generally be implemented as checking the line level of the
* DAT[0:3] lines of the SD bus. No SD commands need to be sent, the controller
* simply needs to report the status of the SD bus.
* @param dev: SDHC device
* @retval 0 card is not busy
* @retval 1 card is busy
* @retval -EIO I/O error
*/
__syscall int sdhc_card_busy(const struct device *dev);
static inline int z_impl_sdhc_card_busy(const struct device *dev)
{
const struct sdhc_driver_api *api = (const struct sdhc_driver_api *)dev->api;
if (!api->card_busy) {
return -ENOSYS;
}
return api->card_busy(dev);
}
/**
* @brief Get SD host controller properties
*
* Gets host properties from the host controller. Host controller should
* initialize all values in the @ref sdhc_host_props structure provided.
* @param dev: SDHC device
* @param props property structure to be filled by sdhc driver
* @retval 0 function succeeded.
* @retval -ENOTSUP host controller does not support this call
*/
__syscall int sdhc_get_host_props(const struct device *dev,
struct sdhc_host_props *props);
static inline int z_impl_sdhc_get_host_props(const struct device *dev,
struct sdhc_host_props *props)
{
const struct sdhc_driver_api *api = (const struct sdhc_driver_api *)dev->api;
if (!api->get_host_props) {
return -ENOSYS;
}
return api->get_host_props(dev, props);
}
/**
* @brief Enable SDHC interrupt sources.
*
* Enables SDHC interrupt sources. Each subsequent call of this function
* should replace the previous callback set, and leave only the interrupts
* specified in the "sources" argument enabled.
* @param dev: SDHC device
* @param callback: Callback called when interrupt occurs
* @param sources: bitmask of @ref sdhc_interrupt_source values
* indicating which interrupts should produce a callback
* @param user_data: parameter that will be passed to callback function
* @retval 0 interrupts were enabled, and callback was installed
* @retval -ENOTSUP: controller does not support this function
* @retval -EIO: I/O error
*/
__syscall int sdhc_enable_interrupt(const struct device *dev,
sdhc_interrupt_cb_t callback,
int sources, void *user_data);
static inline int z_impl_sdhc_enable_interrupt(const struct device *dev,
sdhc_interrupt_cb_t callback,
int sources, void *user_data)
{
const struct sdhc_driver_api *api = (const struct sdhc_driver_api *)dev->api;
if (!api->enable_interrupt) {
return -ENOSYS;
}
return api->enable_interrupt(dev, callback, sources, user_data);
}
/**
* @brief Disable SDHC interrupt sources
*
* Disables SDHC interrupt sources. If multiple sources are enabled, only
* the ones specified in "sources" will be masked.
* @param dev: SDHC device
* @param sources: bitmask of @ref sdhc_interrupt_source values
* indicating which interrupts should be disabled.
* @retval 0 interrupts were disabled
* @retval -ENOTSUP: controller does not support this function
* @retval -EIO: I/O error
*/
__syscall int sdhc_disable_interrupt(const struct device *dev, int sources);
static inline int z_impl_sdhc_disable_interrupt(const struct device *dev,
int sources)
{
const struct sdhc_driver_api *api = (const struct sdhc_driver_api *)dev->api;
if (!api->disable_interrupt) {
return -ENOSYS;
}
return api->disable_interrupt(dev, sources);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/sdhc.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_SDHC_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/sdhc.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 4,316 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public APIs for the I2S (Inter-IC Sound) bus drivers.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_I2S_H_
#define ZEPHYR_INCLUDE_DRIVERS_I2S_H_
/**
* @defgroup i2s_interface I2S Interface
* @since 1.9
* @version 1.0.0
* @ingroup io_interfaces
* @brief I2S (Inter-IC Sound) Interface
*
* The I2S API provides support for the standard I2S interface standard as well
* as common non-standard extensions such as PCM Short/Long Frame Sync,
* Left/Right Justified Data Format.
* @{
*/
#include <zephyr/types.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* The following #defines are used to configure the I2S controller.
*/
/** I2S data stream format options */
typedef uint8_t i2s_fmt_t;
/** Data Format bit field position. */
#define I2S_FMT_DATA_FORMAT_SHIFT 0
/** Data Format bit field mask. */
#define I2S_FMT_DATA_FORMAT_MASK (0x7 << I2S_FMT_DATA_FORMAT_SHIFT)
/** @brief Standard I2S Data Format.
*
* Serial data is transmitted in two's complement with the MSB first. Both
* Word Select (WS) and Serial Data (SD) signals are sampled on the rising edge
* of the clock signal (SCK). The MSB is always sent one clock period after the
* WS changes. Left channel data are sent first indicated by WS = 0, followed
* by right channel data indicated by WS = 1.
*
* -. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-.
* SCK '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '
* -. .-------------------------------.
* WS '-------------------------------' '----
* -.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.
* SD | |MSB| |...| |LSB| x |...| x |MSB| |...| |LSB| x |...| x |
* -'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'
* | Left channel | Right channel |
*/
#define I2S_FMT_DATA_FORMAT_I2S (0 << I2S_FMT_DATA_FORMAT_SHIFT)
/** @brief PCM Short Frame Sync Data Format.
*
* Serial data is transmitted in two's complement with the MSB first. Both
* Word Select (WS) and Serial Data (SD) signals are sampled on the falling edge
* of the clock signal (SCK). The falling edge of the frame sync signal (WS)
* indicates the start of the PCM word. The frame sync is one clock cycle long.
* An arbitrary number of data words can be sent in one frame.
*
* .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-.
* SCK -' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-
* .---. .---.
* WS -' '- -' '-
* -.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---
* SD | |MSB| |...| |LSB|MSB| |...| |LSB|MSB| |...| |LSB|
* -'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---
* | Word 1 | Word 2 | Word 3 | Word n |
*/
#define I2S_FMT_DATA_FORMAT_PCM_SHORT (1 << I2S_FMT_DATA_FORMAT_SHIFT)
/** @brief PCM Long Frame Sync Data Format.
*
* Serial data is transmitted in two's complement with the MSB first. Both
* Word Select (WS) and Serial Data (SD) signals are sampled on the falling edge
* of the clock signal (SCK). The rising edge of the frame sync signal (WS)
* indicates the start of the PCM word. The frame sync has an arbitrary length,
* however it has to fall before the start of the next frame. An arbitrary
* number of data words can be sent in one frame.
*
* .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-.
* SCK -' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-
* .--- ---. ---. ---. .---
* WS -' '- '- '- -'
* -.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---
* SD | |MSB| |...| |LSB|MSB| |...| |LSB|MSB| |...| |LSB|
* -'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---
* | Word 1 | Word 2 | Word 3 | Word n |
*/
#define I2S_FMT_DATA_FORMAT_PCM_LONG (2 << I2S_FMT_DATA_FORMAT_SHIFT)
/**
* @brief Left Justified Data Format.
*
* Serial data is transmitted in two's complement with the MSB first. Both
* Word Select (WS) and Serial Data (SD) signals are sampled on the rising edge
* of the clock signal (SCK). The bits within the data word are left justified
* such that the MSB is always sent in the clock period following the WS
* transition. Left channel data are sent first indicated by WS = 1, followed
* by right channel data indicated by WS = 0.
*
* .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-.
* SCK -' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-
* .-------------------------------. .-
* WS ---' '-------------------------------'
* ---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.-
* SD |MSB| |...| |LSB| x |...| x |MSB| |...| |LSB| x |...| x |
* ---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'-
* | Left channel | Right channel |
*/
#define I2S_FMT_DATA_FORMAT_LEFT_JUSTIFIED (3 << I2S_FMT_DATA_FORMAT_SHIFT)
/**
* @brief Right Justified Data Format.
*
* Serial data is transmitted in two's complement with the MSB first. Both
* Word Select (WS) and Serial Data (SD) signals are sampled on the rising edge
* of the clock signal (SCK). The bits within the data word are right justified
* such that the LSB is always sent in the clock period preceding the WS
* transition. Left channel data are sent first indicated by WS = 1, followed
* by right channel data indicated by WS = 0.
*
* .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-. .-.
* SCK -' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-
* .-------------------------------. .-
* WS ---' '-------------------------------'
* ---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.-
* SD | x |...| x |MSB| |...| |LSB| x |...| x |MSB| |...| |LSB|
* ---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'-
* | Left channel | Right channel |
*/
#define I2S_FMT_DATA_FORMAT_RIGHT_JUSTIFIED (4 << I2S_FMT_DATA_FORMAT_SHIFT)
/** Send MSB first */
#define I2S_FMT_DATA_ORDER_MSB (0 << 3)
/** Send LSB first */
#define I2S_FMT_DATA_ORDER_LSB BIT(3)
/** Invert bit ordering, send LSB first */
#define I2S_FMT_DATA_ORDER_INV I2S_FMT_DATA_ORDER_LSB
/** Data Format bit field position. */
#define I2S_FMT_CLK_FORMAT_SHIFT 4
/** Data Format bit field mask. */
#define I2S_FMT_CLK_FORMAT_MASK (0x3 << I2S_FMT_CLK_FORMAT_SHIFT)
/** Invert bit clock */
#define I2S_FMT_BIT_CLK_INV BIT(4)
/** Invert frame clock */
#define I2S_FMT_FRAME_CLK_INV BIT(5)
/** Normal Frame, Normal Bit Clk */
#define I2S_FMT_CLK_NF_NB (0 << I2S_FMT_CLK_FORMAT_SHIFT)
/** Normal Frame, Inverted Bit Clk */
#define I2S_FMT_CLK_NF_IB (1 << I2S_FMT_CLK_FORMAT_SHIFT)
/** Inverted Frame, Normal Bit Clk */
#define I2S_FMT_CLK_IF_NB (2 << I2S_FMT_CLK_FORMAT_SHIFT)
/** Inverted Frame, Inverted Bit Clk */
#define I2S_FMT_CLK_IF_IB (3 << I2S_FMT_CLK_FORMAT_SHIFT)
/** I2S configuration options */
typedef uint8_t i2s_opt_t;
/** Run bit clock continuously */
#define I2S_OPT_BIT_CLK_CONT (0 << 0)
/** Run bit clock when sending data only */
#define I2S_OPT_BIT_CLK_GATED BIT(0)
/** I2S driver is bit clock master */
#define I2S_OPT_BIT_CLK_MASTER (0 << 1)
/** I2S driver is bit clock slave */
#define I2S_OPT_BIT_CLK_SLAVE BIT(1)
/** I2S driver is frame clock master */
#define I2S_OPT_FRAME_CLK_MASTER (0 << 2)
/** I2S driver is frame clock slave */
#define I2S_OPT_FRAME_CLK_SLAVE BIT(2)
/** @brief Loop back mode.
*
* In loop back mode RX input will be connected internally to TX output.
* This is used primarily for testing.
*/
#define I2S_OPT_LOOPBACK BIT(7)
/** @brief Ping pong mode
*
* In ping pong mode TX output will keep alternating between a ping buffer
* and a pong buffer. This is normally used in audio streams when one buffer
* is being populated while the other is being played (DMAed) and vice versa.
* So, in this mode, 2 sets of buffers fixed in size are used. Static Arrays
* are used to achieve this and hence they are never freed.
*/
#define I2S_OPT_PINGPONG BIT(6)
/**
* @brief I2C Direction
*/
enum i2s_dir {
/** Receive data */
I2S_DIR_RX,
/** Transmit data */
I2S_DIR_TX,
/** Both receive and transmit data */
I2S_DIR_BOTH,
};
/** Interface state */
enum i2s_state {
/** @brief The interface is not ready.
*
* The interface was initialized but is not yet ready to receive /
* transmit data. Call i2s_configure() to configure interface and change
* its state to READY.
*/
I2S_STATE_NOT_READY,
/** The interface is ready to receive / transmit data. */
I2S_STATE_READY,
/** The interface is receiving / transmitting data. */
I2S_STATE_RUNNING,
/** The interface is draining its transmit queue. */
I2S_STATE_STOPPING,
/** TX buffer underrun or RX buffer overrun has occurred. */
I2S_STATE_ERROR,
};
/** Trigger command */
enum i2s_trigger_cmd {
/** @brief Start the transmission / reception of data.
*
* If I2S_DIR_TX is set some data has to be queued for transmission by
* the i2s_write() function. This trigger can be used in READY state
* only and changes the interface state to RUNNING.
*/
I2S_TRIGGER_START,
/** @brief Stop the transmission / reception of data.
*
* Stop the transmission / reception of data at the end of the current
* memory block. This trigger can be used in RUNNING state only and at
* first changes the interface state to STOPPING. When the current TX /
* RX block is transmitted / received the state is changed to READY.
* Subsequent START trigger will resume transmission / reception where
* it stopped.
*/
I2S_TRIGGER_STOP,
/** @brief Empty the transmit queue.
*
* Send all data in the transmit queue and stop the transmission.
* If the trigger is applied to the RX queue it has the same effect as
* I2S_TRIGGER_STOP. This trigger can be used in RUNNING state only and
* at first changes the interface state to STOPPING. When all TX blocks
* are transmitted the state is changed to READY.
*/
I2S_TRIGGER_DRAIN,
/** @brief Discard the transmit / receive queue.
*
* Stop the transmission / reception immediately and discard the
* contents of the respective queue. This trigger can be used in any
* state other than NOT_READY and changes the interface state to READY.
*/
I2S_TRIGGER_DROP,
/** @brief Prepare the queues after underrun/overrun error has occurred.
*
* This trigger can be used in ERROR state only and changes the
* interface state to READY.
*/
I2S_TRIGGER_PREPARE,
};
/** @struct i2s_config
* @brief Interface configuration options.
*
* Memory slab pointed to by the mem_slab field has to be defined and
* initialized by the user. For I2S driver to function correctly number of
* memory blocks in a slab has to be at least 2 per queue. Size of the memory
* block should be multiple of frame_size where frame_size = (channels *
* word_size_bytes). As an example 16 bit word will occupy 2 bytes, 24 or 32
* bit word will occupy 4 bytes.
*
* Please check Zephyr Kernel Primer for more information on memory slabs.
*
* @remark When I2S data format is selected parameter channels is ignored,
* number of words in a frame is always 2.
*/
struct i2s_config {
/** Number of bits representing one data word. */
uint8_t word_size;
/** Number of words per frame. */
uint8_t channels;
/** Data stream format as defined by I2S_FMT_* constants. */
i2s_fmt_t format;
/** Configuration options as defined by I2S_OPT_* constants. */
i2s_opt_t options;
/** Frame clock (WS) frequency, this is sampling rate. */
uint32_t frame_clk_freq;
/** Memory slab to store RX/TX data. */
struct k_mem_slab *mem_slab;
/** Size of one RX/TX memory block (buffer) in bytes. */
size_t block_size;
/** Read/Write timeout. Number of milliseconds to wait in case TX queue
* is full or RX queue is empty, or 0, or SYS_FOREVER_MS.
*/
int32_t timeout;
};
/**
* @cond INTERNAL_HIDDEN
*
* For internal use only, skip these in public documentation.
*/
__subsystem struct i2s_driver_api {
int (*configure)(const struct device *dev, enum i2s_dir dir,
const struct i2s_config *cfg);
const struct i2s_config *(*config_get)(const struct device *dev,
enum i2s_dir dir);
int (*read)(const struct device *dev, void **mem_block, size_t *size);
int (*write)(const struct device *dev, void *mem_block, size_t size);
int (*trigger)(const struct device *dev, enum i2s_dir dir,
enum i2s_trigger_cmd cmd);
};
/**
* @endcond
*/
/**
* @brief Configure operation of a host I2S controller.
*
* The dir parameter specifies if Transmit (TX) or Receive (RX) direction
* will be configured by data provided via cfg parameter.
*
* The function can be called in NOT_READY or READY state only. If executed
* successfully the function will change the interface state to READY.
*
* If the function is called with the parameter cfg->frame_clk_freq set to 0
* the interface state will be changed to NOT_READY.
*
* @param dev Pointer to the device structure for the driver instance.
* @param dir Stream direction: RX, TX, or both, as defined by I2S_DIR_*.
* The I2S_DIR_BOTH value may not be supported by some drivers.
* For those, the RX and TX streams need to be configured separately.
* @param cfg Pointer to the structure containing configuration parameters.
*
* @retval 0 If successful.
* @retval -EINVAL Invalid argument.
* @retval -ENOSYS I2S_DIR_BOTH value is not supported.
*/
__syscall int i2s_configure(const struct device *dev, enum i2s_dir dir,
const struct i2s_config *cfg);
static inline int z_impl_i2s_configure(const struct device *dev,
enum i2s_dir dir,
const struct i2s_config *cfg)
{
const struct i2s_driver_api *api =
(const struct i2s_driver_api *)dev->api;
return api->configure(dev, dir, cfg);
}
/**
* @brief Fetch configuration information of a host I2S controller
*
* @param dev Pointer to the device structure for the driver instance
* @param dir Stream direction: RX or TX as defined by I2S_DIR_*
* @retval Pointer to the structure containing configuration parameters,
* or NULL if un-configured
*/
static inline const struct i2s_config *i2s_config_get(const struct device *dev,
enum i2s_dir dir)
{
const struct i2s_driver_api *api =
(const struct i2s_driver_api *)dev->api;
return api->config_get(dev, dir);
}
/**
* @brief Read data from the RX queue.
*
* Data received by the I2S interface is stored in the RX queue consisting of
* memory blocks preallocated by this function from rx_mem_slab (as defined by
* i2s_configure). Ownership of the RX memory block is passed on to the user
* application which has to release it.
*
* The data is read in chunks equal to the size of the memory block. If the
* interface is in READY state the number of bytes read can be smaller.
*
* If there is no data in the RX queue the function will block waiting for
* the next RX memory block to fill in. This operation can timeout as defined
* by i2s_configure. If the timeout value is set to K_NO_WAIT the function
* is non-blocking.
*
* Reading from the RX queue is possible in any state other than NOT_READY.
* If the interface is in the ERROR state it is still possible to read all the
* valid data stored in RX queue. Afterwards the function will return -EIO
* error.
*
* @param dev Pointer to the device structure for the driver instance.
* @param mem_block Pointer to the RX memory block containing received data.
* @param size Pointer to the variable storing the number of bytes read.
*
* @retval 0 If successful.
* @retval -EIO The interface is in NOT_READY or ERROR state and there are no
* more data blocks in the RX queue.
* @retval -EBUSY Returned without waiting.
* @retval -EAGAIN Waiting period timed out.
*/
static inline int i2s_read(const struct device *dev, void **mem_block,
size_t *size)
{
const struct i2s_driver_api *api =
(const struct i2s_driver_api *)dev->api;
return api->read(dev, mem_block, size);
}
/**
* @brief Read data from the RX queue into a provided buffer
*
* Data received by the I2S interface is stored in the RX queue consisting of
* memory blocks preallocated by this function from rx_mem_slab (as defined by
* i2s_configure). Calling this function removes one block from the queue
* which is copied into the provided buffer and then freed.
*
* The provided buffer must be large enough to contain a full memory block
* of data, which is parameterized for the channel via i2s_configure().
*
* This function is otherwise equivalent to i2s_read().
*
* @param dev Pointer to the device structure for the driver instance.
* @param buf Destination buffer for read data, which must be at least the
* as large as the configured memory block size for the RX channel.
* @param size Pointer to the variable storing the number of bytes read.
*
* @retval 0 If successful.
* @retval -EIO The interface is in NOT_READY or ERROR state and there are no
* more data blocks in the RX queue.
* @retval -EBUSY Returned without waiting.
* @retval -EAGAIN Waiting period timed out.
*/
__syscall int i2s_buf_read(const struct device *dev, void *buf, size_t *size);
/**
* @brief Write data to the TX queue.
*
* Data to be sent by the I2S interface is stored first in the TX queue. TX
* queue consists of memory blocks preallocated by the user from tx_mem_slab
* (as defined by i2s_configure). This function takes ownership of the memory
* block and will release it when all data are transmitted.
*
* If there are no free slots in the TX queue the function will block waiting
* for the next TX memory block to be send and removed from the queue. This
* operation can timeout as defined by i2s_configure. If the timeout value is
* set to K_NO_WAIT the function is non-blocking.
*
* Writing to the TX queue is only possible if the interface is in READY or
* RUNNING state.
*
* @param dev Pointer to the device structure for the driver instance.
* @param mem_block Pointer to the TX memory block containing data to be sent.
* @param size Number of bytes to write. This value has to be equal or smaller
* than the size of the memory block.
*
* @retval 0 If successful.
* @retval -EIO The interface is not in READY or RUNNING state.
* @retval -EBUSY Returned without waiting.
* @retval -EAGAIN Waiting period timed out.
*/
static inline int i2s_write(const struct device *dev, void *mem_block,
size_t size)
{
const struct i2s_driver_api *api =
(const struct i2s_driver_api *)dev->api;
return api->write(dev, mem_block, size);
}
/**
* @brief Write data to the TX queue from a provided buffer
*
* This function acquires a memory block from the I2S channel TX queue
* and copies the provided data buffer into it. It is otherwise equivalent
* to i2s_write().
*
* @param dev Pointer to the device structure for the driver instance.
* @param buf Pointer to a buffer containing the data to transmit.
* @param size Number of bytes to write. This value has to be equal or smaller
* than the size of the channel's TX memory block configuration.
*
* @retval 0 If successful.
* @retval -EIO The interface is not in READY or RUNNING state.
* @retval -EBUSY Returned without waiting.
* @retval -EAGAIN Waiting period timed out.
* @retval -ENOMEM No memory in TX slab queue.
* @retval -EINVAL Size parameter larger than TX queue memory block.
*/
__syscall int i2s_buf_write(const struct device *dev, void *buf, size_t size);
/**
* @brief Send a trigger command.
*
* @param dev Pointer to the device structure for the driver instance.
* @param dir Stream direction: RX, TX, or both, as defined by I2S_DIR_*.
* The I2S_DIR_BOTH value may not be supported by some drivers.
* For those, triggering need to be done separately for the RX
* and TX streams.
* @param cmd Trigger command.
*
* @retval 0 If successful.
* @retval -EINVAL Invalid argument.
* @retval -EIO The trigger cannot be executed in the current state or a DMA
* channel cannot be allocated.
* @retval -ENOMEM RX/TX memory block not available.
* @retval -ENOSYS I2S_DIR_BOTH value is not supported.
*/
__syscall int i2s_trigger(const struct device *dev, enum i2s_dir dir,
enum i2s_trigger_cmd cmd);
static inline int z_impl_i2s_trigger(const struct device *dev,
enum i2s_dir dir,
enum i2s_trigger_cmd cmd)
{
const struct i2s_driver_api *api =
(const struct i2s_driver_api *)dev->api;
return api->trigger(dev, dir, cmd);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/i2s.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_I2S_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/i2s.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 5,676 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public API for Keyboard scan matrix devices.
* The scope of this API is simply to report which key event was triggered
* and users can later decode keys using their desired scan code tables in
* their application. In addition, typematic rate and delay can easily be
* implemented using a timer if desired.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_KB_SCAN_H_
#define ZEPHYR_INCLUDE_DRIVERS_KB_SCAN_H_
#include <errno.h>
#include <zephyr/types.h>
#include <stddef.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief KSCAN APIs
* @defgroup kscan_interface Keyboard Scan Driver APIs
* @since 2.1
* @version 1.0.0
* @ingroup io_interfaces
* @{
*/
/**
* @brief Keyboard scan callback called when user press/release
* a key on a matrix keyboard.
*
* @param dev Pointer to the device structure for the driver instance.
* @param row Describes row change.
* @param column Describes column change.
* @param pressed Describes the kind of key event.
*/
typedef void (*kscan_callback_t)(const struct device *dev, uint32_t row,
uint32_t column,
bool pressed);
/**
* @cond INTERNAL_HIDDEN
*
* Keyboard scan driver API definition and system call entry points.
*
* (Internal use only.)
*/
typedef int (*kscan_config_t)(const struct device *dev,
kscan_callback_t callback);
typedef int (*kscan_disable_callback_t)(const struct device *dev);
typedef int (*kscan_enable_callback_t)(const struct device *dev);
__subsystem struct kscan_driver_api {
kscan_config_t config;
kscan_disable_callback_t disable_callback;
kscan_enable_callback_t enable_callback;
};
/**
* @endcond
*/
/**
* @brief Configure a Keyboard scan instance.
*
* @param dev Pointer to the device structure for the driver instance.
* @param callback called when keyboard devices reply to a keyboard
* event such as key pressed/released.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int kscan_config(const struct device *dev,
kscan_callback_t callback);
static inline int z_impl_kscan_config(const struct device *dev,
kscan_callback_t callback)
{
const struct kscan_driver_api *api =
(struct kscan_driver_api *)dev->api;
return api->config(dev, callback);
}
/**
* @brief Enables callback.
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int kscan_enable_callback(const struct device *dev);
static inline int z_impl_kscan_enable_callback(const struct device *dev)
{
const struct kscan_driver_api *api =
(const struct kscan_driver_api *)dev->api;
if (api->enable_callback == NULL) {
return -ENOSYS;
}
return api->enable_callback(dev);
}
/**
* @brief Disables callback.
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval Negative errno code if failure.
*/
__syscall int kscan_disable_callback(const struct device *dev);
static inline int z_impl_kscan_disable_callback(const struct device *dev)
{
const struct kscan_driver_api *api =
(const struct kscan_driver_api *)dev->api;
if (api->disable_callback == NULL) {
return -ENOSYS;
}
return api->disable_callback(dev);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/kscan.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_KB_SCAN_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/kscan.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 811 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public 1-Wire Driver APIs
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_W1_H_
#define ZEPHYR_INCLUDE_DRIVERS_W1_H_
#include <zephyr/types.h>
#include <zephyr/device.h>
#include <zephyr/kernel.h>
#include <zephyr/sys/crc.h>
#include <zephyr/sys/byteorder.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief 1-Wire Interface
* @defgroup w1_interface 1-Wire Interface
* @since 3.2
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
/** @cond INTERNAL_HIDDEN */
/*
* Count the number of slaves expected on the bus.
* This can be used to decide if the bus has a multidrop topology or
* only a single slave is present.
* There is a comma after each ordinal (including the last)
* Hence FOR_EACH adds "+1" once too often which has to be subtracted in the end.
*/
#define F1(x) 1
#define W1_SLAVE_COUNT(node_id) \
(FOR_EACH(F1, (+), DT_SUPPORTS_DEP_ORDS(node_id)) - 1)
#define W1_INST_SLAVE_COUNT(inst) \
(W1_SLAVE_COUNT(DT_DRV_INST(inst)))
/** @endcond */
/**
* @brief Defines the 1-Wire master settings types, which are runtime configurable.
*/
enum w1_settings_type {
/** Overdrive speed is enabled in case a value of 1 is passed and
* disabled passing 0.
*/
W1_SETTING_SPEED,
/**
* The strong pullup resistor is activated immediately after the next
* written data block by passing a value of 1, and deactivated passing 0.
*/
W1_SETTING_STRONG_PULLUP,
/**
* Number of different settings types.
*/
W1_SETINGS_TYPE_COUNT,
};
/** @cond INTERNAL_HIDDEN */
/** Configuration common to all 1-Wire master implementations. */
struct w1_master_config {
/* Number of connected slaves */
uint16_t slave_count;
};
/** Data common to all 1-Wire master implementations. */
struct w1_master_data {
/* The mutex used by w1_lock_bus and w1_unlock_bus methods */
struct k_mutex bus_lock;
};
typedef int (*w1_reset_bus_t)(const struct device *dev);
typedef int (*w1_read_bit_t)(const struct device *dev);
typedef int (*w1_write_bit_t)(const struct device *dev, bool bit);
typedef int (*w1_read_byte_t)(const struct device *dev);
typedef int (*w1_write_byte_t)(const struct device *dev, const uint8_t byte);
typedef int (*w1_read_block_t)(const struct device *dev, uint8_t *buffer,
size_t len);
typedef int (*w1_write_block_t)(const struct device *dev, const uint8_t *buffer,
size_t len);
typedef size_t (*w1_get_slave_count_t)(const struct device *dev);
typedef int (*w1_configure_t)(const struct device *dev,
enum w1_settings_type type, uint32_t value);
typedef int (*w1_change_bus_lock_t)(const struct device *dev, bool lock);
__subsystem struct w1_driver_api {
w1_reset_bus_t reset_bus;
w1_read_bit_t read_bit;
w1_write_bit_t write_bit;
w1_read_byte_t read_byte;
w1_write_byte_t write_byte;
w1_read_block_t read_block;
w1_write_block_t write_block;
w1_configure_t configure;
w1_change_bus_lock_t change_bus_lock;
};
/** @endcond */
/** @cond INTERNAL_HIDDEN */
__syscall int w1_change_bus_lock(const struct device *dev, bool lock);
static inline int z_impl_w1_change_bus_lock(const struct device *dev, bool lock)
{
struct w1_master_data *ctrl_data = (struct w1_master_data *)dev->data;
const struct w1_driver_api *api = (const struct w1_driver_api *)dev->api;
if (api->change_bus_lock) {
return api->change_bus_lock(dev, lock);
}
if (lock) {
return k_mutex_lock(&ctrl_data->bus_lock, K_FOREVER);
} else {
return k_mutex_unlock(&ctrl_data->bus_lock);
}
}
/** @endcond */
/**
* @brief Lock the 1-wire bus to prevent simultaneous access.
*
* This routine locks the bus to prevent simultaneous access from different
* threads. The calling thread waits until the bus becomes available.
* A thread is permitted to lock a mutex it has already locked.
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval -errno Negative error code on error.
*/
static inline int w1_lock_bus(const struct device *dev)
{
return w1_change_bus_lock(dev, true);
}
/**
* @brief Unlock the 1-wire bus.
*
* This routine unlocks the bus to permit access to bus line.
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval -errno Negative error code on error.
*/
static inline int w1_unlock_bus(const struct device *dev)
{
return w1_change_bus_lock(dev, false);
}
/**
* @brief 1-Wire data link layer
* @defgroup w1_data_link 1-Wire data link layer
* @ingroup w1_interface
* @{
*/
/**
* @brief Reset the 1-Wire bus to prepare slaves for communication.
*
* This routine resets all 1-Wire bus slaves such that they are
* ready to receive a command.
* Connected slaves answer with a presence pulse once they are ready
* to receive data.
*
* In case the driver supports both standard speed and overdrive speed,
* the reset routine takes care of sendig either a short or a long reset pulse
* depending on the current state. The speed can be changed using
* @a w1_configure().
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @retval 0 If no slaves answer with a present pulse.
* @retval 1 If at least one slave answers with a present pulse.
* @retval -errno Negative error code on error.
*/
__syscall int w1_reset_bus(const struct device *dev);
static inline int z_impl_w1_reset_bus(const struct device *dev)
{
const struct w1_driver_api *api = (const struct w1_driver_api *)dev->api;
return api->reset_bus(dev);
}
/**
* @brief Read a single bit from the 1-Wire bus.
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @retval rx_bit The read bit value on success.
* @retval -errno Negative error code on error.
*/
__syscall int w1_read_bit(const struct device *dev);
static inline int z_impl_w1_read_bit(const struct device *dev)
{
const struct w1_driver_api *api = (const struct w1_driver_api *)dev->api;
return api->read_bit(dev);
}
/**
* @brief Write a single bit to the 1-Wire bus.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param bit Transmitting bit value 1 or 0.
*
* @retval 0 If successful.
* @retval -errno Negative error code on error.
*/
__syscall int w1_write_bit(const struct device *dev, const bool bit);
static inline int z_impl_w1_write_bit(const struct device *dev, bool bit)
{
const struct w1_driver_api *api = (const struct w1_driver_api *)dev->api;
return api->write_bit(dev, bit);
}
/**
* @brief Read a single byte from the 1-Wire bus.
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @retval rx_byte The read byte value on success.
* @retval -errno Negative error code on error.
*/
__syscall int w1_read_byte(const struct device *dev);
static inline int z_impl_w1_read_byte(const struct device *dev)
{
const struct w1_driver_api *api = (const struct w1_driver_api *)dev->api;
return api->read_byte(dev);
}
/**
* @brief Write a single byte to the 1-Wire bus.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param byte Transmitting byte.
*
* @retval 0 If successful.
* @retval -errno Negative error code on error.
*/
__syscall int w1_write_byte(const struct device *dev, uint8_t byte);
static inline int z_impl_w1_write_byte(const struct device *dev, uint8_t byte)
{
const struct w1_driver_api *api = (const struct w1_driver_api *)dev->api;
return api->write_byte(dev, byte);
}
/**
* @brief Read a block of data from the 1-Wire bus.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param[out] buffer Pointer to receive buffer.
* @param len Length of receiving buffer (in bytes).
*
* @retval 0 If successful.
* @retval -errno Negative error code on error.
*/
__syscall int w1_read_block(const struct device *dev, uint8_t *buffer, size_t len);
/**
* @brief Write a block of data from the 1-Wire bus.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param[in] buffer Pointer to transmitting buffer.
* @param len Length of transmitting buffer (in bytes).
*
* @retval 0 If successful.
* @retval -errno Negative error code on error.
*/
__syscall int w1_write_block(const struct device *dev,
const uint8_t *buffer, size_t len);
/**
* @brief Get the number of slaves on the bus.
*
* @param[in] dev Pointer to the device structure for the driver instance.
*
* @retval slave_count Positive Number of connected 1-Wire slaves on success.
* @retval -errno Negative error code on error.
*/
__syscall size_t w1_get_slave_count(const struct device *dev);
static inline size_t z_impl_w1_get_slave_count(const struct device *dev)
{
const struct w1_master_config *ctrl_cfg =
(const struct w1_master_config *)dev->config;
return ctrl_cfg->slave_count;
}
/**
* @brief Configure parameters of the 1-Wire master.
*
* Allowed configuration parameters are defined in enum w1_settings_type,
* but master devices may not support all types.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param type Enum specifying the setting type.
* @param value The new value for the passed settings type.
*
* @retval 0 If successful.
* @retval -ENOTSUP The master doesn't support the configuration of the supplied type.
* @retval -EIO General input / output error, failed to configure master devices.
*/
__syscall int w1_configure(const struct device *dev,
enum w1_settings_type type, uint32_t value);
static inline int z_impl_w1_configure(const struct device *dev,
enum w1_settings_type type, uint32_t value)
{
const struct w1_driver_api *api = (const struct w1_driver_api *)dev->api;
return api->configure(dev, type, value);
}
/**
* @}
*/
/**
* @brief 1-Wire network layer
* @defgroup w1_network 1-Wire network layer
* @ingroup w1_interface
* @{
*/
/**
* @name 1-Wire ROM Commands
* @{
*/
/**
* This command allows the bus master to read the slave devices without
* providing their ROM code.
*/
#define W1_CMD_SKIP_ROM 0xCC
/**
* This command allows the bus master to address a specific slave device by
* providing its ROM code.
*/
#define W1_CMD_MATCH_ROM 0x55
/**
* This command allows the bus master to resume a previous read out from where
* it left off.
*/
#define W1_CMD_RESUME 0xA5
/**
* This command allows the bus master to read the ROM code from a single slave
* device.
* This command should be used when there is only a single slave device on the
* bus.
*/
#define W1_CMD_READ_ROM 0x33
/**
* This command allows the bus master to discover the addresses (i.e., ROM
* codes) of all slave devices on the bus.
*/
#define W1_CMD_SEARCH_ROM 0xF0
/**
* This command allows the bus master to identify which devices have experienced
* an alarm condition.
*/
#define W1_CMD_SEARCH_ALARM 0xEC
/**
* This command allows the bus master to address all devices on the bus and then
* switch them to overdrive speed.
*/
#define W1_CMD_OVERDRIVE_SKIP_ROM 0x3C
/**
* This command allows the bus master to address a specific device and switch it
* to overdrive speed.
*/
#define W1_CMD_OVERDRIVE_MATCH_ROM 0x69
/** @} */
/**
* @name CRC Defines
* @{
*/
/** Seed value used to calculate the 1-Wire 8-bit crc. */
#define W1_CRC8_SEED 0x00
/** Polynomial used to calculate the 1-Wire 8-bit crc. */
#define W1_CRC8_POLYNOMIAL 0x8C
/** Seed value used to calculate the 1-Wire 16-bit crc. */
#define W1_CRC16_SEED 0x0000
/** Polynomial used to calculate the 1-Wire 16-bit crc. */
#define W1_CRC16_POLYNOMIAL 0xa001
/** @} */
/** This flag can be passed to searches in order to not filter on family ID. */
#define W1_SEARCH_ALL_FAMILIES 0x00
/** Initialize all w1_rom struct members to zero. */
#define W1_ROM_INIT_ZERO \
{ \
.family = 0, .serial = { 0 }, .crc = 0, \
}
/**
* @brief w1_rom struct.
*/
struct w1_rom {
/** @brief The 1-Wire family code identifying the slave device type.
*
* An incomplete list of family codes is available at:
* path_to_url
* others are documented in the respective device data sheet.
*/
uint8_t family;
/** The serial together with the family code composes the unique 56-bit id */
uint8_t serial[6];
/** 8-bit checksum of the 56-bit unique id. */
uint8_t crc;
};
/**
* @brief Node specific 1-wire configuration struct.
*
* This struct is passed to network functions, such that they can configure
* the bus to address the specific slave using the selected speed.
*/
struct w1_slave_config {
/** Unique 1-Wire ROM. */
struct w1_rom rom;
/** overdrive speed is used if set to 1. */
uint32_t overdrive : 1;
/** @cond INTERNAL_HIDDEN */
uint32_t res : 31;
/** @endcond */
};
/**
* @brief Define the application callback handler function signature
* for searches.
*
* @param rom found The ROM of the found slave.
* @param user_data User data provided to the w1_search_bus() call.
*/
typedef void (*w1_search_callback_t)(struct w1_rom rom, void *user_data);
/**
* @brief Read Peripheral 64-bit ROM.
*
* This procedure allows the 1-Wire bus master to read the peripherals
* 64-bit ROM without using the Search ROM procedure.
* This command can be used as long as not more than a single peripheral is
* connected to the bus.
* Otherwise data collisions occur and a faulty ROM is read.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param[out] rom Pointer to the ROM structure.
*
* @retval 0 If successful.
* @retval -ENODEV In case no slave responds to reset.
* @retval -errno Other negative error code in case of invalid crc and
* communication errors.
*/
int w1_read_rom(const struct device *dev, struct w1_rom *rom);
/**
* @brief Select a specific slave by broadcasting a selected ROM.
*
* This routine allows the 1-Wire bus master to select a slave
* identified by its unique ROM, such that the next command will target only
* this single selected slave.
*
* This command is only necessary in multidrop environments, otherwise the
* Skip ROM command can be issued.
* Once a slave has been selected, to reduce the communication overhead, the
* resume command can be used instead of this command to communicate with the
* selected slave.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param[in] config Pointer to the slave specific 1-Wire config.
*
* @retval 0 If successful.
* @retval -ENODEV In case no slave responds to reset.
* @retval -errno Other negative error code on error.
*/
int w1_match_rom(const struct device *dev, const struct w1_slave_config *config);
/**
* @brief Select the slave last addressed with a Match ROM or Search ROM command.
*
* This routine allows the 1-Wire bus master to re-select a slave
* device that was already addressed using a Match ROM or Search ROM command.
*
* @param dev Pointer to the device structure for the driver instance.
*
* @retval 0 If successful.
* @retval -ENODEV In case no slave responds to reset.
* @retval -errno Other negative error code on error.
*/
int w1_resume_command(const struct device *dev);
/**
* @brief Select all slaves regardless of ROM.
*
* This routine sets up the bus slaves to receive a command.
* It is usually used when there is only one peripheral on the bus
* to avoid the overhead of the Match ROM command.
* But it can also be used to concurrently write to all slave devices.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param[in] config Pointer to the slave specific 1-Wire config.
*
* @retval 0 If successful.
* @retval -ENODEV In case no slave responds to reset.
* @retval -errno Other negative error code on error.
*/
int w1_skip_rom(const struct device *dev, const struct w1_slave_config *config);
/**
* @brief In single drop configurations use Skip Select command, otherwise use
* Match ROM command.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param[in] config Pointer to the slave specific 1-Wire config.
*
* @retval 0 If successful.
* @retval -ENODEV In case no slave responds to reset.
* @retval -errno Other negative error code on error.
*/
int w1_reset_select(const struct device *dev, const struct w1_slave_config *config);
/**
* @brief Write then read data from the 1-Wire slave with matching ROM.
*
* This routine uses w1_reset_select to select the given ROM.
* Then writes given data and reads the response back from the slave.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param[in] config Pointer to the slave specific 1-Wire config.
* @param[in] write_buf Pointer to the data to be written.
* @param write_len Number of bytes to write.
* @param[out] read_buf Pointer to storage for read data.
* @param read_len Number of bytes to read.
*
* @retval 0 If successful.
* @retval -ENODEV In case no slave responds to reset.
* @retval -errno Other negative error code on error.
*/
int w1_write_read(const struct device *dev, const struct w1_slave_config *config,
const uint8_t *write_buf, size_t write_len,
uint8_t *read_buf, size_t read_len);
/**
* @brief Search 1-wire slaves on the bus.
*
* This function searches slaves on the 1-wire bus, with the possibility
* to search either all slaves or only slaves that have an active alarm state.
* If a callback is passed, the callback is called for each found slave.
*
* The algorithm mostly follows the suggestions of
* path_to_url
*
* Note: Filtering on families is not supported.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param command Can either be W1_SEARCH_ALARM or W1_SEARCH_ROM.
* @param family W1_SEARCH_ALL_FAMILIES searcheas all families,
* filtering on a specific family is not yet supported.
* @param callback Application callback handler function to be called
* for each found slave.
* @param[in] user_data User data to pass to the application callback handler
* function.
*
* @retval slave_count Number of slaves found.
* @retval -errno Negative error code on error.
*/
__syscall int w1_search_bus(const struct device *dev, uint8_t command,
uint8_t family, w1_search_callback_t callback,
void *user_data);
/**
* @brief Search for 1-Wire slave on bus.
*
* This routine can discover unknown slaves on the bus by scanning for the
* unique 64-bit registration number.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param callback Application callback handler function to be called
* for each found slave.
* @param[in] user_data User data to pass to the application callback handler
* function.
*
* @retval slave_count Number of slaves found.
* @retval -errno Negative error code on error.
*/
static inline int w1_search_rom(const struct device *dev,
w1_search_callback_t callback, void *user_data)
{
return w1_search_bus(dev, W1_CMD_SEARCH_ROM, W1_SEARCH_ALL_FAMILIES,
callback, user_data);
}
/**
* @brief Search for 1-Wire slaves with an active alarm.
*
* This routine searches 1-Wire slaves on the bus, which currently have
* an active alarm.
*
* @param[in] dev Pointer to the device structure for the driver instance.
* @param callback Application callback handler function to be called
* for each found slave.
* @param[in] user_data User data to pass to the application callback handler
* function.
*
* @retval slave_count Number of slaves found.
* @retval -errno Negative error code on error.
*/
static inline int w1_search_alarm(const struct device *dev,
w1_search_callback_t callback, void *user_data)
{
return w1_search_bus(dev, W1_CMD_SEARCH_ALARM, W1_SEARCH_ALL_FAMILIES,
callback, user_data);
}
/**
* @brief Function to convert a w1_rom struct to an uint64_t.
*
* @param[in] rom Pointer to the ROM struct.
*
* @retval rom64 The ROM converted to an unsigned integer in endianness.
*/
static inline uint64_t w1_rom_to_uint64(const struct w1_rom *rom)
{
return sys_get_be64((uint8_t *)rom);
}
/**
* @brief Function to write an uint64_t to struct w1_rom pointer.
*
* @param rom64 Unsigned 64 bit integer representing the ROM in host endianness.
* @param[out] rom The ROM struct pointer.
*/
static inline void w1_uint64_to_rom(const uint64_t rom64, struct w1_rom *rom)
{
sys_put_be64(rom64, (uint8_t *)rom);
}
/**
* @brief Compute CRC-8 chacksum as defined in the 1-Wire specification.
*
* The 1-Wire of CRC 8 variant is using 0x31 as its polynomial with the initial
* value set to 0x00.
* This CRC is used to check the correctness of the unique 56-bit ROM.
*
* @param[in] src Input bytes for the computation.
* @param len Length of the input in bytes.
*
* @retval crc The computed CRC8 value.
*/
static inline uint8_t w1_crc8(const uint8_t *src, size_t len)
{
return crc8(src, len, W1_CRC8_POLYNOMIAL, W1_CRC8_SEED, true);
}
/**
* @brief Compute 1-Wire variant of CRC 16
*
* The 16-bit 1-Wire crc variant is using the reflected polynomial function
* X^16 + X^15 * + X^2 + 1 with the initial value set to 0x0000.
* See also APPLICATION NOTE 27:
* "UNDERSTANDING AND USING CYCLIC REDUNDANCY CHECKS WITH MAXIM 1-WIRE AND IBUTTON PRODUCTS"
* path_to_url
*
* @param seed Init value for the CRC, it is usually set to 0x0000.
* @param[in] src Input bytes for the computation.
* @param len Length of the input in bytes.
*
* @retval crc The computed CRC16 value.
*/
static inline uint16_t w1_crc16(const uint16_t seed, const uint8_t *src,
const size_t len)
{
return crc16_reflect(W1_CRC16_POLYNOMIAL, seed, src, len);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/w1.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_W1_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/w1.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 5,545 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_I3C_H_
#define ZEPHYR_INCLUDE_DRIVERS_I3C_H_
/**
* @brief I3C Interface
* @defgroup i3c_interface I3C Interface
* @since 3.2
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <stdint.h>
#include <stddef.h>
#include <zephyr/device.h>
#include <zephyr/drivers/i3c/addresses.h>
#include <zephyr/drivers/i3c/ccc.h>
#include <zephyr/drivers/i3c/devicetree.h>
#include <zephyr/drivers/i3c/ibi.h>
#include <zephyr/drivers/i2c.h>
#include <zephyr/sys/slist.h>
#include <zephyr/sys/util.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name Bus Characteristic Register (BCR)
* @anchor I3C_BCR
*
* - BCR[7:6]: Device Role
* - 0: I3C Target
* - 1: I3C Controller capable
* - 2: Reserved
* - 3: Reserved
* .
* - BCR[5]: Advanced Capabilities
* - 0: Does not support optional advanced capabilities.
* - 1: Supports optional advanced capabilities which
* can be viewed via GETCAPS CCC.
* .
* - BCR[4]: Virtual Target Support
* - 0: Is not a virtual target.
* - 1: Is a virtual target.
* .
* - BCR[3]: Offline Capable
* - 0: Will always response to I3C commands.
* - 1: Will not always response to I3C commands.
* .
* - BCR[2]: IBI Payload
* - 0: No data bytes following the accepted IBI.
* - 1: One data byte (MDB, Mandatory Data Byte) follows
* the accepted IBI. Additional data bytes may also
* follows.
* .
* - BCR[1]: IBI Request Capable
* - 0: Not capable
* - 1: Capable
* .
* - BCR[0]: Max Data Speed Limitation
* - 0: No Limitation
* - 1: Limitation obtained via GETMXDS CCC.
* .
*
* @{
*/
/**
* @brief Max Data Speed Limitation bit.
*
* 0 - No Limitation.
* 1 - Limitation obtained via GETMXDS CCC.
*/
#define I3C_BCR_MAX_DATA_SPEED_LIMIT BIT(0)
/** @brief IBI Request Capable bit. */
#define I3C_BCR_IBI_REQUEST_CAPABLE BIT(1)
/**
* @brief IBI Payload bit.
*
* 0 - No data bytes following the accepted IBI.
* 1 - One data byte (MDB, Mandatory Data Byte) follows the accepted IBI.
* Additional data bytes may also follows.
*/
#define I3C_BCR_IBI_PAYLOAD_HAS_DATA_BYTE BIT(2)
/**
* @brief Offline Capable bit.
*
* 0 - Will always respond to I3C commands.
* 1 - Will not always respond to I3C commands.
*/
#define I3C_BCR_OFFLINE_CAPABLE BIT(3)
/**
* @brief Virtual Target Support bit.
*
* 0 - Is not a virtual target.
* 1 - Is a virtual target.
*/
#define I3C_BCR_VIRTUAL_TARGET BIT(4)
/**
* @brief Advanced Capabilities bit.
*
* 0 - Does not support optional advanced capabilities.
* 1 - Supports optional advanced capabilities which can be viewed via
* GETCAPS CCC.
*/
#define I3C_BCR_ADV_CAPABILITIES BIT(5)
/** Device Role - I3C Target. */
#define I3C_BCR_DEVICE_ROLE_I3C_TARGET 0U
/** Device Role - I3C Controller Capable. */
#define I3C_BCR_DEVICE_ROLE_I3C_CONTROLLER_CAPABLE 1U
/** Device Role bit shift mask. */
#define I3C_BCR_DEVICE_ROLE_MASK GENMASK(7U, 6U)
/**
* @brief Device Role
*
* Obtain Device Role value from the BCR value obtained via GETBCR.
*
* @param bcr BCR value
*/
#define I3C_BCR_DEVICE_ROLE(bcr) \
FIELD_GET(I3C_BCR_DEVICE_ROLE_MASK, (bcr))
/** @} */
/**
* @name Legacy Virtual Register (LVR)
* @anchor I3C_LVR
*
* Legacy Virtual Register (LVR)
* - LVR[7:5]: I2C device index:
* - 0: I2C device has a 50 ns spike filter where
* it is not affected by high frequency on SCL.
* - 1: I2C device does not have a 50 ns spike filter
* but can work with high frequency on SCL.
* - 2: I2C device does not have a 50 ns spike filter
* and cannot work with high frequency on SCL.
* - LVR[4]: I2C mode indicator:
* - 0: FM+ mode
* - 1: FM mode
* - LVR[3:0]: Reserved.
*
* @{
*/
/** I2C FM+ Mode. */
#define I3C_LVR_I2C_FM_PLUS_MODE 0
/** I2C FM Mode. */
#define I3C_LVR_I2C_FM_MODE 1
/** I2C Mode Indicator bitmask. */
#define I3C_LVR_I2C_MODE_MASK BIT(4)
/**
* @brief I2C Mode
*
* Obtain I2C Mode value from the LVR value.
*
* @param lvr LVR value
*/
#define I3C_LVR_I2C_MODE(lvr) \
FIELD_GET(I3C_LVR_I2C_MODE_MASK, (lvr))
/**
* @brief I2C Device Index 0.
*
* I2C device has a 50 ns spike filter where it is not affected by high
* frequency on SCL.
*/
#define I3C_LVR_I2C_DEV_IDX_0 0
/**
* @brief I2C Device Index 1.
*
* I2C device does not have a 50 ns spike filter but can work with high
* frequency on SCL.
*/
#define I3C_LVR_I2C_DEV_IDX_1 1
/**
* @brief I2C Device Index 2.
*
* I2C device does not have a 50 ns spike filter and cannot work with high
* frequency on SCL.
*/
#define I3C_LVR_I2C_DEV_IDX_2 2
/** I2C Device Index bitmask. */
#define I3C_LVR_I2C_DEV_IDX_MASK GENMASK(7U, 5U)
/**
* @brief I2C Device Index
*
* Obtain I2C Device Index value from the LVR value.
*
* @param lvr LVR value
*/
#define I3C_LVR_I2C_DEV_IDX(lvr) \
FIELD_GET(I3C_LVR_I2C_DEV_IDX_MASK, (lvr))
/** @} */
/**
* @brief I3C bus mode
*/
enum i3c_bus_mode {
/** Only I3C devices are on the bus. */
I3C_BUS_MODE_PURE,
/**
* Both I3C and legacy I2C devices are on the bus.
* The I2C devices have 50ns spike filter on SCL.
*/
I3C_BUS_MODE_MIXED_FAST,
/**
* Both I3C and legacy I2C devices are on the bus.
* The I2C devices do not have 50ns spike filter on SCL
* and can tolerate maximum SDR SCL clock frequency.
*/
I3C_BUS_MODE_MIXED_LIMITED,
/**
* Both I3C and legacy I2C devices are on the bus.
* The I2C devices do not have 50ns spike filter on SCL
* but cannot tolerate maximum SDR SCL clock frequency.
*/
I3C_BUS_MODE_MIXED_SLOW,
I3C_BUS_MODE_MAX = I3C_BUS_MODE_MIXED_SLOW,
I3C_BUS_MODE_INVALID,
};
/**
* @brief I2C bus speed under I3C bus.
*
* Only FM and FM+ modes are supported for I2C devices under I3C bus.
*/
enum i3c_i2c_speed_type {
/** I2C FM mode */
I3C_I2C_SPEED_FM,
/** I2C FM+ mode */
I3C_I2C_SPEED_FMPLUS,
I3C_I2C_SPEED_MAX = I3C_I2C_SPEED_FMPLUS,
I3C_I2C_SPEED_INVALID,
};
/**
* @brief I3C data rate
*
* I3C data transfer rate defined by the I3C specification.
*/
enum i3c_data_rate {
/** Single Data Rate messaging */
I3C_DATA_RATE_SDR,
/** High Data Rate - Double Data Rate messaging */
I3C_DATA_RATE_HDR_DDR,
/** High Data Rate - Ternary Symbol Legacy-inclusive-Bus */
I3C_DATA_RATE_HDR_TSL,
/** High Data Rate - Ternary Symbol for Pure Bus */
I3C_DATA_RATE_HDR_TSP,
/** High Data Rate - Bulk Transport */
I3C_DATA_RATE_HDR_BT,
I3C_DATA_RATE_MAX = I3C_DATA_RATE_HDR_BT,
I3C_DATA_RATE_INVALID,
};
/**
* @brief I3C SDR Controller Error Codes
*
* These are error codes defined by the I3C specification.
*
* #I3C_ERROR_CE_UNKNOWN and #I3C_ERROR_CE_NONE are not
* official error codes according to the specification.
* These are there simply to aid in error handling during
* interactions with the I3C drivers and subsystem.
*/
enum i3c_sdr_controller_error_codes {
/** Transaction after sending CCC */
I3C_ERROR_CE0,
/** Monitoring Error */
I3C_ERROR_CE1,
/** No response to broadcast address (0x7E) */
I3C_ERROR_CE2,
/** Failed Controller Handoff */
I3C_ERROR_CE3,
/** Unknown error (not official error code) */
I3C_ERROR_CE_UNKNOWN,
/** No error (not official error code) */
I3C_ERROR_CE_NONE,
I3C_ERROR_CE_MAX = I3C_ERROR_CE_UNKNOWN,
I3C_ERROR_CE_INVALID,
};
/**
* @brief I3C SDR Target Error Codes
*
* These are error codes defined by the I3C specification.
*
* #I3C_ERROR_TE_UNKNOWN and #I3C_ERROR_TE_NONE are not
* official error codes according to the specification.
* These are there simply to aid in error handling during
* interactions with the I3C drivers and subsystem.
*/
enum i3c_sdr_target_error_codes {
/**
* Invalid Broadcast Address or
* Dynamic Address after DA assignment
*/
I3C_ERROR_TE0,
/** CCC Code */
I3C_ERROR_TE1,
/** Write Data */
I3C_ERROR_TE2,
/** Assigned Address during Dynamic Address Arbitration */
I3C_ERROR_TE3,
/** 0x7E/R missing after RESTART during Dynamic Address Arbitration */
I3C_ERROR_TE4,
/** Transaction after detecting CCC */
I3C_ERROR_TE5,
/** Monitoring Error */
I3C_ERROR_TE6,
/** Dead Bus Recovery */
I3C_ERROR_DBR,
/** Unknown error (not official error code) */
I3C_ERROR_TE_UNKNOWN,
/** No error (not official error code) */
I3C_ERROR_TE_NONE,
I3C_ERROR_TE_MAX = I3C_ERROR_TE_UNKNOWN,
I3C_ERROR_TE_INVALID,
};
/**
* @brief I3C Transfer API
* @defgroup i3c_transfer_api I3C Transfer API
* @{
*/
/*
* I3C_MSG_* are I3C Message flags.
*/
/** Write message to I3C bus. */
#define I3C_MSG_WRITE (0U << 0U)
/** Read message from I3C bus. */
#define I3C_MSG_READ BIT(0)
/** @cond INTERNAL_HIDDEN */
#define I3C_MSG_RW_MASK BIT(0)
/** @endcond */
/** Send STOP after this message. */
#define I3C_MSG_STOP BIT(1)
/**
* RESTART I3C transaction for this message.
*
* @note Not all I3C drivers have or require explicit support for this
* feature. Some drivers require this be present on a read message
* that follows a write, or vice-versa. Some drivers will merge
* adjacent fragments into a single transaction using this flag; some
* will not.
*/
#define I3C_MSG_RESTART BIT(2)
/** Transfer use HDR mode */
#define I3C_MSG_HDR BIT(3)
/** Skip I3C broadcast header. Private Transfers only. */
#define I3C_MSG_NBCH BIT(4)
/** I3C HDR Mode 0 */
#define I3C_MSG_HDR_MODE0 BIT(0)
/** I3C HDR Mode 1 */
#define I3C_MSG_HDR_MODE1 BIT(1)
/** I3C HDR Mode 2 */
#define I3C_MSG_HDR_MODE2 BIT(2)
/** I3C HDR Mode 3 */
#define I3C_MSG_HDR_MODE3 BIT(3)
/** I3C HDR Mode 4 */
#define I3C_MSG_HDR_MODE4 BIT(4)
/** I3C HDR Mode 5 */
#define I3C_MSG_HDR_MODE5 BIT(5)
/** I3C HDR Mode 6 */
#define I3C_MSG_HDR_MODE6 BIT(6)
/** I3C HDR Mode 7 */
#define I3C_MSG_HDR_MODE7 BIT(7)
/** I3C HDR-DDR (Double Data Rate) */
#define I3C_MSG_HDR_DDR I3C_MSG_HDR_MODE0
/** I3C HDR-TSP (Ternary Symbol Pure-bus) */
#define I3C_MSG_HDR_TSP I3C_MSG_HDR_MODE1
/** I3C HDR-TSL (Ternary Symbol Legacy-inclusive-bus) */
#define I3C_MSG_HDR_TSL I3C_MSG_HDR_MODE2
/** I3C HDR-BT (Bulk Transport) */
#define I3C_MSG_HDR_BT I3C_MSG_HDR_MODE3
/** @} */
/**
* @addtogroup i3c_transfer_api
* @{
*/
/**
* @brief One I3C Message.
*
* This defines one I3C message to transact on the I3C bus.
*
* @note Some of the configurations supported by this API may not be
* supported by specific SoC I3C hardware implementations, in
* particular features related to bus transactions intended to read or
* write data from different buffers within a single transaction.
* Invocations of i3c_transfer() may not indicate an error when an
* unsupported configuration is encountered. In some cases drivers
* will generate separate transactions for each message fragment, with
* or without presence of #I3C_MSG_RESTART in #flags.
*/
struct i3c_msg {
/** Data buffer in bytes */
uint8_t *buf;
/** Length of buffer in bytes */
uint32_t len;
/**
* Total number of bytes transferred
*
* A Target can issue an EoD or the Controller can abort a transfer
* before the length of the buffer. It is expected for the driver to
* write to this after the transfer.
*/
uint32_t num_xfer;
/** Flags for this message */
uint8_t flags;
/**
* HDR mode (@c I3C_MSG_HDR_MODE*) for transfer
* if any @c I3C_MSG_HDR_* is set in #flags.
*
* Use SDR mode if none is set.
*/
uint8_t hdr_mode;
/** HDR command code field (7-bit) for HDR-DDR, HDR-TSP and HDR-TSL */
uint8_t hdr_cmd_code;
};
/** @} */
/**
* @brief Type of configuration being passed to configure function.
*/
enum i3c_config_type {
I3C_CONFIG_CONTROLLER,
I3C_CONFIG_TARGET,
I3C_CONFIG_CUSTOM,
};
/**
* @brief Configuration parameters for I3C hardware to act as controller.
*/
struct i3c_config_controller {
/**
* True if the controller is to be the secondary controller
* of the bus. False to be the primary controller.
*/
bool is_secondary;
struct {
/** SCL frequency (in Hz) for I3C transfers. */
uint32_t i3c;
/** SCL frequency (in Hz) for I2C transfers. */
uint32_t i2c;
} scl;
/**
* Bit mask of supported HDR modes (0 - 7).
*
* This can be used to enable or disable HDR mode
* supported by the hardware at runtime.
*/
uint8_t supported_hdr;
};
/**
* @brief Custom I3C configuration parameters.
*
* This can be used to configure the I3C hardware on parameters
* not covered by i3c_config_controller or i3c_config_target.
* Mostly used to configure vendor specific parameters of the I3C
* hardware.
*/
struct i3c_config_custom {
/** ID of the configuration parameter. */
uint32_t id;
union {
/** Value of configuration parameter. */
uintptr_t val;
/**
* Pointer to configuration parameter.
*
* Mainly used to pointer to a struct that
* the device driver understands.
*/
void *ptr;
};
};
/**
* @cond INTERNAL_HIDDEN
*
* These are for internal use only, so skip these in
* public documentation.
*/
struct i3c_device_desc;
struct i3c_device_id;
struct i3c_i2c_device_desc;
struct i3c_target_config;
__subsystem struct i3c_driver_api {
/**
* For backward compatibility to I2C API.
*
* @see i2c_driver_api for more information.
*
* @internal
* @warning DO NOT MOVE! Must be at the beginning.
* @endinternal
*/
struct i2c_driver_api i2c_api;
/**
* Configure the I3C hardware.
*
* @see i3c_configure()
*
* @param dev Pointer to controller device driver instance.
* @param type Type of configuration parameters being passed
* in @p config.
* @param config Pointer to the configuration parameters.
*
* @return See i3c_configure()
*/
int (*configure)(const struct device *dev,
enum i3c_config_type type, void *config);
/**
* Get configuration of the I3C hardware.
*
* @see i3c_config_get()
*
* @param[in] dev Pointer to controller device driver instance.
* @param[in] type Type of configuration parameters being passed
* in @p config.
* @param[in, out] config Pointer to the configuration parameters.
*
* @return See i3c_config_get()
*/
int (*config_get)(const struct device *dev,
enum i3c_config_type type, void *config);
/**
* Perform bus recovery
*
* Controller only API.
*
* @see i3c_recover_bus()
*
* @param dev Pointer to controller device driver instance.
*
* @return See i3c_recover_bus()
*/
int (*recover_bus)(const struct device *dev);
/**
* I3C Device Attach
*
* Optional API.
*
* @see i3c_attach_i3c_device()
*
* @param dev Pointer to controller device driver instance.
* @param target Pointer to target device descriptor.
* @param addr Address to attach with
*
* @return See i3c_attach_i3c_device()
*/
int (*attach_i3c_device)(const struct device *dev,
struct i3c_device_desc *target,
uint8_t addr);
/**
* I3C Address Update
*
* Optional API.
*
* @see i3c_reattach_i3c_device()
*
* @param dev Pointer to controller device driver instance.
* @param target Pointer to target device descriptor.
* @param old_dyn_addr Old dynamic address
*
* @return See i3c_reattach_i3c_device()
*/
int (*reattach_i3c_device)(const struct device *dev,
struct i3c_device_desc *target,
uint8_t old_dyn_addr);
/**
* I3C Device Detach
*
* Optional API.
*
* @see i3c_detach_i3c_device()
*
* @param dev Pointer to controller device driver instance.
* @param target Pointer to target device descriptor.
*
* @return See i3c_detach_i3c_device()
*/
int (*detach_i3c_device)(const struct device *dev,
struct i3c_device_desc *target);
/**
* I2C Device Attach
*
* Optional API.
*
* @see i3c_attach_i2c_device()
*
* @param dev Pointer to controller device driver instance.
* @param target Pointer to target device descriptor.
*
* @return See i3c_attach_i2c_device()
*/
int (*attach_i2c_device)(const struct device *dev,
struct i3c_i2c_device_desc *target);
/**
* I2C Device Detach
*
* Optional API.
*
* @see i3c_detach_i2c_device()
*
* @param dev Pointer to controller device driver instance.
* @param target Pointer to target device descriptor.
*
* @return See i3c_detach_i2c_device()
*/
int (*detach_i2c_device)(const struct device *dev,
struct i3c_i2c_device_desc *target);
/**
* Perform Dynamic Address Assignment via ENTDAA.
*
* Controller only API.
*
* @see i3c_do_daa()
*
* @param dev Pointer to controller device driver instance.
*
* @return See i3c_do_daa()
*/
int (*do_daa)(const struct device *dev);
/**
* Send Common Command Code (CCC).
*
* Controller only API.
*
* @see i3c_do_ccc()
*
* @param dev Pointer to controller device driver instance.
* @param payload Pointer to the CCC payload.
*
* @return See i3c_do_ccc()
*/
int (*do_ccc)(const struct device *dev,
struct i3c_ccc_payload *payload);
/**
* Transfer messages in I3C mode.
*
* @see i3c_transfer()
*
* @param dev Pointer to controller device driver instance.
* @param target Pointer to target device descriptor.
* @param msg Pointer to I3C messages.
* @param num_msgs Number of messages to transfer.
*
* @return See i3c_transfer()
*/
int (*i3c_xfers)(const struct device *dev,
struct i3c_device_desc *target,
struct i3c_msg *msgs,
uint8_t num_msgs);
/**
* Find a registered I3C target device.
*
* Controller only API.
*
* This returns the I3C device descriptor of the I3C device
* matching the incoming @p id.
*
* @param dev Pointer to controller device driver instance.
* @param id Pointer to I3C device ID.
*
* @return See i3c_device_find().
*/
struct i3c_device_desc *(*i3c_device_find)(const struct device *dev,
const struct i3c_device_id *id);
/**
* Raise In-Band Interrupt (IBI).
*
* Target device only API.
*
* @see i3c_ibi_request()
*
* @param dev Pointer to controller device driver instance.
* @param request Pointer to IBI request struct.
*
* @return See i3c_ibi_request()
*/
int (*ibi_raise)(const struct device *dev,
struct i3c_ibi *request);
/**
* Enable receiving IBI from a target.
*
* Controller only API.
*
* @see i3c_ibi_enable()
*
* @param dev Pointer to controller device driver instance.
* @param target Pointer to target device descriptor.
*
* @return See i3c_ibi_enable()
*/
int (*ibi_enable)(const struct device *dev,
struct i3c_device_desc *target);
/**
* Disable receiving IBI from a target.
*
* Controller only API.
*
* @see i3c_ibi_disable()
*
* @param dev Pointer to controller device driver instance.
* @param target Pointer to target device descriptor.
*
* @return See i3c_ibi_disable()
*/
int (*ibi_disable)(const struct device *dev,
struct i3c_device_desc *target);
/**
* Register config as target device of a controller.
*
* This tells the controller to act as a target device
* on the I3C bus.
*
* Target device only API.
*
* @see i3c_target_register()
*
* @param dev Pointer to the controller device driver instance.
* @param cfg I3C target device configuration
*
* @return See i3c_target_register()
*/
int (*target_register)(const struct device *dev,
struct i3c_target_config *cfg);
/**
* Unregister config as target device of a controller.
*
* This tells the controller to stop acting as a target device
* on the I3C bus.
*
* Target device only API.
*
* @see i3c_target_unregister()
*
* @param dev Pointer to the controller device driver instance.
* @param cfg I3C target device configuration
*
* @return See i3c_target_unregister()
*/
int (*target_unregister)(const struct device *dev,
struct i3c_target_config *cfg);
/**
* Write to the TX FIFO
*
* This writes to the target tx fifo
*
* Target device only API.
*
* @see i3c_target_tx_write()
*
* @param dev Pointer to the controller device driver instance.
* @param buf Pointer to the buffer
* @param len Length of the buffer
* @param hdr_mode HDR mode
*
* @return See i3c_target_tx_write()
*/
int (*target_tx_write)(const struct device *dev,
uint8_t *buf, uint16_t len, uint8_t hdr_mode);
};
/**
* @endcond
*/
/**
* @brief Structure used for matching I3C devices.
*/
struct i3c_device_id {
/** Device Provisioned ID */
const uint64_t pid:48;
};
/**
* @brief Structure initializer for i3c_device_id from PID
*
* This helper macro expands to a static initializer for a i3c_device_id
* by populating the PID (Provisioned ID) field.
*
* @param pid Provisioned ID.
*/
#define I3C_DEVICE_ID(pid) \
{ \
.pid = pid \
}
/**
* @brief Structure describing a I3C target device.
*
* Instances of this are passed to the I3C controller device APIs,
* for example:
* - i3c_device_register() to tell the controller of a target device.
* - i3c_transfers() to initiate data transfers between controller and
* target device.
*
* Fields #bus, #pid and #static_addr must be initialized by the module that
* implements the target device behavior prior to passing the object reference
* to I3C controller device APIs. #static_addr can be zero if target device does
* not have static address.
*
* Internal field @c node should not be initialized or modified manually.
*/
struct i3c_device_desc {
sys_snode_t node;
/** I3C bus to which this target device is attached */
const struct device * const bus;
/** Device driver instance of the I3C device */
const struct device * const dev;
/** Device Provisioned ID */
const uint64_t pid:48;
/**
* Static address for this target device.
*
* 0 if static address is not being used, and only dynamic
* address is used. This means that the target device must
* go through ENTDAA (Dynamic Address Assignment) to get
* a dynamic address before it can communicate with
* the controller. This means SETAASA and SETDASA CCC
* cannot be used to set dynamic address on the target
* device (as both are to tell target device to use static
* address as dynamic address).
*/
const uint8_t static_addr;
/**
* Initial dynamic address.
*
* This is specified in the device tree property "assigned-address"
* to indicate the desired dynamic address during address
* assignment (SETDASA and ENTDAA).
*
* 0 if there is no preference.
*/
const uint8_t init_dynamic_addr;
/**
* Dynamic Address for this target device used for communication.
*
* This is to be set by the controller driver in one of
* the following situations:
* - During Dynamic Address Assignment (during ENTDAA)
* - Reset Dynamic Address Assignment (RSTDAA)
* - Set All Addresses to Static Addresses (SETAASA)
* - Set New Dynamic Address (SETNEWDA)
* - Set Dynamic Address from Static Address (SETDASA)
*
* 0 if address has not been assigned.
*/
uint8_t dynamic_addr;
#if defined(CONFIG_I3C_USE_GROUP_ADDR) || defined(__DOXYGEN__)
/**
* Group address for this target device. Set during:
* - Reset Group Address(es) (RSTGRPA)
* - Set Group Address (SETGRPA)
*
* 0 if group address has not been assigned.
* Only available if @kconfig{CONFIG_I3C_USE_GROUP_ADDR} is set.
*/
uint8_t group_addr;
#endif /* CONFIG_I3C_USE_GROUP_ADDR */
/**
* Bus Characteristic Register (BCR)
* @see @ref I3C_BCR
*/
uint8_t bcr;
/**
* Device Characteristic Register (DCR)
*
* Describes the type of device. Refer to official documentation
* on what this number means.
*/
uint8_t dcr;
struct {
/** Maximum Read Speed */
uint8_t maxrd;
/** Maximum Write Speed */
uint8_t maxwr;
/** Maximum Read turnaround time in microseconds. */
uint32_t max_read_turnaround;
} data_speed;
struct {
/** Maximum Read Length */
uint16_t mrl;
/** Maximum Write Length */
uint16_t mwl;
/** Maximum IBI Payload Size. Valid only if BCR[2] is 1. */
uint8_t max_ibi;
} data_length;
/** Describes advanced (Target) capabilities and features */
struct {
union {
/**
* I3C v1.0 HDR Capabilities (@c I3C_CCC_GETCAPS1_*)
* - Bit[0]: HDR-DDR
* - Bit[1]: HDR-TSP
* - Bit[2]: HDR-TSL
* - Bit[7:3]: Reserved
*/
uint8_t gethdrcap;
/**
* I3C v1.1+ GETCAPS1 (@c I3C_CCC_GETCAPS1_*)
* - Bit[0]: HDR-DDR
* - Bit[1]: HDR-TSP
* - Bit[2]: HDR-TSL
* - Bit[3]: HDR-BT
* - Bit[7:4]: Reserved
*/
uint8_t getcap1;
};
/**
* GETCAPS2 (@c I3C_CCC_GETCAPS2_*)
* - Bit[3:0]: I3C 1.x Specification Version
* - Bit[5:4]: Group Address Capabilities
* - Bit[6]: HDR-DDR Write Abort
* - Bit[7]: HDR-DDR Abort CRC
*/
uint8_t getcap2;
/**
* GETCAPS3 (@c I3C_CCC_GETCAPS3_*)
* - Bit[0]: Multi-Lane (ML) Data Transfer Support
* - Bit[1]: Device to Device Transfer (D2DXFER) Support
* - Bit[2]: Device to Device Transfer (D2DXFER) IBI Capable
* - Bit[3]: Defining Byte Support in GETCAPS
* - Bit[4]: Defining Byte Support in GETSTATUS
* - Bit[5]: HDR-BT CRC-32 Support
* - Bit[6]: IBI MDB Support for Pending Read Notification
* - Bit[7]: Reserved
*/
uint8_t getcap3;
/**
* GETCAPS4
* - Bit[7:0]: Reserved
*/
uint8_t getcap4;
} getcaps;
/** @cond INTERNAL_HIDDEN */
/**
* Private data by the controller to aid in transactions. Do not modify.
*/
void *controller_priv;
/** @endcond */
#if defined(CONFIG_I3C_USE_IBI) || defined(__DOXYGEN__)
/**
* In-Band Interrupt (IBI) callback.
* Only available if @kconfig{CONFIG_I3C_USE_IBI} is set.
*/
i3c_target_ibi_cb_t ibi_cb;
#endif /* CONFIG_I3C_USE_IBI */
};
/**
* @brief Structure describing a I2C device on I3C bus.
*
* Instances of this are passed to the I3C controller device APIs,
* for example:
* () i3c_i2c_device_register() to tell the controller of an I2C device.
* () i3c_i2c_transfers() to initiate data transfers between controller
* and I2C device.
*
* Fields other than @c node must be initialized by the module that
* implements the device behavior prior to passing the object
* reference to I3C controller device APIs.
*/
struct i3c_i2c_device_desc {
sys_snode_t node;
/** I3C bus to which this I2C device is attached */
const struct device *bus;
/** Static address for this I2C device. */
const uint16_t addr;
/**
* Legacy Virtual Register (LVR)
* @see @ref I3C_LVR
*/
const uint8_t lvr;
/** @cond INTERNAL_HIDDEN */
/**
* Private data by the controller to aid in transactions. Do not modify.
*/
void *controller_priv;
/** @endcond */
};
/**
* @brief Structure for describing attached devices for a controller.
*
* This contains slists of attached I3C and I2C devices.
*
* This is a helper struct that can be used by controller device
* driver to aid in device management.
*/
struct i3c_dev_attached_list {
/**
* Address slots:
* - Aid in dynamic address assignment.
* - Quick way to find out if a target address is
* a I3C or I2C device.
*/
struct i3c_addr_slots addr_slots;
struct {
/**
* Linked list of attached I3C devices.
*/
sys_slist_t i3c;
/**
* Linked list of attached I2C devices.
*/
sys_slist_t i2c;
} devices;
};
/**
* @brief Structure for describing known devices for a controller.
*
* This contains arrays of known I3C and I2C devices.
*
* This is a helper struct that can be used by controller device
* driver to aid in device management.
*/
struct i3c_dev_list {
/**
* Pointer to array of known I3C devices.
*/
struct i3c_device_desc * const i3c;
/**
* Pointer to array of known I2C devices.
*/
struct i3c_i2c_device_desc * const i2c;
/**
* Number of I3C devices in array.
*/
const uint8_t num_i3c;
/**
* Number of I2C devices in array.
*/
const uint8_t num_i2c;
};
/**
* This structure is common to all I3C drivers and is expected to be
* the first element in the object pointed to by the config field
* in the device structure.
*/
struct i3c_driver_config {
/** I3C/I2C device list struct. */
struct i3c_dev_list dev_list;
};
/**
* This structure is common to all I3C drivers and is expected to be the first
* element in the driver's struct driver_data declaration.
*/
struct i3c_driver_data {
/** Controller Configuration */
struct i3c_config_controller ctrl_config;
/** Attached I3C/I2C devices and addresses */
struct i3c_dev_attached_list attached_dev;
};
/**
* @brief Find a I3C target device descriptor by ID.
*
* This finds the I3C target device descriptor in the device list
* matching the provided ID struct (@p id).
*
* @param dev_list Pointer to the device list struct.
* @param id Pointer to I3C device ID struct.
*
* @return Pointer to the I3C target device descriptor, or
* `NULL` if none is found.
*/
struct i3c_device_desc *i3c_dev_list_find(const struct i3c_dev_list *dev_list,
const struct i3c_device_id *id);
/**
* @brief Find a I3C target device descriptor by dynamic address.
*
* This finds the I3C target device descriptor in the attached
* device list matching the dynamic address (@p addr)
*
* @param dev_list Pointer to the device list struct.
* @param addr Dynamic address to be matched.
*
* @return Pointer to the I3C target device descriptor, or
* `NULL` if none is found.
*/
struct i3c_device_desc *i3c_dev_list_i3c_addr_find(struct i3c_dev_attached_list *dev_list,
uint8_t addr);
/**
* @brief Find a I2C target device descriptor by address.
*
* This finds the I2C target device descriptor in the attached
* device list matching the address (@p addr)
*
* @param dev_list Pointer to the device list struct.
* @param addr Address to be matched.
*
* @return Pointer to the I2C target device descriptor, or
* `NULL` if none is found.
*/
struct i3c_i2c_device_desc *i3c_dev_list_i2c_addr_find(struct i3c_dev_attached_list *dev_list,
uint16_t addr);
/**
* @brief Helper function to find the default address an i3c device is attached with
*
* This is a helper function to find the default address the
* device will be loaded with. This could be either it's static
* address, a requested dynamic address, or just a dynamic address
* that is available
* @param[in] target The pointer of the device descriptor
* @param[out] addr Address to be assigned to target device.
*
* @retval 0 if successful.
* @retval -EINVAL if the expected default address is already in use
*/
int i3c_determine_default_addr(struct i3c_device_desc *target, uint8_t *addr);
/**
* @brief Helper function to find a usable address during ENTDAA.
*
* This is a helper function to find a usable address during
* Dynamic Address Assignment. Given the PID (@p pid), it will
* search through the device list for the matching device
* descriptor. If the device descriptor indicates that there is
* a preferred address (i.e. assigned-address in device tree,
* i3c_device_desc::init_dynamic_addr), this preferred
* address will be returned if this address is still available.
* If it is not available, another free address will be returned.
*
* If @p must_match is true, the PID (@p pid) must match
* one of the device in the device list.
*
* If @p must_match is false, this will return an arbitrary
* address. This is useful when not all devices are described in
* device tree. Or else, the DAA process cannot proceed since
* there is no address to be assigned.
*
* If @p assigned_okay is true, it will return the same address
* already assigned to the device
* (i3c_device_desc::dynamic_addr). If no address has been
* assigned, it behaves as if @p assigned_okay is false.
* This is useful for assigning the same address to the same
* device (for example, hot-join after device coming back from
* suspend).
*
* If @p assigned_okay is false, the device cannot have an address
* assigned already (that i3c_device_desc::dynamic_addr is not
* zero). This is mainly used during the initial DAA.
*
* @param[in] addr_slots Pointer to address slots struct.
* @param[in] dev_list Pointer to the device list struct.
* @param[in] pid Provisioned ID of device to be assigned address.
* @param[in] must_match True if PID must match devices in
* the device list. False otherwise.
* @param[in] assigned_okay True if it is okay to return the
* address already assigned to the target
* matching the PID (@p pid).
* @param[out] target Store the pointer of the device descriptor
* if it matches the incoming PID (@p pid).
* @param[out] addr Address to be assigned to target device.
*
* @retval 0 if successful.
* @retval -ENODEV if no device matches the PID (@p pid) in
* the device list and @p must_match is true.
* @retval -EINVAL if the device matching PID (@p pid) already
* has an address assigned or invalid function
* arguments.
*/
int i3c_dev_list_daa_addr_helper(struct i3c_addr_slots *addr_slots,
const struct i3c_dev_list *dev_list,
uint64_t pid, bool must_match,
bool assigned_okay,
struct i3c_device_desc **target,
uint8_t *addr);
/**
* @brief Configure the I3C hardware.
*
* @param dev Pointer to controller device driver instance.
* @param type Type of configuration parameters being passed
* in @p config.
* @param config Pointer to the configuration parameters.
*
* @retval 0 If successful.
* @retval -EINVAL If invalid configure parameters.
* @retval -EIO General Input/Output errors.
* @retval -ENOSYS If not implemented.
*/
static inline int i3c_configure(const struct device *dev,
enum i3c_config_type type, void *config)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)dev->api;
if (api->configure == NULL) {
return -ENOSYS;
}
return api->configure(dev, type, config);
}
/**
* @brief Get configuration of the I3C hardware.
*
* This provides a way to get the current configuration of the I3C hardware.
*
* This can return cached config or probed hardware parameters, but it has to
* be up to date with current configuration.
*
* @param[in] dev Pointer to controller device driver instance.
* @param[in] type Type of configuration parameters being passed
* in @p config.
* @param[in,out] config Pointer to the configuration parameters.
*
* Note that if @p type is #I3C_CONFIG_CUSTOM, @p config must contain
* the ID of the parameter to be retrieved.
*
* @retval 0 If successful.
* @retval -EIO General Input/Output errors.
* @retval -ENOSYS If not implemented.
*/
static inline int i3c_config_get(const struct device *dev,
enum i3c_config_type type, void *config)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)dev->api;
if (api->config_get == NULL) {
return -ENOSYS;
}
return api->config_get(dev, type, config);
}
/**
* @brief Attempt bus recovery on the I3C bus.
*
* This routine asks the controller to attempt bus recovery.
*
* @retval 0 If successful.
* @retval -EBUSY If bus recovery fails.
* @retval -EIO General input / output error.
* @retval -ENOSYS Bus recovery is not supported by the controller driver.
*/
static inline int i3c_recover_bus(const struct device *dev)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)dev->api;
if (api->recover_bus == NULL) {
return -ENOSYS;
}
return api->recover_bus(dev);
}
/**
* @brief Attach an I3C device
*
* Called to attach a I3C device to the addresses. This is
* typically called before a SETDASA or ENTDAA to reserve
* the addresses. This will also call the optional api to
* update any registers within the driver if implemented.
*
* @warning
* Use cases involving multiple writers to the i3c/i2c devices must prevent
* concurrent write operations, either by preventing all writers from
* being preempted or by using a mutex to govern writes to the i3c/i2c devices.
*
* @param target Pointer to the target device descriptor
*
* @retval 0 If successful.
* @retval -EINVAL If address is not available or if the device
* has already been attached before
*/
int i3c_attach_i3c_device(struct i3c_device_desc *target);
/**
* @brief Reattach I3C device
*
* called after every time an I3C device has its address
* changed. It can be because the device has been powered
* down and has lost its address, or it can happen when a
* device had a static address and has been assigned a
* dynamic address with SETDASA or a dynamic address has
* been updated with SETNEWDA. This will also call the
* optional api to update any registers within the driver
* if implemented.
*
* @warning
* Use cases involving multiple writers to the i3c/i2c devices must prevent
* concurrent write operations, either by preventing all writers from
* being preempted or by using a mutex to govern writes to the i3c/i2c devices.
*
* @param target Pointer to the target device descriptor
* @param old_dyn_addr The old dynamic address of target device, 0 if
* there was no old dynamic address
*
* @retval 0 If successful.
* @retval -EINVAL If address is not available
*/
int i3c_reattach_i3c_device(struct i3c_device_desc *target, uint8_t old_dyn_addr);
/**
* @brief Detach I3C Device
*
* called to remove an I3C device and to free up the address
* that it used. If it's dynamic address was not set, then it
* assumed that SETDASA failed and will free it's static addr.
* This will also call the optional api to update any registers
* within the driver if implemented.
*
* @warning
* Use cases involving multiple writers to the i3c/i2c devices must prevent
* concurrent write operations, either by preventing all writers from
* being preempted or by using a mutex to govern writes to the i3c/i2c devices.
*
* @param target Pointer to the target device descriptor
*
* @retval 0 If successful.
* @retval -EINVAL If device is already detached
*/
int i3c_detach_i3c_device(struct i3c_device_desc *target);
/**
* @brief Attach an I2C device
*
* Called to attach a I2C device to the addresses. This will
* also call the optional api to update any registers within
* the driver if implemented.
*
* @warning
* Use cases involving multiple writers to the i3c/i2c devices must prevent
* concurrent write operations, either by preventing all writers from
* being preempted or by using a mutex to govern writes to the i3c/i2c devices.
*
* @param target Pointer to the target device descriptor
*
* @retval 0 If successful.
* @retval -EINVAL If address is not available or if the device
* has already been attached before
*/
int i3c_attach_i2c_device(struct i3c_i2c_device_desc *target);
/**
* @brief Detach I2C Device
*
* called to remove an I2C device and to free up the address
* that it used. This will also call the optional api to
* update any registers within the driver if implemented.
*
* @warning
* Use cases involving multiple writers to the i3c/i2c devices must prevent
* concurrent write operations, either by preventing all writers from
* being preempted or by using a mutex to govern writes to the i3c/i2c devices.
*
* @param target Pointer to the target device descriptor
*
* @retval 0 If successful.
* @retval -EINVAL If device is already detached
*/
int i3c_detach_i2c_device(struct i3c_i2c_device_desc *target);
/**
* @brief Perform Dynamic Address Assignment on the I3C bus.
*
* This routine asks the controller to perform dynamic address assignment
* where the controller belongs. Only the active controller of the bus
* should do this.
*
* @note For controller driver implementation, the controller should perform
* SETDASA to allow static addresses to be the dynamic addresses before
* actually doing ENTDAA.
*
* @param dev Pointer to the device structure for the controller driver
* instance.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
* @retval -ENODEV If a provisioned ID does not match to any target devices
* in the registered device list.
* @retval -ENOSPC No more free addresses can be assigned to target.
* @retval -ENOSYS Dynamic address assignment is not supported by
* the controller driver.
*/
static inline int i3c_do_daa(const struct device *dev)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)dev->api;
if (api->do_daa == NULL) {
return -ENOSYS;
}
return api->do_daa(dev);
}
/**
* @brief Send CCC to the bus.
*
* @param dev Pointer to the device structure for the controller driver
* instance.
* @param payload Pointer to the structure describing the CCC payload.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General Input / output error.
* @retval -EINVAL Invalid valid set in the payload structure.
* @retval -ENOSYS Not implemented.
*/
__syscall int i3c_do_ccc(const struct device *dev,
struct i3c_ccc_payload *payload);
static inline int z_impl_i3c_do_ccc(const struct device *dev,
struct i3c_ccc_payload *payload)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)dev->api;
if (api->do_ccc == NULL) {
return -ENOSYS;
}
return api->do_ccc(dev, payload);
}
/**
* @addtogroup i3c_transfer_api
* @{
*/
/**
* @brief Perform data transfer from the controller to a I3C target device.
*
* This routine provides a generic interface to perform data transfer
* to a target device synchronously. Use i3c_read()/i3c_write()
* for simple read or write.
*
* The array of message @p msgs must not be `NULL`. The number of
* message @p num_msgs may be zero, in which case no transfer occurs.
*
* @note Not all scatter/gather transactions can be supported by all
* drivers. As an example, a gather write (multiple consecutive
* i3c_msg buffers all configured for #I3C_MSG_WRITE) may be packed
* into a single transaction by some drivers, but others may emit each
* fragment as a distinct write transaction, which will not produce
* the same behavior. See the documentation of i3c_msg for
* limitations on support for multi-message bus transactions.
*
* @param target I3C target device descriptor.
* @param msgs Array of messages to transfer.
* @param num_msgs Number of messages to transfer.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
__syscall int i3c_transfer(struct i3c_device_desc *target,
struct i3c_msg *msgs, uint8_t num_msgs);
static inline int z_impl_i3c_transfer(struct i3c_device_desc *target,
struct i3c_msg *msgs, uint8_t num_msgs)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)target->bus->api;
return api->i3c_xfers(target->bus, target, msgs, num_msgs);
}
/** @} */
/**
* Find a registered I3C target device.
*
* Controller only API.
*
* This returns the I3C device descriptor of the I3C device
* matching the incoming @p id.
*
* @param dev Pointer to controller device driver instance.
* @param id Pointer to I3C device ID.
*
* @return Pointer to I3C device descriptor, or `NULL` if
* no I3C device found matching incoming @p id.
*/
static inline
struct i3c_device_desc *i3c_device_find(const struct device *dev,
const struct i3c_device_id *id)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)dev->api;
if (api->i3c_device_find == NULL) {
return NULL;
}
return api->i3c_device_find(dev, id);
}
/**
* @addtogroup i3c_ibi
* @{
*/
/**
* @brief Raise an In-Band Interrupt (IBI).
*
* This raises an In-Band Interrupt (IBI) to the active controller.
*
* @param dev Pointer to controller device driver instance.
* @param request Pointer to the IBI request struct.
*
* @retval 0 if operation is successful.
* @retval -EIO General input / output error.
*/
static inline int i3c_ibi_raise(const struct device *dev,
struct i3c_ibi *request)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)dev->api;
if (api->ibi_raise == NULL) {
return -ENOSYS;
}
return api->ibi_raise(dev, request);
}
/**
* @brief Enable IBI of a target device.
*
* This enables IBI of a target device where the IBI has already been
* request.
*
* @param target I3C target device descriptor.
*
* @retval 0 If successful.
* @retval -EIO General Input / output error.
* @retval -ENOMEM If these is no more empty entries in
* the controller's IBI table (if the controller
* uses such table).
*/
static inline int i3c_ibi_enable(struct i3c_device_desc *target)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)target->bus->api;
if (api->ibi_enable == NULL) {
return -ENOSYS;
}
return api->ibi_enable(target->bus, target);
}
/**
* @brief Disable IBI of a target device.
*
* This enables IBI of a target device where the IBI has already been
* request.
*
* @param target I3C target device descriptor.
*
* @retval 0 If successful.
* @retval -EIO General Input / output error.
* @retval -ENODEV If IBI is not previously enabled for @p target.
*/
static inline int i3c_ibi_disable(struct i3c_device_desc *target)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)target->bus->api;
if (api->ibi_disable == NULL) {
return -ENOSYS;
}
return api->ibi_disable(target->bus, target);
}
/**
* @brief Check if target's IBI has payload.
*
* This reads the BCR from the device descriptor struct to determine
* whether IBI from device has payload.
*
* Note that BCR must have been obtained from device and
* i3c_device_desc::bcr must be set.
*
* @return True if IBI has payload, false otherwise.
*/
static inline int i3c_ibi_has_payload(struct i3c_device_desc *target)
{
return (target->bcr & I3C_BCR_IBI_PAYLOAD_HAS_DATA_BYTE)
== I3C_BCR_IBI_PAYLOAD_HAS_DATA_BYTE;
}
/**
* @brief Check if device is IBI capable.
*
* This reads the BCR from the device descriptor struct to determine
* whether device is capable of IBI.
*
* Note that BCR must have been obtained from device and
* i3c_device_desc::bcr must be set.
*
* @return True if IBI has payload, false otherwise.
*/
static inline int i3c_device_is_ibi_capable(struct i3c_device_desc *target)
{
return (target->bcr & I3C_BCR_IBI_REQUEST_CAPABLE)
== I3C_BCR_IBI_REQUEST_CAPABLE;
}
/** @} */
/**
* @addtogroup i3c_transfer_api
* @{
*/
/**
* @brief Write a set amount of data to an I3C target device.
*
* This routine writes a set amount of data synchronously.
*
* @param target I3C target device descriptor.
* @param buf Memory pool from which the data is transferred.
* @param num_bytes Number of bytes to write.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_write(struct i3c_device_desc *target,
const uint8_t *buf, uint32_t num_bytes)
{
struct i3c_msg msg;
msg.buf = (uint8_t *)buf;
msg.len = num_bytes;
msg.flags = I3C_MSG_WRITE | I3C_MSG_STOP;
msg.hdr_mode = 0;
msg.hdr_cmd_code = 0;
return i3c_transfer(target, &msg, 1);
}
/**
* @brief Read a set amount of data from an I3C target device.
*
* This routine reads a set amount of data synchronously.
*
* @param target I3C target device descriptor.
* @param buf Memory pool that stores the retrieved data.
* @param num_bytes Number of bytes to read.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_read(struct i3c_device_desc *target,
uint8_t *buf, uint32_t num_bytes)
{
struct i3c_msg msg;
msg.buf = buf;
msg.len = num_bytes;
msg.flags = I3C_MSG_READ | I3C_MSG_STOP;
msg.hdr_mode = 0;
msg.hdr_cmd_code = 0;
return i3c_transfer(target, &msg, 1);
}
/**
* @brief Write then read data from an I3C target device.
*
* This supports the common operation "this is what I want", "now give
* it to me" transaction pair through a combined write-then-read bus
* transaction.
*
* @param target I3C target device descriptor.
* @param write_buf Pointer to the data to be written
* @param num_write Number of bytes to write
* @param read_buf Pointer to storage for read data
* @param num_read Number of bytes to read
*
* @retval 0 if successful
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_write_read(struct i3c_device_desc *target,
const void *write_buf, size_t num_write,
void *read_buf, size_t num_read)
{
struct i3c_msg msg[2];
msg[0].buf = (uint8_t *)write_buf;
msg[0].len = num_write;
msg[0].flags = I3C_MSG_WRITE;
msg[0].hdr_mode = 0;
msg[0].hdr_cmd_code = 0;
msg[1].buf = (uint8_t *)read_buf;
msg[1].len = num_read;
msg[1].flags = I3C_MSG_RESTART | I3C_MSG_READ | I3C_MSG_STOP;
msg[1].hdr_mode = 0;
msg[1].hdr_cmd_code = 0;
return i3c_transfer(target, msg, 2);
}
/**
* @brief Read multiple bytes from an internal address of an I3C target device.
*
* This routine reads multiple bytes from an internal address of an
* I3C target device synchronously.
*
* Instances of this may be replaced by i3c_write_read().
*
* @param target I3C target device descriptor,
* @param start_addr Internal address from which the data is being read.
* @param buf Memory pool that stores the retrieved data.
* @param num_bytes Number of bytes being read.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_burst_read(struct i3c_device_desc *target,
uint8_t start_addr,
uint8_t *buf,
uint32_t num_bytes)
{
return i3c_write_read(target,
&start_addr, sizeof(start_addr),
buf, num_bytes);
}
/**
* @brief Write multiple bytes to an internal address of an I3C target device.
*
* This routine writes multiple bytes to an internal address of an
* I3C target device synchronously.
*
* @warning The combined write synthesized by this API may not be
* supported on all I3C devices. Uses of this API may be made more
* portable by replacing them with calls to i3c_write() passing a
* buffer containing the combined address and data.
*
* @param target I3C target device descriptor.
* @param start_addr Internal address to which the data is being written.
* @param buf Memory pool from which the data is transferred.
* @param num_bytes Number of bytes being written.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_burst_write(struct i3c_device_desc *target,
uint8_t start_addr,
const uint8_t *buf,
uint32_t num_bytes)
{
struct i3c_msg msg[2];
msg[0].buf = &start_addr;
msg[0].len = 1U;
msg[0].flags = I3C_MSG_WRITE;
msg[0].hdr_mode = 0;
msg[0].hdr_cmd_code = 0;
msg[1].buf = (uint8_t *)buf;
msg[1].len = num_bytes;
msg[1].flags = I3C_MSG_WRITE | I3C_MSG_STOP;
msg[1].hdr_mode = 0;
msg[1].hdr_cmd_code = 0;
return i3c_transfer(target, msg, 2);
}
/**
* @brief Read internal register of an I3C target device.
*
* This routine reads the value of an 8-bit internal register of an I3C target
* device synchronously.
*
* @param target I3C target device descriptor.
* @param reg_addr Address of the internal register being read.
* @param value Memory pool that stores the retrieved register value.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_reg_read_byte(struct i3c_device_desc *target,
uint8_t reg_addr, uint8_t *value)
{
return i3c_write_read(target,
®_addr, sizeof(reg_addr),
value, sizeof(*value));
}
/**
* @brief Write internal register of an I3C target device.
*
* This routine writes a value to an 8-bit internal register of an I3C target
* device synchronously.
*
* @note This function internally combines the register and value into
* a single bus transaction.
*
* @param target I3C target device descriptor.
* @param reg_addr Address of the internal register being written.
* @param value Value to be written to internal register.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_reg_write_byte(struct i3c_device_desc *target,
uint8_t reg_addr, uint8_t value)
{
uint8_t tx_buf[2] = {reg_addr, value};
return i3c_write(target, tx_buf, 2);
}
/**
* @brief Update internal register of an I3C target device.
*
* This routine updates the value of a set of bits from an 8-bit internal
* register of an I3C target device synchronously.
*
* @note If the calculated new register value matches the value that
* was read this function will not generate a write operation.
*
* @param target I3C target device descriptor.
* @param reg_addr Address of the internal register being updated.
* @param mask Bitmask for updating internal register.
* @param value Value for updating internal register.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_reg_update_byte(struct i3c_device_desc *target,
uint8_t reg_addr, uint8_t mask,
uint8_t value)
{
uint8_t old_value, new_value;
int rc;
rc = i3c_reg_read_byte(target, reg_addr, &old_value);
if (rc != 0) {
return rc;
}
new_value = (old_value & ~mask) | (value & mask);
if (new_value == old_value) {
return 0;
}
return i3c_reg_write_byte(target, reg_addr, new_value);
}
/**
* @brief Dump out an I3C message
*
* Dumps out a list of I3C messages. For any that are writes (W), the data is
* displayed in hex.
*
* It looks something like this (with name "testing"):
*
* @code
* D: I3C msg: testing, addr=56
* D: W len=01:
* D: contents:
* D: 06 |.
* D: W len=0e:
* D: contents:
* D: 00 01 02 03 04 05 06 07 |........
* D: 08 09 0a 0b 0c 0d |......
* @endcode
*
* @param name Name of this dump, displayed at the top.
* @param msgs Array of messages to dump.
* @param num_msgs Number of messages to dump.
* @param target I3C target device descriptor.
*/
void i3c_dump_msgs(const char *name, const struct i3c_msg *msgs,
uint8_t num_msgs, struct i3c_device_desc *target);
/** @} */
/**
* @brief Generic helper function to perform bus initialization.
*
* @param dev Pointer to controller device driver instance.
* @param i3c_dev_list Pointer to I3C device list.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
* @retval -ENODEV If a provisioned ID does not match to any target devices
* in the registered device list.
* @retval -ENOSPC No more free addresses can be assigned to target.
* @retval -ENOSYS Dynamic address assignment is not supported by
* the controller driver.
*/
int i3c_bus_init(const struct device *dev,
const struct i3c_dev_list *i3c_dev_list);
/**
* @brief Get basic information from device and update device descriptor.
*
* This retrieves some basic information:
* * Bus Characteristics Register (GETBCR)
* * Device Characteristics Register (GETDCR)
* * Max Read Length (GETMRL)
* * Max Write Length (GETMWL)
* from the device and update the corresponding fields of the device
* descriptor.
*
* This only updates the field(s) in device descriptor
* only if CCC operations succeed.
*
* @param[in,out] target I3C target device descriptor.
*
* @retval 0 if successful.
* @retval -EIO General Input/Output error.
*/
int i3c_device_basic_info_get(struct i3c_device_desc *target);
/*
* This needs to be after declaration of struct i3c_driver_api,
* or else compiler complains about undefined type inside
* the static inline API wrappers.
*/
#include <zephyr/drivers/i3c/target_device.h>
/*
* Include High-Data-Rate (HDR) inline helper functions
*/
#include <zephyr/drivers/i3c/hdr_ddr.h>
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/i3c.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_I3C_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/i3c.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 15,374 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_EMUL_STUB_DEVICE_H_
#define ZEPHYR_INCLUDE_EMUL_STUB_DEVICE_H_
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
/*
* Needed for emulators without corresponding DEVICE_DT_DEFINE drivers
*/
struct emul_stub_dev_data {
/* Stub */
};
struct emul_stub_dev_config {
/* Stub */
};
struct emul_stub_dev_api {
/* Stub */
};
/* For every instance of a DT_DRV_COMPAT stub out a device for that instance */
#define EMUL_STUB_DEVICE(n) \
__maybe_unused static int emul_init_stub_##n(const struct device *dev) \
{ \
ARG_UNUSED(dev); \
return 0; \
} \
\
static struct emul_stub_dev_data stub_data_##n; \
static struct emul_stub_dev_config stub_config_##n; \
static struct emul_stub_dev_api stub_api_##n; \
DEVICE_DT_INST_DEFINE(n, &emul_init_stub_##n, NULL, &stub_data_##n, &stub_config_##n, \
POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &stub_api_##n);
#endif /* ZEPHYR_INCLUDE_EMUL_STUB_DEVICE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/emul_stub_device.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 278 |
```objective-c
/*
*
*/
/**
* @file drivers/cellular.h
* @brief Public cellular network API
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CELLULAR_H_
#define ZEPHYR_INCLUDE_DRIVERS_CELLULAR_H_
/**
* @brief Cellular interface
* @defgroup cellular_interface Cellular Interface
* @ingroup io_interfaces
* @{
*/
#include <zephyr/types.h>
#include <zephyr/device.h>
#include <errno.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Cellular access technologies */
enum cellular_access_technology {
CELLULAR_ACCESS_TECHNOLOGY_GSM = 0,
CELLULAR_ACCESS_TECHNOLOGY_GPRS,
CELLULAR_ACCESS_TECHNOLOGY_UMTS,
CELLULAR_ACCESS_TECHNOLOGY_EDGE,
CELLULAR_ACCESS_TECHNOLOGY_LTE,
CELLULAR_ACCESS_TECHNOLOGY_LTE_CAT_M1,
CELLULAR_ACCESS_TECHNOLOGY_LTE_CAT_M2,
CELLULAR_ACCESS_TECHNOLOGY_NB_IOT,
};
/** Cellular network structure */
struct cellular_network {
/** Cellular access technology */
enum cellular_access_technology technology;
/**
* List of bands, as defined by the specified cellular access technology,
* to enables. All supported bands are enabled if none are provided.
*/
uint16_t *bands;
/** Size of bands */
uint16_t size;
};
/** Cellular signal type */
enum cellular_signal_type {
CELLULAR_SIGNAL_RSSI,
CELLULAR_SIGNAL_RSRP,
CELLULAR_SIGNAL_RSRQ,
};
/** Cellular modem info type */
enum cellular_modem_info_type {
/** International Mobile Equipment Identity */
CELLULAR_MODEM_INFO_IMEI,
/** Modem model ID */
CELLULAR_MODEM_INFO_MODEL_ID,
/** Modem manufacturer */
CELLULAR_MODEM_INFO_MANUFACTURER,
/** Modem fw version */
CELLULAR_MODEM_INFO_FW_VERSION,
/** International Mobile Subscriber Identity */
CELLULAR_MODEM_INFO_SIM_IMSI,
/** Integrated Circuit Card Identification Number (SIM) */
CELLULAR_MODEM_INFO_SIM_ICCID,
};
enum cellular_registration_status {
CELLULAR_REGISTRATION_NOT_REGISTERED = 0,
CELLULAR_REGISTRATION_REGISTERED_HOME,
CELLULAR_REGISTRATION_SEARCHING,
CELLULAR_REGISTRATION_DENIED,
CELLULAR_REGISTRATION_UNKNOWN,
CELLULAR_REGISTRATION_REGISTERED_ROAMING,
};
/** API for configuring networks */
typedef int (*cellular_api_configure_networks)(const struct device *dev,
const struct cellular_network *networks,
uint8_t size);
/** API for getting supported networks */
typedef int (*cellular_api_get_supported_networks)(const struct device *dev,
const struct cellular_network **networks,
uint8_t *size);
/** API for getting network signal strength */
typedef int (*cellular_api_get_signal)(const struct device *dev,
const enum cellular_signal_type type, int16_t *value);
/** API for getting modem information */
typedef int (*cellular_api_get_modem_info)(const struct device *dev,
const enum cellular_modem_info_type type,
char *info, size_t size);
/** API for getting registration status */
typedef int (*cellular_api_get_registration_status)(const struct device *dev,
enum cellular_access_technology tech,
enum cellular_registration_status *status);
/** Cellular driver API */
__subsystem struct cellular_driver_api {
cellular_api_configure_networks configure_networks;
cellular_api_get_supported_networks get_supported_networks;
cellular_api_get_signal get_signal;
cellular_api_get_modem_info get_modem_info;
cellular_api_get_registration_status get_registration_status;
};
/**
* @brief Configure cellular networks for the device
*
* @details Cellular network devices support at least one cellular access technology.
* Each cellular access technology defines a set of bands, of which the cellular device
* will support all or a subset of.
*
* The cellular device can only use one cellular network technology at a time. It must
* exclusively use the cellular network configurations provided, and will prioritize
* the cellular network configurations in the order they are provided in case there are
* multiple (the first cellular network configuration has the highest priority).
*
* @param dev Cellular network device instance.
* @param networks List of cellular network configurations to apply.
* @param size Size of list of cellular network configurations.
*
* @retval 0 if successful.
* @retval -EINVAL if any provided cellular network configuration is invalid or unsupported.
* @retval -ENOTSUP if API is not supported by cellular network device.
* @retval Negative errno-code otherwise.
*/
static inline int cellular_configure_networks(const struct device *dev,
const struct cellular_network *networks, uint8_t size)
{
const struct cellular_driver_api *api = (const struct cellular_driver_api *)dev->api;
if (api->configure_networks == NULL) {
return -ENOSYS;
}
return api->configure_networks(dev, networks, size);
}
/**
* @brief Get supported cellular networks for the device
*
* @param dev Cellular network device instance
* @param networks Pointer to list of supported cellular network configurations.
* @param size Size of list of cellular network configurations.
*
* @retval 0 if successful.
* @retval -ENOTSUP if API is not supported by cellular network device.
* @retval Negative errno-code otherwise.
*/
static inline int cellular_get_supported_networks(const struct device *dev,
const struct cellular_network **networks,
uint8_t *size)
{
const struct cellular_driver_api *api = (const struct cellular_driver_api *)dev->api;
if (api->get_supported_networks == NULL) {
return -ENOSYS;
}
return api->get_supported_networks(dev, networks, size);
}
/**
* @brief Get signal for the device
*
* @param dev Cellular network device instance
* @param type Type of the signal information requested
* @param value Signal strength destination (one of RSSI, RSRP, RSRQ)
*
* @retval 0 if successful.
* @retval -ENOTSUP if API is not supported by cellular network device.
* @retval -ENODATA if device is not in a state where signal can be polled
* @retval Negative errno-code otherwise.
*/
static inline int cellular_get_signal(const struct device *dev,
const enum cellular_signal_type type, int16_t *value)
{
const struct cellular_driver_api *api = (const struct cellular_driver_api *)dev->api;
if (api->get_signal == NULL) {
return -ENOSYS;
}
return api->get_signal(dev, type, value);
}
/**
* @brief Get modem info for the device
*
* @param dev Cellular network device instance
* @param type Type of the modem info requested
* @param info Info string destination
* @param size Info string size
*
* @retval 0 if successful.
* @retval -ENOTSUP if API is not supported by cellular network device.
* @retval -ENODATA if modem does not provide info requested
* @retval Negative errno-code from chat module otherwise.
*/
static inline int cellular_get_modem_info(const struct device *dev,
const enum cellular_modem_info_type type, char *info,
size_t size)
{
const struct cellular_driver_api *api = (const struct cellular_driver_api *)dev->api;
if (api->get_modem_info == NULL) {
return -ENOSYS;
}
return api->get_modem_info(dev, type, info, size);
}
/**
* @brief Get network registration status for the device
*
* @param dev Cellular network device instance
* @param tech Which access technology to get status for
* @param status Registration status for given access technology
*
* @retval 0 if successful.
* @retval -ENOSYS if API is not supported by cellular network device.
* @retval -ENODATA if modem does not provide info requested
* @retval Negative errno-code from chat module otherwise.
*/
static inline int cellular_get_registration_status(const struct device *dev,
enum cellular_access_technology tech,
enum cellular_registration_status *status)
{
const struct cellular_driver_api *api = (const struct cellular_driver_api *)dev->api;
if (api->get_registration_status == NULL) {
return -ENOSYS;
}
return api->get_registration_status(dev, tech, status);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_CELLULAR_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/cellular.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,790 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_MSPI_EMUL_H_
#define ZEPHYR_INCLUDE_DRIVERS_MSPI_EMUL_H_
#include <zephyr/device.h>
#include <zephyr/drivers/emul.h>
#include <zephyr/drivers/mspi.h>
#include <zephyr/sys/slist.h>
#include <zephyr/types.h>
/**
* @file
*
* @brief Public APIs for the MSPI emulation drivers.
*/
/**
* @brief MSPI Emulation Interface
* @defgroup mspi_emul_interface MSPI Emulation Interface
* @ingroup io_emulators
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
struct mspi_emul;
/**
* Find an emulator present on a MSPI bus
*
* At present the function is used only to find an emulator of the host
* device. It may be useful in systems with the SPI flash chips.
*
* @param dev MSPI emulation controller device
* @param dev_idx Device index from device tree.
* @return mspi_emul to use
* @return NULL if not found
*/
typedef struct mspi_emul *(*mspi_emul_find_emul)(const struct device *dev,
uint16_t dev_idx);
/**
* Triggers an event on the emulator of MSPI controller side which causes
* calling specific callbacks.
*
* @param dev MSPI emulation controller device
* @param evt_type Event type to be triggered @see mspi_bus_event
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
typedef int (*mspi_emul_trigger_event)(const struct device *dev,
enum mspi_bus_event evt_type);
/**
* Loopback MSPI transceive request to the device emulator
* as no real hardware attached
*
* @param target The device Emulator instance
* @param packets Pointer to the buffers of command, addr, data and etc.
* @param num_packet The number of packets in packets.
* @param async Indicate whether this is a asynchronous request.
* @param timeout Maximum Time allowed for this request
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
typedef int (*emul_mspi_dev_api_transceive)(const struct emul *target,
const struct mspi_xfer_packet *packets,
uint32_t num_packet,
bool async,
uint32_t timeout);
/** Definition of the MSPI device emulator API */
struct emul_mspi_device_api {
emul_mspi_dev_api_transceive transceive;
};
/** Node in a linked list of emulators for MSPI devices */
struct mspi_emul {
sys_snode_t node;
/** Target emulator - REQUIRED for all emulated bus nodes of any type */
const struct emul *target;
/** API provided for this device */
const struct emul_mspi_device_api *api;
/** device index */
uint16_t dev_idx;
};
/** Definition of the MSPI controller emulator API */
struct emul_mspi_driver_api {
/* The struct mspi_driver_api has to be first in
* struct emul_mspi_driver_api to make pointer casting working
*/
struct mspi_driver_api mspi_api;
/* The rest, emulator specific functions */
mspi_emul_trigger_event trigger_event;
mspi_emul_find_emul find_emul;
};
/**
* Register an emulated device on the controller
*
* @param dev MSPI emulation controller device
* @param emul MSPI device emulator to be registered
* @return 0 indicating success (always)
*/
int mspi_emul_register(const struct device *dev, struct mspi_emul *emul);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_MSPI_EMUL_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/mspi_emul.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 812 |
```objective-c
/*
*
*/
/**
* @file
* @brief Backend APIs for the fuel gauge emulators.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_EMUL_FUEL_GAUGE_H_
#define ZEPHYR_INCLUDE_DRIVERS_EMUL_FUEL_GAUGE_H_
#include <stdint.h>
#include <zephyr/drivers/emul.h>
#include <zephyr/drivers/fuel_gauge.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Fuel gauge backend emulator APIs
* @defgroup fuel_gauge_emulator_backend Fuel gauge backend emulator APIs
* @ingroup io_interfaces
* @{
*/
/**
* @cond INTERNAL_HIDDEN
*
* These are for internal use only, so skip these in public documentation.
*/
__subsystem struct fuel_gauge_emul_driver_api {
int (*set_battery_charging)(const struct emul *emul, uint32_t uV, int uA);
int (*is_battery_cutoff)(const struct emul *emul, bool *cutoff);
};
/**
* @endcond
*/
/**
* @brief Set charging for fuel gauge associated battery.
*
* Set how much the battery associated with a fuel gauge IC is charging or discharging. Where
* voltage is always positive and a positive or negative current denotes charging or discharging,
* respectively.
*
* @param target Pointer to the emulator structure for the fuel gauge emulator instance.
* @param uV Microvolts describing the battery voltage.
* @param uA Microamps describing the battery current where negative is discharging.
*
* @retval 0 If successful.
* @retval -EINVAL if mV or mA are 0.
*/
__syscall int emul_fuel_gauge_set_battery_charging(const struct emul *target, uint32_t uV, int uA);
static inline int z_impl_emul_fuel_gauge_set_battery_charging(const struct emul *target,
uint32_t uV, int uA)
{
const struct fuel_gauge_emul_driver_api *backend_api =
(const struct fuel_gauge_emul_driver_api *)target->backend_api;
if (backend_api->set_battery_charging == 0) {
return -ENOTSUP;
}
return backend_api->set_battery_charging(target, uV, uA);
}
/**
* @brief Check if the battery has been cut off.
*
* @param target Pointer to the emulator structure for the fuel gauge emulator instance.
* @param cutoff Pointer to bool storing variable.
*
* @retval 0 If successful.
* @retval -ENOTSUP if not supported by emulator.
*/
__syscall int emul_fuel_gauge_is_battery_cutoff(const struct emul *target, bool *cutoff);
static inline int z_impl_emul_fuel_gauge_is_battery_cutoff(const struct emul *target, bool *cutoff)
{
const struct fuel_gauge_emul_driver_api *backend_api =
(const struct fuel_gauge_emul_driver_api *)target->backend_api;
if (backend_api->is_battery_cutoff == 0) {
return -ENOTSUP;
}
return backend_api->is_battery_cutoff(target, cutoff);
}
#ifdef __cplusplus
}
#endif
#include <zephyr/syscalls/emul_fuel_gauge.h>
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_EMUL_FUEL_GAUGE_H_*/
``` | /content/code_sandbox/include/zephyr/drivers/emul_fuel_gauge.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 699 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_FPGA_H_
#define ZEPHYR_INCLUDE_DRIVERS_FPGA_H_
#include <errno.h>
#include <zephyr/types.h>
#include <zephyr/sys/util.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
enum FPGA_status {
/* Inactive is when the FPGA cannot accept the bitstream
* and will not be programmed correctly
*/
FPGA_STATUS_INACTIVE,
/* Active is when the FPGA can accept the bitstream and
* can be programmed correctly
*/
FPGA_STATUS_ACTIVE
};
typedef enum FPGA_status (*fpga_api_get_status)(const struct device *dev);
typedef int (*fpga_api_load)(const struct device *dev, uint32_t *image_ptr,
uint32_t img_size);
typedef int (*fpga_api_reset)(const struct device *dev);
typedef int (*fpga_api_on)(const struct device *dev);
typedef int (*fpga_api_off)(const struct device *dev);
typedef const char *(*fpga_api_get_info)(const struct device *dev);
__subsystem struct fpga_driver_api {
fpga_api_get_status get_status;
fpga_api_reset reset;
fpga_api_load load;
fpga_api_on on;
fpga_api_off off;
fpga_api_get_info get_info;
};
/**
* @brief Read the status of FPGA.
*
* @param dev FPGA device structure.
*
* @retval 0 if the FPGA is in INACTIVE state.
* @retval 1 if the FPGA is in ACTIVE state.
*/
static inline enum FPGA_status fpga_get_status(const struct device *dev)
{
const struct fpga_driver_api *api =
(const struct fpga_driver_api *)dev->api;
if (api->get_status == NULL) {
/* assume it can never be reprogrammed if it
* doesn't support the get_status callback
*/
return FPGA_STATUS_INACTIVE;
}
return api->get_status(dev);
}
/**
* @brief Reset the FPGA.
*
* @param dev FPGA device structure.
*
* @retval 0 if successful.
* @retval Failed Otherwise.
*/
static inline int fpga_reset(const struct device *dev)
{
const struct fpga_driver_api *api =
(const struct fpga_driver_api *)dev->api;
if (api->reset == NULL) {
return -ENOTSUP;
}
return api->reset(dev);
}
/**
* @brief Load the bitstream and program the FPGA
*
* @param dev FPGA device structure.
* @param image_ptr Pointer to bitstream.
* @param img_size Bitstream size in bytes.
*
* @retval 0 if successful.
* @retval Failed Otherwise.
*/
static inline int fpga_load(const struct device *dev, uint32_t *image_ptr,
uint32_t img_size)
{
const struct fpga_driver_api *api =
(const struct fpga_driver_api *)dev->api;
if (api->load == NULL) {
return -ENOTSUP;
}
return api->load(dev, image_ptr, img_size);
}
/**
* @brief Turns on the FPGA.
*
* @param dev FPGA device structure.
*
* @retval 0 if successful.
* @retval negative errno code on failure.
*/
static inline int fpga_on(const struct device *dev)
{
const struct fpga_driver_api *api =
(const struct fpga_driver_api *)dev->api;
if (api->on == NULL) {
return -ENOTSUP;
}
return api->on(dev);
}
#define FPGA_GET_INFO_DEFAULT "n/a"
/**
* @brief Returns information about the FPGA.
*
* @param dev FPGA device structure.
*
* @return String containing information.
*/
static inline const char *fpga_get_info(const struct device *dev)
{
const struct fpga_driver_api *api =
(const struct fpga_driver_api *)dev->api;
if (api->get_info == NULL) {
return FPGA_GET_INFO_DEFAULT;
}
return api->get_info(dev);
}
/**
* @brief Turns off the FPGA.
*
* @param dev FPGA device structure.
*
* @retval 0 if successful.
* @retval negative errno code on failure.
*/
static inline int fpga_off(const struct device *dev)
{
const struct fpga_driver_api *api =
(const struct fpga_driver_api *)dev->api;
if (api->off == NULL) {
return -ENOTSUP;
}
return api->off(dev);
}
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_FPGA_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/fpga.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 974 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_ESPI_SPI_EMUL_H_
#define ZEPHYR_INCLUDE_DRIVERS_ESPI_SPI_EMUL_H_
#include <zephyr/device.h>
#include <zephyr/drivers/emul.h>
#include <zephyr/drivers/espi.h>
#include <zephyr/sys/slist.h>
#include <zephyr/types.h>
/**
* @file
*
* @brief Public APIs for the eSPI emulation drivers.
*/
/**
* @brief eSPI Emulation Interface
* @defgroup espi_emul_interface eSPI Emulation Interface
* @ingroup io_emulators
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
#define EMUL_ESPI_HOST_CHIPSEL 0
struct espi_emul;
/**
* Passes eSPI virtual wires set request (virtual wire packet) to the emulator.
* The emulator updates the state (level) of its virtual wire.
*
* @param target The device Emulator instance
* @param vw The signal to be set.
* @param level The level of signal requested LOW(0) or HIGH(1).
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
typedef int (*emul_espi_api_set_vw)(const struct emul *target, enum espi_vwire_signal vw,
uint8_t level);
/**
* Passes eSPI virtual wires get request (virtual wire packet) to the emulator.
* The emulator returns the state (level) of its virtual wire.
*
* @param target The device Emulator instance
* @param vw The signal to be get.
* @param level The level of the signal to be get.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
typedef int (*emul_espi_api_get_vw)(const struct emul *target, enum espi_vwire_signal vw,
uint8_t *level);
#ifdef CONFIG_ESPI_PERIPHERAL_ACPI_SHM_REGION
/**
* Get the ACPI shared memory address owned by the emulator.
*
* @param target The device Emulator instance
*
* @retval The address of the memory.
*/
typedef uintptr_t (*emul_espi_api_get_acpi_shm)(const struct emul *target);
#endif
/**
* Find an emulator present on a eSPI bus
*
* At present the function is used only to find an emulator of the host
* device. It may be useful in systems with the SPI flash chips.
*
* @param dev eSPI emulation controller device
* @param chipsel Chip-select value
* @return espi_emul to use
* @return NULL if not found
*/
typedef struct espi_emul *(*emul_find_emul)(const struct device *dev, unsigned int chipsel);
/**
* Triggers an event on the emulator of eSPI controller side which causes
* calling specific callbacks.
*
* @param dev Device instance of emulated eSPI controller
* @param evt Event to be triggered
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
typedef int (*emul_trigger_event)(const struct device *dev, struct espi_event *evt);
/** Definition of the eSPI device emulator API */
struct emul_espi_device_api {
emul_espi_api_set_vw set_vw;
emul_espi_api_get_vw get_vw;
#ifdef CONFIG_ESPI_PERIPHERAL_ACPI_SHM_REGION
emul_espi_api_get_acpi_shm get_acpi_shm;
#endif
};
/** Node in a linked list of emulators for eSPI devices */
struct espi_emul {
sys_snode_t node;
/** Target emulator - REQUIRED for all emulated bus nodes of any type */
const struct emul *target;
/** API provided for this device */
const struct emul_espi_device_api *api;
/** eSPI chip-select of the emulated device */
uint16_t chipsel;
};
/** Definition of the eSPI controller emulator API */
struct emul_espi_driver_api {
/* The struct espi_driver_api has to be first in
* struct emul_espi_driver_api to make pointer casting working
*/
struct espi_driver_api espi_api;
/* The rest, emulator specific functions */
emul_trigger_event trigger_event;
emul_find_emul find_emul;
};
/**
* Register an emulated device on the controller
*
* @param dev Device that will use the emulator
* @param emul eSPI emulator to use
* @return 0 indicating success (always)
*/
int espi_emul_register(const struct device *dev, struct espi_emul *emul);
/**
* Sets the eSPI virtual wire on the host side, which will
* trigger a proper event(and callbacks) on the emulated eSPI controller
*
* @param espi_dev eSPI emulation controller device
* @param vw The signal to be set.
* @param level The level of the signal to be set.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
int emul_espi_host_send_vw(const struct device *espi_dev, enum espi_vwire_signal vw, uint8_t level);
/**
* Perform port80 write on the emulated host side, which will
* trigger a proper event(and callbacks) on the emulated eSPI controller
*
* @param espi_dev eSPI emulation controller device
* @param data The date to be written.
*
* @retval 0 If successful.
* @retval -EIO General input / output error.
*/
int emul_espi_host_port80_write(const struct device *espi_dev, uint32_t data);
#ifdef CONFIG_ESPI_PERIPHERAL_ACPI_SHM_REGION
/**
* Get the host device's ACPI shared memory start address. The size of the region is
* CONFIG_EMUL_ESPI_HOST_ACPI_SHM_REGION_SIZE.
*
* @param espi_dev eSPI emulation controller device.
* @return Address of the start of the ACPI shared memory.
*/
uintptr_t emul_espi_host_get_acpi_shm(const struct device *espi_dev);
#endif
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_ESPI_SPI_EMUL_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/espi_emul.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,333 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_LOOPBACK_DISK_ACCESS_H_
#define ZEPHYR_INCLUDE_DRIVERS_LOOPBACK_DISK_ACCESS_H_
#include <zephyr/drivers/disk.h>
#include <zephyr/fs/fs_interface.h>
/**
* @brief Context object for an active loopback disk device
*/
struct loopback_disk_access {
struct disk_info info;
const char *file_path;
struct fs_file_t file;
size_t num_sectors;
};
/**
* @brief Register a loopback disk device
*
* Registers a new loopback disk deviced backed by a file at the specified path.
*
* @details
* @p All parameters (ctx, file_path and disk_access_name) must point to data that will remain valid
* until the disk access is unregistered. This is trivially true for file_path and disk_access_name
* if they are string literals, but care must be taken for ctx, as well as for file_path and
* disk_access_name if they are constructed dynamically.
*
* @param ctx Preallocated context structure
* @param file_path Path to backing file
* @param disk_access_name Name of the created disk access (for disk_access_*() functions)
*
* @retval 0 on success;
* @retval <0 negative errno code, depending on file system of the backing file.
*/
int loopback_disk_access_register(struct loopback_disk_access *ctx, const char *file_path,
const char *disk_access_name);
/**
* @brief Unregister a previously registered loopback disk device
*
* Cleans up resources used by the disk access.
*
* @param ctx Context structure previously passed to a successful invocation of
* loopback_disk_access_register()
*
* @retval 0 on success;
* @retval <0 negative errno code, depending on file system of the backing file.
*/
int loopback_disk_access_unregister(struct loopback_disk_access *ctx);
#endif /* ZEPHYR_INCLUDE_DRIVERS_LOOPBACK_DISK_ACCESS_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/loopback_disk.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 412 |
```objective-c
/*
*
*/
/**
* @file
* @brief Public API for controlling linear strips of LEDs.
*
* This library abstracts the chipset drivers for individually
* addressable strips of LEDs.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_LED_STRIP_H_
#define ZEPHYR_INCLUDE_DRIVERS_LED_STRIP_H_
/**
* @brief LED Strip Interface
* @defgroup led_strip_interface LED Strip Interface
* @ingroup io_interfaces
* @{
*/
#include <errno.h>
#include <zephyr/types.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Color value for a single RGB LED.
*
* Individual strip drivers may ignore lower-order bits if their
* resolution in any channel is less than a full byte.
*/
struct led_rgb {
#ifdef CONFIG_LED_STRIP_RGB_SCRATCH
/*
* Pad/scratch space needed by some drivers. Users should
* ignore.
*/
uint8_t scratch;
#endif
/** Red channel */
uint8_t r;
/** Green channel */
uint8_t g;
/** Blue channel */
uint8_t b;
};
/**
* @typedef led_api_update_rgb
* @brief Callback API for updating an RGB LED strip
*
* @see led_strip_update_rgb() for argument descriptions.
*/
typedef int (*led_api_update_rgb)(const struct device *dev,
struct led_rgb *pixels,
size_t num_pixels);
/**
* @typedef led_api_update_channels
* @brief Callback API for updating channels without an RGB interpretation.
*
* @see led_strip_update_channels() for argument descriptions.
*/
typedef int (*led_api_update_channels)(const struct device *dev,
uint8_t *channels,
size_t num_channels);
/**
* @typedef led_api_length
* @brief Callback API for getting length of an LED strip.
*
* @see led_strip_length() for argument descriptions.
*/
typedef size_t (*led_api_length)(const struct device *dev);
/**
* @brief LED strip driver API
*
* This is the mandatory API any LED strip driver needs to expose.
*/
__subsystem struct led_strip_driver_api {
led_api_update_rgb update_rgb;
led_api_update_channels update_channels;
led_api_length length;
};
/**
* @brief Mandatory function to update an LED strip with the given RGB array.
*
* @param dev LED strip device.
* @param pixels Array of pixel data.
* @param num_pixels Length of pixels array.
*
* @retval 0 on success.
* @retval -errno negative errno code on failure.
*
* @warning This routine may overwrite @a pixels.
*/
static inline int led_strip_update_rgb(const struct device *dev,
struct led_rgb *pixels,
size_t num_pixels)
{
const struct led_strip_driver_api *api =
(const struct led_strip_driver_api *)dev->api;
/* Allow for out-of-tree drivers that do not have this function for 2 Zephyr releases
* until making it mandatory, function added after Zephyr 3.6
*/
if (api->length != NULL) {
/* Ensure supplied pixel size is valid for this device */
if (api->length(dev) < num_pixels) {
return -ERANGE;
}
}
return api->update_rgb(dev, pixels, num_pixels);
}
/**
* @brief Optional function to update an LED strip with the given channel array
* (each channel byte corresponding to an individually addressable color
* channel or LED. Channels are updated linearly in strip order.
*
* @param dev LED strip device.
* @param channels Array of per-channel data.
* @param num_channels Length of channels array.
*
* @retval 0 on success.
* @retval -ENOSYS if not implemented.
* @retval -errno negative errno code on other failure.
*
* @warning This routine may overwrite @a channels.
*/
static inline int led_strip_update_channels(const struct device *dev,
uint8_t *channels,
size_t num_channels)
{
const struct led_strip_driver_api *api =
(const struct led_strip_driver_api *)dev->api;
if (api->update_channels == NULL) {
return -ENOSYS;
}
return api->update_channels(dev, channels, num_channels);
}
/**
* @brief Mandatory function to get chain length (in pixels) of an LED strip device.
*
* @param dev LED strip device.
*
* @retval Length of LED strip device.
*/
static inline size_t led_strip_length(const struct device *dev)
{
const struct led_strip_driver_api *api =
(const struct led_strip_driver_api *)dev->api;
return api->length(dev);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_LED_STRIP_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/led_strip.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,025 |
```objective-c
/*
*
*
*/
#ifndef ZEPHYR_SOC_ARM_RENESAS_RCAR_COMMON_PINCTRL_SOC_H_
#define ZEPHYR_SOC_ARM_RENESAS_RCAR_COMMON_PINCTRL_SOC_H_
#include <zephyr/devicetree.h>
#include <zephyr/dt-bindings/pinctrl/renesas/pinctrl-rcar-common.h>
#include <stdint.h>
#include <zephyr/sys/util_macro.h>
struct rcar_pin_func {
uint8_t bank:5; /* bank number 0 - 18 */
uint8_t shift:5; /* bit shift 0 - 28 */
uint8_t func:4; /* choice from 0x0 to 0xF */
};
/** Pull-up, pull-down, or bias disable is requested */
#define RCAR_PIN_FLAGS_PULL_SET BIT(0)
/** Performs on/off control of the pull resistors */
#define RCAR_PIN_FLAGS_PUEN BIT(1)
/** Select pull-up resistor if set pull-down otherwise */
#define RCAR_PIN_FLAGS_PUD BIT(2)
/** Alternate function for the pin is requested */
#define RCAR_PIN_FLAGS_FUNC_SET BIT(3)
/** Ignore IPSR settings for alternate function pin */
#define RCAR_PIN_FLAGS_FUNC_DUMMY BIT(4)
#define RCAR_PIN_PULL_UP (RCAR_PIN_FLAGS_PULL_SET | RCAR_PIN_FLAGS_PUEN | RCAR_PIN_FLAGS_PUD)
#define RCAR_PIN_PULL_DOWN (RCAR_PIN_FLAGS_PULL_SET | RCAR_PIN_FLAGS_PUEN)
#define RCAR_PIN_PULL_DISABLE RCAR_PIN_FLAGS_PULL_SET
/** Type for R-Car pin. */
typedef struct pinctrl_soc_pin {
uint16_t pin;
struct rcar_pin_func func;
uint8_t flags;
uint8_t drive_strength;
uint8_t voltage;
} pinctrl_soc_pin_t;
#define RCAR_IPSR(node_id) DT_PROP_BY_IDX(node_id, pin, 1)
#define RCAR_HAS_IPSR(node_id) DT_PROP_HAS_IDX(node_id, pin, 1)
/* Offsets are defined in dt-bindings pinctrl-rcar-common.h */
#define RCAR_PIN_FUNC(node_id) \
{ \
((RCAR_IPSR(node_id) >> 10U) & 0x1FU), \
((RCAR_IPSR(node_id) >> 4U) & 0x1FU), \
((RCAR_IPSR(node_id) & 0xFU)) \
}
#define RCAR_PIN_IS_FUNC_DUMMY(node_id) \
((((RCAR_IPSR(node_id) >> 10U) & 0x1FU) == 0x1F) && \
(((RCAR_IPSR(node_id) >> 4U) & 0x1FU) == 0x1F) && \
((RCAR_IPSR(node_id) & 0xFU) == 0xF))
#define RCAR_PIN_FLAGS(node_id) \
DT_PROP(node_id, bias_pull_up) * RCAR_PIN_PULL_UP | \
DT_PROP(node_id, bias_pull_down) * RCAR_PIN_PULL_DOWN | \
DT_PROP(node_id, bias_disable) * RCAR_PIN_PULL_DISABLE | \
RCAR_HAS_IPSR(node_id) * RCAR_PIN_FLAGS_FUNC_SET | \
RCAR_PIN_IS_FUNC_DUMMY(node_id) * RCAR_PIN_FLAGS_FUNC_DUMMY
#define RCAR_DT_PIN(node_id) \
{ \
.pin = DT_PROP_BY_IDX(node_id, pin, 0), \
.func = COND_CODE_1(RCAR_HAS_IPSR(node_id), \
(RCAR_PIN_FUNC(node_id)), {0}), \
.flags = RCAR_PIN_FLAGS(node_id), \
.drive_strength = \
COND_CODE_1(DT_NODE_HAS_PROP(node_id, drive_strength), \
(DT_PROP(node_id, drive_strength)), (0)), \
.voltage = COND_CODE_1(DT_NODE_HAS_PROP(node_id, \
power_source), \
(DT_PROP(node_id, power_source)), \
(PIN_VOLTAGE_NONE)), \
},
/**
* @brief Utility macro to initialize each pin.
*
* @param node_id Node identifier.
* @param state_prop State property name.
* @param idx State property entry index.
*/
#define Z_PINCTRL_STATE_PIN_INIT(node_id, state_prop, idx) \
RCAR_DT_PIN(DT_PROP_BY_IDX(node_id, state_prop, idx))
/**
* @brief Utility macro to initialize state pins contained in a given property.
*
* @param node_id Node identifier.
* @param prop Property name describing state pins.
*/
#define Z_PINCTRL_STATE_PINS_INIT(node_id, prop) \
{ DT_FOREACH_PROP_ELEM(node_id, prop, Z_PINCTRL_STATE_PIN_INIT) }
struct pfc_drive_reg_field {
uint16_t pin;
uint8_t offset;
uint8_t size;
};
struct pfc_drive_reg {
uint32_t reg;
const struct pfc_drive_reg_field fields[8];
};
struct pfc_bias_reg {
uint32_t puen; /** Pull-enable or pull-up control register */
uint32_t pud; /** Pull-up/down or pull-down control register */
const uint16_t pins[32];
};
/**
* @brief Utility macro to check if a pin is GPIO capable
*
* @param pin
* @return true if pin is GPIO capable false otherwise
*/
#define RCAR_IS_GP_PIN(pin) (pin < PIN_NOGPSR_START)
#endif /* ZEPHYR_SOC_ARM_RENESAS_RCAR_COMMON_PINCTRL_SOC_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/pinctrl/pinctrl_rcar_common.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,207 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_PINCTRL_PINCTRL_ESP32_COMMON_H_
#define ZEPHYR_INCLUDE_DRIVERS_PINCTRL_PINCTRL_ESP32_COMMON_H_
#define ESP32_PORT_IDX(_pin) \
(((_pin) < 32) ? 0 : 1)
#define ESP32_PIN_NUM(_mux) \
(((_mux) >> ESP32_PIN_NUM_SHIFT) & ESP32_PIN_NUM_MASK)
#define ESP32_PIN_SIGI(_mux) \
(((_mux) >> ESP32_PIN_SIGI_SHIFT) & ESP32_PIN_SIGI_MASK)
#define ESP32_PIN_SIGO(_mux) \
(((_mux) >> ESP32_PIN_SIGO_SHIFT) & ESP32_PIN_SIGO_MASK)
#define ESP32_PIN_BIAS(_cfg) \
(((_cfg) >> ESP32_PIN_BIAS_SHIFT) & ESP32_PIN_BIAS_MASK)
#define ESP32_PIN_DRV(_cfg) \
(((_cfg) >> ESP32_PIN_DRV_SHIFT) & ESP32_PIN_DRV_MASK)
#define ESP32_PIN_MODE_OUT(_cfg) \
(((_cfg) >> ESP32_PIN_OUT_SHIFT) & ESP32_PIN_OUT_MASK)
#define ESP32_PIN_EN_DIR(_cfg) \
(((_cfg) >> ESP32_PIN_EN_DIR_SHIFT) & ESP32_PIN_EN_DIR_MASK)
#endif /* ZEPHYR_INCLUDE_DRIVERS_PINCTRL_PINCTRL_ESP32_COMMON_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/pinctrl/pinctrl_esp32_common.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 294 |
```objective-c
/*
*
*/
/**
* @file
* Atmel SAM SoC specific helpers for pinctrl driver
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_PINCTRL_PINCTRL_SOC_SAM_COMMON_H_
#define ZEPHYR_INCLUDE_DRIVERS_PINCTRL_PINCTRL_SOC_SAM_COMMON_H_
#include <zephyr/devicetree.h>
#include <zephyr/types.h>
#include <dt-bindings/pinctrl/atmel_sam_pinctrl.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @cond INTERNAL_HIDDEN */
/** @brief Type for SAM pin.
*
* Bits:
* - 0-15: SAM pinmux bit field (@ref SAM_PINMUX).
* - 16-21: Pin flags bit field (@ref SAM_PINFLAGS).
* - 22-31: Reserved.
*/
typedef uint32_t pinctrl_soc_pin_t;
/**
* @brief Utility macro to initialize each pin.
*
* @param node_id Node identifier.
* @param prop Property name.
* @param idx Property entry index.
*/
#if defined(CONFIG_SOC_FAMILY_ATMEL_SAM)
#define Z_PINCTRL_STATE_PIN_INIT(node_id, prop, idx) \
((DT_PROP_BY_IDX(node_id, prop, idx) << SAM_PINCTRL_PINMUX_POS) \
| (DT_PROP(node_id, bias_pull_up) << SAM_PINCTRL_PULLUP_POS) \
| (DT_PROP(node_id, bias_pull_down) << SAM_PINCTRL_PULLDOWN_POS) \
| (DT_PROP(node_id, drive_open_drain) << SAM_PINCTRL_OPENDRAIN_POS) \
),
#else /* CONFIG_SOC_FAMILY_ATMEL_SAM0 */
#define Z_PINCTRL_STATE_PIN_INIT(node_id, prop, idx) \
((DT_PROP_BY_IDX(node_id, prop, idx) << SAM_PINCTRL_PINMUX_POS) \
| (DT_PROP(node_id, bias_pull_up) << SAM_PINCTRL_PULLUP_POS) \
| (DT_PROP(node_id, bias_pull_down) << SAM_PINCTRL_PULLDOWN_POS) \
| (DT_PROP(node_id, input_enable) << SAM_PINCTRL_INPUTENABLE_POS) \
| (DT_PROP(node_id, output_enable) << SAM_PINCTRL_OUTPUTENABLE_POS) \
| (DT_ENUM_IDX(node_id, drive_strength) << SAM_PINCTRL_DRIVESTRENGTH_POS)\
),
#endif
/**
* @brief Utility macro to initialize state pins contained in a given property.
*
* @param node_id Node identifier.
* @param prop Property name describing state pins.
*/
#define Z_PINCTRL_STATE_PINS_INIT(node_id, prop) \
{DT_FOREACH_CHILD_VARGS(DT_PHANDLE(node_id, prop), \
DT_FOREACH_PROP_ELEM, pinmux, \
Z_PINCTRL_STATE_PIN_INIT)}
/** @endcond */
/**
* @brief Pin flags/attributes
* @anchor SAM_PINFLAGS
*
* @{
*/
#define SAM_PINCTRL_FLAGS_DEFAULT (0U)
#define SAM_PINCTRL_FLAGS_POS (0U)
#define SAM_PINCTRL_FLAGS_MASK (0x3F << SAM_PINCTRL_FLAGS_POS)
#define SAM_PINCTRL_FLAG_MASK (1U)
#define SAM_PINCTRL_PULLUP_POS (SAM_PINCTRL_FLAGS_POS)
#define SAM_PINCTRL_PULLUP (1U << SAM_PINCTRL_PULLUP_POS)
#define SAM_PINCTRL_PULLDOWN_POS (SAM_PINCTRL_PULLUP_POS + 1U)
#define SAM_PINCTRL_PULLDOWN (1U << SAM_PINCTRL_PULLDOWN_POS)
#define SAM_PINCTRL_OPENDRAIN_POS (SAM_PINCTRL_PULLDOWN_POS + 1U)
#define SAM_PINCTRL_OPENDRAIN (1U << SAM_PINCTRL_OPENDRAIN_POS)
#define SAM_PINCTRL_INPUTENABLE_POS (SAM_PINCTRL_OPENDRAIN_POS + 1U)
#define SAM_PINCTRL_INPUTENABLE (1U << SAM_PINCTRL_INPUTENABLE_POS)
#define SAM_PINCTRL_OUTPUTENABLE_POS (SAM_PINCTRL_INPUTENABLE_POS + 1U)
#define SAM_PINCTRL_OUTPUTENABLE (1U << SAM_PINCTRL_OUTPUTENABLE_POS)
#define SAM_PINCTRL_DRIVESTRENGTH_POS (SAM_PINCTRL_OUTPUTENABLE_POS + 1U)
#define SAM_PINCTRL_DRIVESTRENGTH (1U << SAM_PINCTRL_DRIVESTRENGTH_POS)
/** @} */
/**
* Obtain Flag value from pinctrl_soc_pin_t configuration.
*
* @param pincfg pinctrl_soc_pin_t bit field value.
* @param pos attribute/flags bit position (@ref SAM_PINFLAGS).
*/
#define SAM_PINCTRL_FLAG_GET(pincfg, pos) \
(((pincfg) >> pos) & SAM_PINCTRL_FLAG_MASK)
#define SAM_PINCTRL_FLAGS_GET(pincfg) \
(((pincfg) >> SAM_PINCTRL_FLAGS_POS) & SAM_PINCTRL_FLAGS_MASK)
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_PINCTRL_PINCTRL_SOC_SAM_COMMON_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/pinctrl/pinctrl_soc_sam_common.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,053 |
```objective-c
/*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_HAPTICS_DRV2605_H_
#define ZEPHYR_INCLUDE_DRIVERS_HAPTICS_DRV2605_H_
#include <zephyr/drivers/haptics.h>
#include <zephyr/types.h>
#define DRV2605_WAVEFORM_SEQUENCER_MAX 8
enum drv2605_library {
DRV2605_LIBRARY_EMPTY = 0,
DRV2605_LIBRARY_TS2200_A,
DRV2605_LIBRARY_TS2200_B,
DRV2605_LIBRARY_TS2200_C,
DRV2605_LIBRARY_TS2200_D,
DRV2605_LIBRARY_TS2200_E,
DRV2605_LIBRARY_LRA,
};
enum drv2605_mode {
DRV2605_MODE_INTERNAL_TRIGGER = 0,
DRV2605_MODE_EXTERNAL_EDGE_TRIGGER,
DRV2605_MODE_EXTERNAL_LEVEL_TRIGGER,
DRV2605_MODE_PWM_ANALOG_INPUT,
DRV2605_MODE_AUDIO_TO_VIBE,
DRV2605_MODE_RTP,
DRV2605_MODE_DIAGNOSTICS,
DRV2605_MODE_AUTO_CAL,
};
/**
* @brief DRV2605 haptic driver signal sources
*/
enum drv2605_haptics_source {
/** The playback source is device ROM */
DRV2605_HAPTICS_SOURCE_ROM,
/** The playback source is the RTP buffer */
DRV2605_HAPTICS_SOURCE_RTP,
/** The playback source is audio */
DRV2605_HAPTICS_SOURCE_AUDIO,
/** The playback source is a PWM signal */
DRV2605_HAPTICS_SOURCE_PWM,
/** The playback source is an analog signal */
DRV2605_HAPTICS_SOURCE_ANALOG,
};
struct drv2605_rom_data {
enum drv2605_mode trigger;
enum drv2605_library library;
uint8_t seq_regs[DRV2605_WAVEFORM_SEQUENCER_MAX];
uint8_t overdrive_time;
uint8_t sustain_pos_time;
uint8_t sustain_neg_time;
uint8_t brake_time;
};
struct drv2605_rtp_data {
size_t size;
uint32_t *rtp_hold_us;
uint8_t *rtp_input;
};
union drv2605_config_data {
struct drv2605_rom_data *rom_data;
struct drv2605_rtp_data *rtp_data;
};
/**
* @brief Configure the DRV2605 device for a particular signal source
*
* @param dev Pointer to the device structure for haptic device instance
* @param source The type of haptic signal source desired
* @param config_data Pointer to the configuration data union for the source
*
* @retval 0 if successful
* @retval -ENOTSUP if the signal source is not supported
* @retval <0 if failed
*/
int drv2605_haptic_config(const struct device *dev, enum drv2605_haptics_source source,
const union drv2605_config_data *config_data);
#endif
``` | /content/code_sandbox/include/zephyr/drivers/haptics/drv2605.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 606 |
```objective-c
/*
*
*/
/**
* @file
* @brief Real-time clock control based on the MCUX IMX SNVS counter API.
*
* The core Zephyr API to this device is as a counter.
*
* Additional implementation details a user should take into account:
* * an optional SRTC can be enabled (default) with configuration
* options
* * the high power channel (id 0) is always available, the low power
* channel (id 1) is optional
* * the low power alarm can be used to assert a wake-up
* * the counter has a fixed 1Hz period
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_RTC_MCUX_SNVS_H_
#define ZEPHYR_INCLUDE_DRIVERS_RTC_MCUX_SNVS_H_
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @brief Set the current counter value
*
* As the counter advances at 1Hz this will usually be set to the
* current UNIX time stamp.
*
* @param dev the IMX SNVS RTC device pointer.
*
* @param ticks the new value of the internal counter
*
* @retval non-negative on success
*/
int mcux_snvs_rtc_set(const struct device *dev, uint32_t ticks);
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_RTC_MCUX_SNVS_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/rtc/mcux_snvs_rtc.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 295 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_RTC_RTC_FAKE_H_
#define ZEPHYR_INCLUDE_DRIVERS_RTC_RTC_FAKE_H_
#include <zephyr/drivers/rtc.h>
#include <zephyr/fff.h>
#ifdef __cplusplus
extern "C" {
#endif
DECLARE_FAKE_VALUE_FUNC(int, rtc_fake_set_time, const struct device *, const struct rtc_time *);
DECLARE_FAKE_VALUE_FUNC(int, rtc_fake_get_time, const struct device *, struct rtc_time *);
#ifdef CONFIG_RTC_ALARM
DECLARE_FAKE_VALUE_FUNC(int, rtc_fake_alarm_get_supported_fields, const struct device *, uint16_t,
uint16_t *);
DECLARE_FAKE_VALUE_FUNC(int, rtc_fake_alarm_set_time, const struct device *, uint16_t, uint16_t,
const struct rtc_time *);
DECLARE_FAKE_VALUE_FUNC(int, rtc_fake_alarm_get_time, const struct device *, uint16_t, uint16_t *,
struct rtc_time *);
DECLARE_FAKE_VALUE_FUNC(int, rtc_fake_alarm_is_pending, const struct device *, uint16_t);
DECLARE_FAKE_VALUE_FUNC(int, rtc_fake_alarm_set_callback, const struct device *, uint16_t,
rtc_alarm_callback, void *);
#endif /* CONFIG_RTC_ALARM */
#ifdef CONFIG_RTC_UPDATE
DECLARE_FAKE_VALUE_FUNC(int, rtc_fake_update_set_callback, const struct device *,
rtc_update_callback, void *);
#endif /* CONFIG_RTC_UPDATE */
#ifdef CONFIG_RTC_CALIBRATION
DECLARE_FAKE_VALUE_FUNC(int, rtc_fake_set_calibration, const struct device *, int32_t);
DECLARE_FAKE_VALUE_FUNC(int, rtc_fake_get_calibration, const struct device *, int32_t *);
#endif /* CONFIG_RTC_CALIBRATION */
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_RTC_RTC_FAKE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/rtc/rtc_fake.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 366 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_RTC_MCP7940N_H_
#define ZEPHYR_INCLUDE_DRIVERS_RTC_MCP7940N_H_
#include <zephyr/sys/timeutil.h>
#include <time.h>
struct mcp7940n_rtc_sec {
uint8_t sec_one : 4;
uint8_t sec_ten : 3;
uint8_t start_osc : 1;
} __packed;
struct mcp7940n_rtc_min {
uint8_t min_one : 4;
uint8_t min_ten : 3;
uint8_t nimp : 1;
} __packed;
struct mcp7940n_rtc_hours {
uint8_t hr_one : 4;
uint8_t hr_ten : 2;
uint8_t twelve_hr : 1;
uint8_t nimp : 1;
} __packed;
struct mcp7940n_rtc_weekday {
uint8_t weekday : 3;
uint8_t vbaten : 1;
uint8_t pwrfail : 1;
uint8_t oscrun : 1;
uint8_t nimp : 2;
} __packed;
struct mcp7940n_rtc_date {
uint8_t date_one : 4;
uint8_t date_ten : 2;
uint8_t nimp : 2;
} __packed;
struct mcp7940n_rtc_month {
uint8_t month_one : 4;
uint8_t month_ten : 1;
uint8_t lpyr : 1;
uint8_t nimp : 2;
} __packed;
struct mcp7940n_rtc_year {
uint8_t year_one : 4;
uint8_t year_ten : 4;
} __packed;
struct mcp7940n_rtc_control {
uint8_t sqwfs : 2;
uint8_t crs_trim : 1;
uint8_t ext_osc : 1;
uint8_t alm0_en : 1;
uint8_t alm1_en : 1;
uint8_t sqw_en : 1;
uint8_t out : 1;
} __packed;
struct mcp7940n_rtc_osctrim {
uint8_t trim_val : 7;
uint8_t sign : 1;
} __packed;
struct mcp7940n_alm_sec {
uint8_t sec_one : 4;
uint8_t sec_ten : 3;
uint8_t nimp : 1;
} __packed;
struct mcp7940n_alm_min {
uint8_t min_one : 4;
uint8_t min_ten : 3;
uint8_t nimp : 1;
} __packed;
struct mcp7940n_alm_hours {
uint8_t hr_one : 4;
uint8_t hr_ten : 2;
uint8_t twelve_hr : 1;
uint8_t nimp : 1;
} __packed;
struct mcp7940n_alm_weekday {
uint8_t weekday : 3;
uint8_t alm_if : 1;
uint8_t alm_msk : 3;
uint8_t alm_pol : 1;
} __packed;
struct mcp7940n_alm_date {
uint8_t date_one : 4;
uint8_t date_ten : 2;
uint8_t nimp : 2;
} __packed;
struct mcp7940n_alm_month {
uint8_t month_one : 4;
uint8_t month_ten : 1;
uint8_t nimp : 3;
} __packed;
struct mcp7940n_time_registers {
struct mcp7940n_rtc_sec rtc_sec;
struct mcp7940n_rtc_min rtc_min;
struct mcp7940n_rtc_hours rtc_hours;
struct mcp7940n_rtc_weekday rtc_weekday;
struct mcp7940n_rtc_date rtc_date;
struct mcp7940n_rtc_month rtc_month;
struct mcp7940n_rtc_year rtc_year;
struct mcp7940n_rtc_control rtc_control;
struct mcp7940n_rtc_osctrim rtc_osctrim;
} __packed;
struct mcp7940n_alarm_registers {
struct mcp7940n_alm_sec alm_sec;
struct mcp7940n_alm_min alm_min;
struct mcp7940n_alm_hours alm_hours;
struct mcp7940n_alm_weekday alm_weekday;
struct mcp7940n_alm_date alm_date;
struct mcp7940n_alm_month alm_month;
} __packed;
enum mcp7940n_register {
REG_RTC_SEC = 0x0,
REG_RTC_MIN = 0x1,
REG_RTC_HOUR = 0x2,
REG_RTC_WDAY = 0x3,
REG_RTC_DATE = 0x4,
REG_RTC_MONTH = 0x5,
REG_RTC_YEAR = 0x6,
REG_RTC_CONTROL = 0x7,
REG_RTC_OSCTRIM = 0x8,
/* 0x9 not implemented */
REG_ALM0_SEC = 0xA,
REG_ALM0_MIN = 0xB,
REG_ALM0_HOUR = 0xC,
REG_ALM0_WDAY = 0xD,
REG_ALM0_DATE = 0xE,
REG_ALM0_MONTH = 0xF,
/* 0x10 not implemented */
REG_ALM1_SEC = 0x11,
REG_ALM1_MIN = 0x12,
REG_ALM1_HOUR = 0x13,
REG_ALM1_WDAY = 0x14,
REG_ALM1_DATE = 0x15,
REG_ALM1_MONTH = 0x16,
/* 0x17 not implemented */
REG_PWR_DWN_MIN = 0x18,
REG_PWR_DWN_HOUR = 0x19,
REG_PWR_DWN_DATE = 0x1A,
REG_PWR_DWN_MONTH = 0x1B,
REG_PWR_UP_MIN = 0x1C,
REG_PWR_UP_HOUR = 0x1D,
REG_PWR_UP_DATE = 0x1E,
REG_PWR_UP_MONTH = 0x1F,
SRAM_MIN = 0x20,
SRAM_MAX = 0x5F,
REG_INVAL = 0x60,
};
/* Mutually exclusive alarm trigger settings */
enum mcp7940n_alarm_trigger {
MCP7940N_ALARM_TRIGGER_SECONDS = 0x0,
MCP7940N_ALARM_TRIGGER_MINUTES = 0x1,
MCP7940N_ALARM_TRIGGER_HOURS = 0x2,
MCP7940N_ALARM_TRIGGER_WDAY = 0x3,
MCP7940N_ALARM_TRIGGER_DATE = 0x4,
/* TRIGGER_ALL matches seconds, minutes, hours, weekday, date and month */
MCP7940N_ALARM_TRIGGER_ALL = 0x7,
};
/** @brief Set the RTC to a given Unix time
*
* The RTC advances one tick per second with no access to sub-second
* precision. This function will convert the given unix_time into seconds,
* minutes, hours, day of the week, day of the month, month and year.
* A Unix time of '0' means a timestamp of 00:00:00 UTC on Thursday 1st January
* 1970.
*
* @param dev the MCP7940N device pointer.
* @param unix_time Unix time to set the rtc to.
*
* @retval return 0 on success, or a negative error code from an I2C
* transaction or invalid parameter.
*/
int mcp7940n_rtc_set_time(const struct device *dev, time_t unix_time);
#endif /* ZEPHYR_INCLUDE_DRIVERS_RTC_MCP7940N_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/rtc/mcp7940n.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,702 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CONSOLE_CONSOLE_H_
#define ZEPHYR_INCLUDE_DRIVERS_CONSOLE_CONSOLE_H_
#ifdef __cplusplus
extern "C" {
#endif
#define CONSOLE_MAX_LINE_LEN CONFIG_CONSOLE_INPUT_MAX_LINE_LEN
/** @brief Console input representation
*
* This struct is used to represent an input line from a console.
* Recorded line must be NULL terminated.
*/
struct console_input {
/** FIFO uses first word itself, reserve space */
intptr_t _unused;
/** Whether this is an mcumgr command */
uint8_t is_mcumgr : 1;
/** Buffer where the input line is recorded */
char line[CONSOLE_MAX_LINE_LEN];
};
/** @brief Console input processing handler signature
*
* Input processing is started when string is typed in the console.
* Carriage return is translated to NULL making string always NULL
* terminated. Application before calling register function need to
* initialize two fifo queues mentioned below.
*
* @param avail k_fifo queue keeping available input slots
* @param lines k_fifo queue of entered lines which to be processed
* in the application code.
* @param completion callback for tab completion of entered commands
*/
typedef void (*console_input_fn)(struct k_fifo *avail, struct k_fifo *lines,
uint8_t (*completion)(char *str, uint8_t len));
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_CONSOLE_CONSOLE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/console/console.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 312 |
```objective-c
/* uart_console.h - uart console driver */
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CONSOLE_UART_CONSOLE_H_
#define ZEPHYR_INCLUDE_DRIVERS_CONSOLE_UART_CONSOLE_H_
#include <zephyr/kernel.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @brief Register uart input processing
*
* Input processing is started when string is typed in the console.
* Carriage return is translated to NULL making string always NULL
* terminated. Application before calling register function need to
* initialize two fifo queues mentioned below.
*
* @param avail k_fifo queue keeping available input slots
* @param lines k_fifo queue of entered lines which to be processed
* in the application code.
* @param completion callback for tab completion of entered commands
*/
void uart_register_input(struct k_fifo *avail, struct k_fifo *lines,
uint8_t (*completion)(char *str, uint8_t len));
/*
* Allows having debug hooks in the console driver for handling incoming
* control characters, and letting other ones through.
*/
#ifdef CONFIG_UART_CONSOLE_DEBUG_SERVER_HOOKS
#define UART_CONSOLE_DEBUG_HOOK_HANDLED 1
#define UART_CONSOLE_OUT_DEBUG_HOOK_SIG(x) int(x)(char c)
typedef UART_CONSOLE_OUT_DEBUG_HOOK_SIG(uart_console_out_debug_hook_t);
void uart_console_out_debug_hook_install(
uart_console_out_debug_hook_t *hook);
typedef int (*uart_console_in_debug_hook_t) (uint8_t);
void uart_console_in_debug_hook_install(uart_console_in_debug_hook_t hook);
#endif
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_CONSOLE_UART_CONSOLE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/console/uart_console.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 347 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CONSOLE_NATIVE_POSIX_CONSOLE_H_
#define ZEPHYR_INCLUDE_DRIVERS_CONSOLE_NATIVE_POSIX_CONSOLE_H_
/*
* This header is left for compatibility with old applications
* The console for native_posix is now provided by the posix_arch_console driver
*/
#include <posix_arch_console.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_CONSOLE_NATIVE_POSIX_CONSOLE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/console/native_posix_console.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 88 |
```objective-c
/* ipm_console.c - Console messages to/from another processor */
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CONSOLE_IPM_CONSOLE_H_
#define ZEPHYR_INCLUDE_DRIVERS_CONSOLE_IPM_CONSOLE_H_
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/sys/ring_buffer.h>
#ifdef __cplusplus
extern "C" {
#endif
#define IPM_CONSOLE_STDOUT (BIT(0))
#define IPM_CONSOLE_PRINTK (BIT(1))
/*
* Good way to determine these numbers other than trial-and-error?
* using printf() in the thread seems to require a lot more stack space
*/
#define IPM_CONSOLE_STACK_SIZE CONFIG_IPM_CONSOLE_STACK_SIZE
#define IPM_CONSOLE_PRI 2
struct ipm_console_receiver_config_info {
/** Name of the low-level IPM driver to bind to */
char *bind_to;
/**
* Stack for the receiver's thread, which prints out messages as
* they come in. Should be sized CONFIG_IPM_CONSOLE_STACK_SIZE
*/
k_thread_stack_t *thread_stack;
/**
* Ring buffer data area for stashing characters from the interrupt
* callback
*/
uint32_t *ring_buf_data;
/** Size of ring_buf_data in 32-bit chunks */
unsigned int rb_size32;
/**
* Line buffer for incoming messages, characters accumulate here
* and then are sent to printk() once full (including a trailing NULL)
* or a carriage return seen
*/
char *line_buf;
/** Size in bytes of the line buffer. Must be at least 2 */
unsigned int lb_size;
/**
* Destination for received console messages, one of
* IPM_CONSOLE_STDOUT or IPM_CONSOLE_PRINTK
*/
unsigned int flags;
};
struct ipm_console_receiver_runtime_data {
/** Buffer for received bytes from the low-level IPM device */
struct ring_buf rb;
/** Semaphore to wake up the thread to print out messages */
struct k_sem sem;
/** pointer to the bound low-level IPM device */
const struct device *ipm_device;
/** Indicator that the channel is temporarily disabled due to
* full buffer
*/
int channel_disabled;
/** Receiver worker thread */
struct k_thread rx_thread;
};
struct ipm_console_sender_config_info {
/** Name of the low-level driver to bind to */
char *bind_to;
/**
* Source of messages to forward, hooks will be installed.
* Can be IPM_CONSOLE_STDOUT, IPM_CONSOLE_PRINTK, or both
*/
int flags;
};
#if CONFIG_IPM_CONSOLE_RECEIVER
int ipm_console_receiver_init(const struct device *d);
#endif
#if CONFIG_IPM_CONSOLE_SENDER
int ipm_console_sender_init(const struct device *d);
#endif
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_CONSOLE_IPM_CONSOLE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/console/ipm_console.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 616 |
```objective-c
/*
*
*/
/** @file
* @brief A driver for sending and receiving mcumgr packets over UART.
*
* @see include/mgmt/serial.h
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CONSOLE_UART_MCUMGR_H_
#define ZEPHYR_INCLUDE_DRIVERS_CONSOLE_UART_MCUMGR_H_
#include <stdlib.h>
#include <zephyr/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Contains an mcumgr fragment received over UART.
*/
struct uart_mcumgr_rx_buf {
void *fifo_reserved; /* 1st word reserved for use by fifo */
uint8_t data[CONFIG_UART_MCUMGR_RX_BUF_SIZE];
int length;
};
/** @typedef uart_mcumgr_recv_fn
* @brief Function that gets called when an mcumgr packet is received.
*
* Function that gets called when an mcumgr packet is received. This function
* gets called in the interrupt context. Ownership of the specified buffer is
* transferred to the callback when this function gets called.
*
* @param rx_buf A buffer containing the incoming mcumgr packet.
*/
typedef void uart_mcumgr_recv_fn(struct uart_mcumgr_rx_buf *rx_buf);
/**
* @brief Sends an mcumgr packet over UART.
*
* @param data Buffer containing the mcumgr packet to send.
* @param len The length of the buffer, in bytes.
*
* @return 0 on success; negative error code on failure.
*/
int uart_mcumgr_send(const uint8_t *data, int len);
/**
* @brief Frees the supplied receive buffer.
*
* @param rx_buf The buffer to free.
*/
void uart_mcumgr_free_rx_buf(struct uart_mcumgr_rx_buf *rx_buf);
/**
* @brief Registers an mcumgr UART receive handler.
*
* Configures the mcumgr UART driver to call the specified function when an
* mcumgr request packet is received.
*
* @param cb The callback to execute when an mcumgr request
* packet is received.
*/
void uart_mcumgr_register(uart_mcumgr_recv_fn *cb);
#ifdef __cplusplus
}
#endif
#endif
``` | /content/code_sandbox/include/zephyr/drivers/console/uart_mcumgr.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 465 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CONSOLE_POSIX_ARCH_CONSOLE_H_
#define ZEPHYR_INCLUDE_DRIVERS_CONSOLE_POSIX_ARCH_CONSOLE_H_
#include <zephyr/kernel.h>
#ifdef __cplusplus
extern "C" {
#endif
void posix_flush_stdout(void);
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_CONSOLE_POSIX_ARCH_CONSOLE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/console/posix_arch_console.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 83 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_SIP_SVC_AGILEX_MB_H_
#define ZEPHYR_INCLUDE_SIP_SVC_AGILEX_MB_H_
/**
* @file
* @brief Intel SoC FPGA Agilex customized SDM Mailbox communication
* protocol handler. SDM Mailbox protocol will be embedded in
* Arm SiP Services SMC protocol and sent to/from SDM via Arm
* SiP Services.
*/
#define SIP_SVP_MB_MAX_WORD_SIZE 1024
#define SIP_SVP_MB_HEADER_TRANS_ID_OFFSET 24
#define SIP_SVP_MB_HEADER_TRANS_ID_MASK 0xFF
#define SIP_SVP_MB_HEADER_LENGTH_OFFSET 12
#define SIP_SVP_MB_HEADER_LENGTH_MASK 0x7FF
#define SIP_SVC_MB_HEADER_GET_CLIENT_ID(header) \
((header) >> SIP_SVP_MB_HEADER_CLIENT_ID_OFFSET & \
SIP_SVP_MB_HEADER_CLIENT_ID_MASK)
#define SIP_SVC_MB_HEADER_GET_TRANS_ID(header) \
((header) >> SIP_SVP_MB_HEADER_TRANS_ID_OFFSET & \
SIP_SVP_MB_HEADER_TRANS_ID_MASK)
#define SIP_SVC_MB_HEADER_SET_TRANS_ID(header, id) \
(header) &= ~(SIP_SVP_MB_HEADER_TRANS_ID_MASK << \
SIP_SVP_MB_HEADER_TRANS_ID_OFFSET); \
(header) |= (((id) & SIP_SVP_MB_HEADER_TRANS_ID_MASK) << \
SIP_SVP_MB_HEADER_TRANS_ID_OFFSET);
#define SIP_SVC_MB_HEADER_GET_LENGTH(header) \
((header) >> SIP_SVP_MB_HEADER_LENGTH_OFFSET & \
SIP_SVP_MB_HEADER_LENGTH_MASK)
#endif /* ZEPHYR_INCLUDE_SIP_SVC_AGILEX_MB_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/sip_svc/sip_svc_agilex_mailbox.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 364 |
```objective-c
/*
*
*/
/**
* @file
* @brief Real-time clock control based on the DS3231 counter API.
*
* The [Maxim
* DS3231](path_to_url
* is a high-precision real-time clock with temperature-compensated
* crystal oscillator and support for configurable alarms.
*
* The core Zephyr API to this device is as a counter, with the
* following limitations:
* * ``counter_read()`` and ``counter_*_alarm()`` cannot be invoked from
* interrupt context, as they require communication with the device
* over an I2C bus.
* * many other counter APIs, such as start/stop/set_top_value are not
* supported as the clock is always running.
* * two alarm channels are supported but are not equally capable:
* channel 0 supports alarms at 1 s resolution, while channel 1
* supports alarms at 1 minute resolution.
*
* Most applications for this device will need to use the extended
* functionality exposed by this header to access the real-time-clock
* features. The majority of these functions must be invoked from
* supervisor mode.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_RTC_DS3231_H_
#define ZEPHYR_INCLUDE_DRIVERS_RTC_DS3231_H_
#include <time.h>
#include <zephyr/drivers/counter.h>
#include <zephyr/kernel.h>
#include <zephyr/types.h>
#include <zephyr/sys/notify.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @brief Bit in ctrl or ctrl_stat associated with alarm 1. */
#define MAXIM_DS3231_ALARM1 BIT(0)
/** @brief Bit in ctrl or ctrl_stat associated with alarm 2. */
#define MAXIM_DS3231_ALARM2 BIT(1)
/* Constants corresponding to bits in the DS3231 control register at
* 0x0E.
*
* See the datasheet for interpretation of these bits.
*/
/** @brief ctrl bit for alarm 1 interrupt enable. */
#define MAXIM_DS3231_REG_CTRL_A1IE MAXIM_DS3231_ALARM1
/** @brief ctrl bit for alarm 2 interrupt enable. */
#define MAXIM_DS3231_REG_CTRL_A2IE MAXIM_DS3231_ALARM2
/** @brief ctrl bit for ISQ functionality.
*
* When clear the ISW signal provides a square wave. When set the ISW
* signal indicates alarm events.
*
* @note The driver expects to be able to control this bit.
*/
#define MAXIM_DS3231_REG_CTRL_INTCN BIT(2)
/** @brief ctrl bit offset for square wave output frequency.
*
* @note The driver will control the content of this field.
*/
#define MAXIM_DS3231_REG_CTRL_RS_Pos 3
/** @brief ctrl mask to isolate RS bits. */
#define MAXIM_DS3231_REG_CTRL_RS_Msk (0x03 << MAXIM_DS3231_REG_CTRL_RS_Pos)
/** @brief ctrl RS field value for 1 Hz square wave. */
#define MAXIM_DS3231_REG_CTRL_RS_1Hz 0x00
/** @brief ctrl RS field value for 1024 Hz square wave. */
#define MAXIM_DS3231_REG_CTRL_RS_1KiHz 0x01
/** @brief ctrl RS field value for 4096 Hz square wave. */
#define MAXIM_DS3231_REG_CTRL_RS_4KiHz 0x02
/** @brief ctrl RS field value for 8192 Hz square wave. */
#define MAXIM_DS3231_REG_CTRL_RS_8KiHz 0x03
/** @brief ctrl bit to write to trigger temperature conversion. */
#define MAXIM_DS3231_REG_CTRL_CONV BIT(5)
/** @brief ctrl bit to write to enable square wave output in battery mode. */
#define MAXIM_DS3231_REG_CTRL_BBSQW BIT(6)
/** @brief ctrl bit to write to disable the oscillator. */
#define MAXIM_DS3231_REG_CTRL_EOSCn BIT(7),
/** @brief ctrl_stat bit indicating alarm1 has triggered.
*
* If an alarm callback handler is registered this bit is
* cleared prior to invoking the callback with the flags
* indicating which alarms are ready.
*/
#define MAXIM_DS3231_REG_STAT_A1F MAXIM_DS3231_ALARM1
/** @brief ctrl_stat bit indicating alarm2 has triggered.
*
* If an alarm callback handler is registered this bit is
* cleared prior to invoking the callback with the flags
* indicating which alarms are ready.
*/
#define MAXIM_DS3231_REG_STAT_A2F MAXIM_DS3231_ALARM2
/** @brief Flag indicating a temperature conversion is in progress. */
#define MAXIM_DS3231_REG_STAT_BSY BIT(2)
/** @brief Set to enable 32 KiHz open drain signal.
*
* @note This is a control bit, though it is positioned within the
* ctrl_stat register which otherwise contains status bits.
*/
#define MAXIM_DS3231_REG_STAT_EN32kHz BIT(3)
/** @brief Flag indicating the oscillator has been off since last cleared. */
#define MAXIM_DS3231_REG_STAT_OSF BIT(7)
/** @brief Control alarm behavior on match in seconds field.
*
* If clear the alarm fires only when the RTC seconds matches the
* alarm seconds.
*
* If set the alarm seconds field is ignored and an alarm will be
* triggered every second. The bits for IGNMN, IGNHR, and IGNDA must
* all be set.
*
* This bit must be clear for the second alarm instance.
*
* Bit maps to A1M1 and is used in
* maxim_ds3231_alarm_configuration::alarm_flags.
*/
#define MAXIM_DS3231_ALARM_FLAGS_IGNSE BIT(0)
/** @brief Control alarm behavior on match in minutes field.
*
* If clear the alarm fires only when the RTC minutes matches the
* alarm minutes. The bit for IGNSE must be clear.
*
* If set the alarm minutes field is ignored and alarms will be
* triggered based on IGNSE. The bits for IGNHR and IGNDA must both be
* set.
*
* Bit maps to A1M2 or A2M2 and is used in
* maxim_ds3231_alarm_configuration::alarm_flags.
*/
#define MAXIM_DS3231_ALARM_FLAGS_IGNMN BIT(1)
/** @brief Control alarm behavior on match in hours field.
*
* If clear the alarm fires only when the RTC hours matches the
* alarm hours. The bits for IGNMN and IGNSE must be clear.
*
* If set the alarm hours field is ignored and alarms will be
* triggered based on IGNMN and IGNSE. The bit for IGNDA must be set.
*
* Bit maps to A1M3 or A2M3 and is used in
* maxim_ds3231_alarm_configuration::alarm_flags.
*/
#define MAXIM_DS3231_ALARM_FLAGS_IGNHR BIT(2)
/** @brief Control alarm behavior on match in day/date field.
*
* If clear the alarm fires only when the RTC day/date matches the
* alarm day/date, mediated by MAXIM_DS3231_ALARM_FLAGS_DAY. The bits
* for IGNHR, IGNMN, and IGNSE must be clear
*
* If set the alarm day/date field is ignored and an alarm will be
* triggered based on IGNHR, IGNMN, and IGNSE.
*
* Bit maps to A1M4 or A2M4 and is used in
* maxim_ds3231_alarm_configuration::alarm_flags.
*/
#define MAXIM_DS3231_ALARM_FLAGS_IGNDA BIT(3)
/** @brief Control match on day of week versus day of month
*
* Set the flag to match on day of week; clear it to match on day of
* month.
*
* Bit maps to DY/DTn in corresponding
* maxim_ds3231_alarm_configuration::alarm_flags.
*/
#define MAXIM_DS3231_ALARM_FLAGS_DOW BIT(4)
/** @brief Indicates that the alarm should be disabled once it fires.
*
* Set the flag in the maxim_ds3231_alarm_configuration::alarm_flags
* field to cause the alarm to be disabled when the interrupt fires,
* prior to invoking the corresponding handler.
*
* Leave false to allow the alarm to remain enabled so it will fire
* again on the next match.
*/
#define MAXIM_DS3231_ALARM_FLAGS_AUTODISABLE BIT(7)
/**
* @brief RTC DS3231 Driver-Specific API
* @defgroup rtc_ds3231_interface RTC DS3231 Interface
* @ingroup io_interfaces
* @{
*/
/** @brief Signature for DS3231 alarm callbacks.
*
* The alarm callback is invoked from the system work queue thread.
* At the point the callback is invoked the corresponding alarm flags
* will have been cleared from the device status register. The
* callback is permitted to invoke operations on the device.
*
* @param dev the device from which the callback originated
* @param id the alarm id
* @param syncclock the value from maxim_ds3231_read_syncclock() at the
* time the alarm interrupt was processed.
* @param user_data the corresponding parameter from
* maxim_ds3231_alarm::user_data.
*/
typedef void (*maxim_ds3231_alarm_callback_handler_t)(const struct device *dev,
uint8_t id,
uint32_t syncclock,
void *user_data);
/** @brief Signature used to notify a user of the DS3231 that an
* asynchronous operation has completed.
*
* Functions compatible with this type are subject to all the
* constraints of #sys_notify_generic_callback.
*
* @param dev the DS3231 device pointer
*
* @param notify the notification structure provided in the call
*
* @param res the result of the operation.
*/
typedef void (*maxim_ds3231_notify_callback)(const struct device *dev,
struct sys_notify *notify,
int res);
/** @brief Information defining the alarm configuration.
*
* DS3231 alarms can be set to fire at specific times or at the
* rollover of minute, hour, day, or day of week.
*
* When an alarm is configured with a handler an interrupt will be
* generated and the handler called from the system work queue.
*
* When an alarm is configured without a handler, or a persisted alarm
* is present, alarms can be read using maxim_ds3231_check_alarms().
*/
struct maxim_ds3231_alarm {
/** @brief Time specification for an RTC alarm.
*
* Though specified as a UNIX time, the alarm parameters are
* determined by converting to civil time and interpreting the
* component hours, minutes, seconds, day-of-week, and
* day-of-month fields, mediated by the corresponding #flags.
*
* The year and month are ignored, but be aware that gmtime()
* determines day-of-week based on calendar date. Decoded
* alarm times will fall within 1978-01 since 1978-01-01
* (first of month) was a Sunday (first of week).
*/
time_t time;
/** @brief Handler to be invoked when alarms are signalled.
*
* If this is null the alarm will not be triggered by the
* INTn/SQW GPIO. This is a "persisted" alarm from its role
* in using the DS3231 to trigger a wake from deep sleep. The
* application should use maxim_ds3231_check_alarms() to
* determine whether such an alarm has been triggered.
*
* If this is not null the driver will monitor the ISW GPIO
* for alarm signals and will invoke the handler with a
* parameter carrying the value returned by
* maxim_ds3231_check_alarms(). The corresponding status flags
* will be cleared in the device before the handler is
* invoked.
*
* The handler will be invoked from the system work queue.
*/
maxim_ds3231_alarm_callback_handler_t handler;
/** @brief User-provided pointer passed to alarm callback. */
void *user_data;
/** @brief Flags controlling configuration of the alarm alarm.
*
* See MAXIM_DS3231_ALARM_FLAGS_IGNSE and related constants.
*
* Note that as described the alarm mask fields require that
* if a unit is not ignored, higher-precision units must also
* not be ignored. For example, if match on hours is enabled,
* match on minutes and seconds must also be enabled. Failure
* to comply with this requirement will cause
* maxim_ds3231_set_alarm() to return an error, leaving the
* alarm configuration unchanged.
*/
uint8_t flags;
};
/** @brief Register the RTC clock against system clocks.
*
* This captures the same instant in both the RTC time scale and a
* stable system clock scale, allowing conversion between those
* scales.
*/
struct maxim_ds3231_syncpoint {
/** @brief Time from the DS3231.
*
* This maybe in UTC, TAI, or local offset depending on how
* the RTC is maintained.
*/
struct timespec rtc;
/** @brief Value of a local clock at the same instant as #rtc.
*
* This is captured from a stable monotonic system clock
* running at between 1 kHz and 1 MHz, allowing for
* microsecond to millisecond accuracy in synchronization.
*/
uint32_t syncclock;
};
/** @brief Read the local synchronization clock.
*
* Synchronization aligns the DS3231 real-time clock with a stable
* monotonic local clock which should have a frequency between 1 kHz
* and 1 MHz and be itself synchronized with the primary system time
* clock. The accuracy of the alignment and the maximum time between
* synchronization updates is affected by the resolution of this
* clock.
*
* On some systems the hardware clock from k_cycles_get_32() is
* suitable, but on others that clock advances too quickly. The
* frequency of the target-specific clock is provided by
* maxim_ds3231_syncclock_frequency().
*
* At this time the value is captured from `k_uptime_get_32()`; future
* kernel extensions may make a higher-resolution clock available.
*
* @note This function is *isr-ok*.
*
* @param dev the DS3231 device pointer
*
* @return the current value of the synchronization clock.
*/
static inline uint32_t maxim_ds3231_read_syncclock(const struct device *dev)
{
return k_uptime_get_32();
}
/** @brief Get the frequency of the synchronization clock.
*
* Provides the frequency of the clock used in maxim_ds3231_read_syncclock().
*
* @param dev the DS3231 device pointer
*
* @return the frequency of the selected synchronization clock.
*/
static inline uint32_t maxim_ds3231_syncclock_frequency(const struct device *dev)
{
return 1000U;
}
/**
* @brief Set and clear specific bits in the control register.
*
* @note This function assumes the device register cache is valid. It
* will not read the register value, and it will write to the device
* only if the value changes as a result of applying the set and clear
* changes.
*
* @note Unlike maxim_ds3231_stat_update() the return value from this
* function indicates the register value after changes were made.
* That return value is cached for use in subsequent operations.
*
* @note This function is *supervisor*.
*
* @return the non-negative updated value of the register, or a
* negative error code from an I2C transaction.
*/
int maxim_ds3231_ctrl_update(const struct device *dev,
uint8_t set_bits,
uint8_t clear_bits);
/**
* @brief Read the ctrl_stat register then set and clear bits in it.
*
* The content of the ctrl_stat register will be read, then the set
* and clear bits applied and the result written back to the device
* (regardless of whether there appears to be a change in value).
*
* OSF, A1F, and A2F will be written with 1s if the corresponding bits
* do not appear in either @p set_bits or @p clear_bits. This ensures
* that if any flag becomes set between the read and the write that
* indicator will not be cleared.
*
* @note Unlike maxim_ds3231_ctrl_update() the return value from this
* function indicates the register value before any changes were made.
*
* @note This function is *supervisor*.
*
* @param dev the DS3231 device pointer
*
* @param set_bits bits to be set when writing back. Setting bits
* other than @ref MAXIM_DS3231_REG_STAT_EN32kHz will have no effect.
*
* @param clear_bits bits to be cleared when writing back. Include
* the bits for the status flags you want to clear.
*
* @return the non-negative register value as originally read
* (disregarding the effect of clears and sets), or a negative error
* code from an I2C transaction.
*/
int maxim_ds3231_stat_update(const struct device *dev,
uint8_t set_bits,
uint8_t clear_bits);
/** @brief Read a DS3231 alarm configuration.
*
* The alarm configuration data is read from the device and
* reconstructed into the output parameter.
*
* @note This function is *supervisor*.
*
* @param dev the DS3231 device pointer.
*
* @param id the alarm index, which must be 0 (for the 1 s resolution
* alarm) or 1 (for the 1 min resolution alarm).
*
* @param cfg a pointer to a structure into which the configured alarm
* data will be stored.
*
* @return a non-negative value indicating successful conversion, or a
* negative error code from an I2C transaction or invalid parameter.
*/
int maxim_ds3231_get_alarm(const struct device *dev,
uint8_t id,
struct maxim_ds3231_alarm *cfg);
/** @brief Configure a DS3231 alarm.
*
* The alarm configuration is validated and stored into the device.
*
* To cancel an alarm use counter_cancel_channel_alarm().
*
* @note This function is *supervisor*.
*
* @param dev the DS3231 device pointer.
*
* @param id 0 Analog to counter index. @c ALARM1 is 0 and has 1 s
* resolution, @c ALARM2 is 1 and has 1 minute resolution.
*
* @param cfg a pointer to the desired alarm configuration. Both
* alarms are configured; if only one is to change the application
* must supply the existing configuration for the other.
*
* @return a non-negative value on success, or a negative error code
* from an I2C transaction or an invalid parameter.
*/
int maxim_ds3231_set_alarm(const struct device *dev,
uint8_t id,
const struct maxim_ds3231_alarm *cfg);
/** @brief Synchronize the RTC against the local clock.
*
* The RTC advances one tick per second with no access to sub-second
* precision. Synchronizing clocks at sub-second resolution requires
* enabling a 1pps signal then capturing the system clocks in a GPIO
* callback. This function provides that operation.
*
* Synchronization is performed in asynchronously, and may take as
* long as 1 s to complete; notification of completion is provided
* through the @p notify parameter.
*
* Applications should use maxim_ds3231_get_syncpoint() to retrieve the
* synchronization data collected by this operation.
*
* @note This function is *supervisor*.
*
* @param dev the DS3231 device pointer.
*
* @param notify pointer to the object used to specify asynchronous
* function behavior and store completion information.
*
* @retval non-negative on success
* @retval -EBUSY if a synchronization or set is currently in progress
* @retval -EINVAL if notify is not provided
* @retval -ENOTSUP if the required interrupt is not configured
*/
int maxim_ds3231_synchronize(const struct device *dev,
struct sys_notify *notify);
/** @brief Request to update the synchronization point.
*
* This is a variant of maxim_ds3231_synchronize() for use from user
* threads.
*
* @param dev the DS3231 device pointer.
*
* @param signal pointer to a valid and ready-to-be-signalled
* k_poll_signal. May be NULL to request a synchronization point be
* collected without notifying when it has been updated.
*
* @retval non-negative on success
* @retval -EBUSY if a synchronization or set is currently in progress
* @retval -ENOTSUP if the required interrupt is not configured
*/
__syscall int maxim_ds3231_req_syncpoint(const struct device *dev,
struct k_poll_signal *signal);
/** @brief Retrieve the most recent synchronization point.
*
* This function returns the synchronization data last captured using
* maxim_ds3231_synchronize().
*
* @param dev the DS3231 device pointer.
*
* @param syncpoint where to store the synchronization data.
*
* @retval non-negative on success
* @retval -ENOENT if no syncpoint has been captured
*/
__syscall int maxim_ds3231_get_syncpoint(const struct device *dev,
struct maxim_ds3231_syncpoint *syncpoint);
/** @brief Set the RTC to a time consistent with the provided
* synchronization.
*
* The RTC advances one tick per second with no access to sub-second
* precision, and setting the clock resets the internal countdown
* chain. This function implements the magic necessary to set the
* clock while retaining as much sub-second accuracy as possible. It
* requires a synchronization point that pairs sub-second resolution
* civil time with a local synchronization clock captured at the same
* instant. The set operation may take as long as 1 second to
* complete; notification of completion is provided through the @p
* notify parameter.
*
* @note This function is *supervisor*.
*
* @param dev the DS3231 device pointer.
*
* @param syncpoint the structure providing the synchronization point.
*
* @param notify pointer to the object used to specify asynchronous
* function behavior and store completion information.
*
* @retval non-negative on success
* @retval -EINVAL if syncpoint or notify are null
* @retval -ENOTSUP if the required interrupt signal is not configured
* @retval -EBUSY if a synchronization or set is currently in progress
*/
int maxim_ds3231_set(const struct device *dev,
const struct maxim_ds3231_syncpoint *syncpoint,
struct sys_notify *notify);
/** @brief Check for and clear flags indicating that an alarm has
* fired.
*
* Returns a mask indicating alarms that are marked as having fired,
* and clears from stat the flags that it found set. Alarms that have
* been configured with a callback are not represented in the return
* value.
*
* This API may be used when a persistent alarm has been programmed.
*
* @note This function is *supervisor*.
*
* @param dev the DS3231 device pointer.
*
* @return a non-negative value that may have MAXIM_DS3231_ALARM1 and/or
* MAXIM_DS3231_ALARM2 set, or a negative error code.
*/
int maxim_ds3231_check_alarms(const struct device *dev);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
/* @todo this should be syscalls/drivers/rtc/maxim_ds3231.h */
#include <zephyr/syscalls/maxim_ds3231.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_RTC_DS3231_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/rtc/maxim_ds3231.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 5,051 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_SIP_SVC_DRIVER_H_
#define ZEPHYR_INCLUDE_SIP_SVC_DRIVER_H_
#include <zephyr/device.h>
#include <zephyr/kernel.h>
#include <zephyr/arch/arm64/arm-smccc.h>
#include <zephyr/drivers/sip_svc/sip_svc_proto.h>
#include <zephyr/sip_svc/sip_svc_controller.h>
#define DEV_API(dev) ((struct svc_driver_api *)(dev)->api)
/**
* @brief Length of SVC conduit name.
*
*/
#define SVC_CONDUIT_NAME_LENGTH (4)
/**
* @brief Callback API for executing the supervisory call
* See @a sip_supervisory_call() for argument description
*/
typedef void (*sip_supervisory_call_t)(const struct device *dev, unsigned long function_id,
unsigned long arg0, unsigned long arg1, unsigned long arg2,
unsigned long arg3, unsigned long arg4, unsigned long arg5,
unsigned long arg6, struct arm_smccc_res *res);
/**
* @brief Callback API for validating function id for the supervisory call.
* See @a sip_svc_plat_func_id_valid() for argument description
*/
typedef bool (*sip_svc_plat_func_id_valid_t)(const struct device *dev, uint32_t command,
uint32_t func_id);
/**
* @brief Callback API for generating the transaction id from client id.
* See @a sip_svc_plat_format_trans_id() for argument description
*/
typedef uint32_t (*sip_svc_plat_format_trans_id_t)(const struct device *dev, uint32_t client_idx,
uint32_t trans_idx);
/**
* @brief Callback API for retrieving client transaction id from transaction id
* See @a sip_svc_plat_get_trans_idx() for argument description
*/
typedef uint32_t (*sip_svc_plat_get_trans_idx_t)(const struct device *dev, uint32_t trans_id);
/**
* @brief Callback API for updating transaction id for request packet for lower layer
* See @a sip_svc_plat_update_trans_id() for argument description
*/
typedef void (*sip_svc_plat_update_trans_id_t)(const struct device *dev,
struct sip_svc_request *request, uint32_t trans_id);
/**
* @brief Callback API for freeing command buffer in ASYNC packets
* See @a sip_svc_plat_free_async_memory() for argument description
*/
typedef void (*sip_svc_plat_free_async_memory_t)(const struct device *dev,
struct sip_svc_request *request);
/**
* @brief Callback API to construct Polling packet for ASYNC transaction.
* See @a sip_svc_plat_async_res_req() for argument description
*/
typedef int (*sip_svc_plat_async_res_req_t)(const struct device *dev, unsigned long *a0,
unsigned long *a1, unsigned long *a2, unsigned long *a3,
unsigned long *a4, unsigned long *a5, unsigned long *a6,
unsigned long *a7, char *buf, size_t size);
/**
* @brief Callback API to check the response of polling request
* See @a sip_svc_plat_async_res_res() for argument description
*/
typedef int (*sip_svc_plat_async_res_res_t)(const struct device *dev, struct arm_smccc_res *res,
char *buf, size_t *size, uint32_t *trans_id);
/**
* @brief Callback API for retrieving error code from a supervisory call response.
* See @a sip_svc_plat_get_error_code() for argument description.
*/
typedef uint32_t (*sip_svc_plat_get_error_code_t)(const struct device *dev,
struct arm_smccc_res *res);
/**
* @brief API structure for sip_svc driver.
*
*/
__subsystem struct svc_driver_api {
sip_supervisory_call_t sip_supervisory_call;
sip_svc_plat_func_id_valid_t sip_svc_plat_func_id_valid;
sip_svc_plat_format_trans_id_t sip_svc_plat_format_trans_id;
sip_svc_plat_get_trans_idx_t sip_svc_plat_get_trans_idx;
sip_svc_plat_update_trans_id_t sip_svc_plat_update_trans_id;
sip_svc_plat_free_async_memory_t sip_svc_plat_free_async_memory;
sip_svc_plat_async_res_req_t sip_svc_plat_async_res_req;
sip_svc_plat_async_res_res_t sip_svc_plat_async_res_res;
sip_svc_plat_get_error_code_t sip_svc_plat_get_error_code;
};
/**
* @brief supervisory call function which will execute the smc/hvc call
*
* @param dev Pointer to the device structure for the driver instance.
* @param function_id Function identifier for the supervisory call.
* @param arg0 Argument 0 for supervisory call.
* @param arg1 Argument 1 for supervisory call.
* @param arg2 Argument 2 for supervisory call.
* @param arg3 Argument 3 for supervisory call.
* @param arg4 Argument 4 for supervisory call.
* @param arg5 Argument 5 for supervisory call.
* @param arg6 Argument 6 for supervisory call.
* @param res Pointer to response buffer for supervisory call.
*/
__syscall void sip_supervisory_call(const struct device *dev, unsigned long function_id,
unsigned long arg0, unsigned long arg1, unsigned long arg2,
unsigned long arg3, unsigned long arg4, unsigned long arg5,
unsigned long arg6, struct arm_smccc_res *res);
static inline void z_impl_sip_supervisory_call(const struct device *dev, unsigned long function_id,
unsigned long arg0, unsigned long arg1,
unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5,
unsigned long arg6, struct arm_smccc_res *res)
{
__ASSERT(dev, "dev shouldn't be NULL");
const struct svc_driver_api *api = DEV_API(dev);
__ASSERT(api->sip_supervisory_call, "sip_supervisory_call shouldn't be NULL");
__ASSERT(res, "response pointer shouldn't be NULL");
api->sip_supervisory_call(dev, function_id, arg0, arg1, arg2, arg3, arg4, arg5, arg6, res);
}
/**
* @brief Validate the function id for the supervisory call.
*
* @param dev Pointer to the device structure for the driver instance.
* @param command Command which specify if the call is SYNC or ASYNC.
* @param func_id Function identifier
*
* @retval true if command and function identifiers are valid.
* @retval false if command and function identifiers are invalid.
*/
__syscall bool sip_svc_plat_func_id_valid(const struct device *dev, uint32_t command,
uint32_t func_id);
static inline bool z_impl_sip_svc_plat_func_id_valid(const struct device *dev, uint32_t command,
uint32_t func_id)
{
__ASSERT(dev, "dev shouldn't be NULL");
const struct svc_driver_api *api = DEV_API(dev);
__ASSERT(api->sip_svc_plat_func_id_valid,
"sip_svc_plat_func_id_valid func shouldn't be NULL");
return api->sip_svc_plat_func_id_valid(dev, command, func_id);
}
/**
* @brief Formats and generates the transaction id from client id.
*
* @param dev Pointer to the device structure for the driver instance.
* @param client_idx client index.
* @param trans_idx transaction index.
*
* @retval transaction id, which is used for tracking each transaction.
*/
__syscall uint32_t sip_svc_plat_format_trans_id(const struct device *dev, uint32_t client_idx,
uint32_t trans_idx);
static inline uint32_t z_impl_sip_svc_plat_format_trans_id(const struct device *dev,
uint32_t client_idx, uint32_t trans_idx)
{
__ASSERT(dev, "dev shouldn't be NULL");
const struct svc_driver_api *api = DEV_API(dev);
__ASSERT(api->sip_svc_plat_format_trans_id,
"sip_svc_plat_format_trans_id func shouldn't be NULL");
return api->sip_svc_plat_format_trans_id(dev, client_idx, trans_idx);
}
/**
* @brief Retrieve client transaction id from packet transaction id.
*
* @param dev Pointer to the device structure for the driver instance.
* @param trans_id transaction identifier if for a transaction.
*
* @retval client transaction id form Transaction id.
*/
__syscall uint32_t sip_svc_plat_get_trans_idx(const struct device *dev, uint32_t trans_id);
static inline uint32_t z_impl_sip_svc_plat_get_trans_idx(const struct device *dev,
uint32_t trans_id)
{
__ASSERT(dev, "dev shouldn't be NULL");
const struct svc_driver_api *api = DEV_API(dev);
__ASSERT(api->sip_svc_plat_get_trans_idx,
"sip_svc_plat_get_trans_idx func shouldn't be NULL");
return api->sip_svc_plat_get_trans_idx(dev, trans_id);
}
/**
* @brief Update transaction id for sip_svc_request for lower layer.
*
* @param dev Pointer to the device structure for the driver instance.
* @param request Pointer to sip_svc_request structure.
* @param trans_id Transaction id.
*/
__syscall void sip_svc_plat_update_trans_id(const struct device *dev,
struct sip_svc_request *request, uint32_t trans_id);
static inline void z_impl_sip_svc_plat_update_trans_id(const struct device *dev,
struct sip_svc_request *request,
uint32_t trans_id)
{
__ASSERT(dev, "dev shouldn't be NULL");
const struct svc_driver_api *api = DEV_API(dev);
__ASSERT(api->sip_svc_plat_update_trans_id,
"sip_svc_plat_update_trans_id func shouldn't be NULL");
__ASSERT(request, "request shouldn't be NULL");
return api->sip_svc_plat_update_trans_id(dev, request, trans_id);
}
/**
* @brief Retrieve the error code from arm_smccc_res response.
*
* @param dev Pointer to the device structure for the driver instance.
* @param res Pointer to struct arm_smccc_res response.
*
* @retval 0 on success.
* @retval SIP_SVC_ID_INVALID on failure
*/
__syscall uint32_t sip_svc_plat_get_error_code(const struct device *dev, struct arm_smccc_res *res);
static inline uint32_t z_impl_sip_svc_plat_get_error_code(const struct device *dev,
struct arm_smccc_res *res)
{
__ASSERT(dev, "dev shouldn't be NULL");
const struct svc_driver_api *api = DEV_API(dev);
__ASSERT(api->sip_svc_plat_get_error_code,
"sip_svc_plat_get_error_code func shouldn't be NULL");
__ASSERT(res, "res shouldn't be NULL");
return api->sip_svc_plat_get_error_code(dev, res);
}
/**
* @brief Set arguments for polling supervisory call. For ASYNC polling of response.
*
* @param dev Pointer to the device structure for the driver instance.
* @param a0 Argument 0 for supervisory call.
* @param a1 Argument 1 for supervisory call.
* @param a2 Argument 2 for supervisory call.
* @param a3 Argument 3 for supervisory call.
* @param a4 Argument 4 for supervisory call.
* @param a5 Argument 5 for supervisory call.
* @param a6 Argument 6 for supervisory call.
* @param a7 Argument 7 for supervisory call.
* @param buf Pointer for response buffer.
* @param size Size of response buffer.
*
* @retval 0 on success
*/
__syscall int sip_svc_plat_async_res_req(const struct device *dev, unsigned long *a0,
unsigned long *a1, unsigned long *a2, unsigned long *a3,
unsigned long *a4, unsigned long *a5, unsigned long *a6,
unsigned long *a7, char *buf, size_t size);
static inline int z_impl_sip_svc_plat_async_res_req(const struct device *dev, unsigned long *a0,
unsigned long *a1, unsigned long *a2,
unsigned long *a3, unsigned long *a4,
unsigned long *a5, unsigned long *a6,
unsigned long *a7, char *buf, size_t size)
{
__ASSERT(dev, "dev shouldn't be NULL");
const struct svc_driver_api *api = DEV_API(dev);
__ASSERT(api->sip_svc_plat_async_res_req,
"sip_svc_plat_async_res_req func shouldn't be NULL");
__ASSERT(a0, "a0 shouldn't be NULL");
__ASSERT(a1, "a1 shouldn't be NULL");
__ASSERT(a2, "a2 shouldn't be NULL");
__ASSERT(a3, "a3 shouldn't be NULL");
__ASSERT(a4, "a4 shouldn't be NULL");
__ASSERT(a5, "a5 shouldn't be NULL");
__ASSERT(a6, "a6 shouldn't be NULL");
__ASSERT(a7, "a7 shouldn't be NULL");
__ASSERT(((buf == NULL && size == 0) || (buf != NULL && size != 0)),
"buf and size should represent a buffer");
return api->sip_svc_plat_async_res_req(dev, a0, a1, a2, a3, a4, a5, a6, a7, buf, size);
}
/**
* @brief Check the response of polling supervisory call and retrieve the response
* size and transaction id.
*
* @param dev Pointer to the device structure for the driver instance.
* @param res Pointer to struct arm_smccc_res response.
* @param buf Pointer to response buffer.
* @param size Size of response in response buffer
* @param trans_id Transaction id of the response.
*
* @retval 0 on getting a valid polling response from supervisory call.
* @retval -EINPROGRESS on no valid polling response from supervisory call.
*/
__syscall int sip_svc_plat_async_res_res(const struct device *dev, struct arm_smccc_res *res,
char *buf, size_t *size, uint32_t *trans_id);
static inline int z_impl_sip_svc_plat_async_res_res(const struct device *dev,
struct arm_smccc_res *res, char *buf,
size_t *size, uint32_t *trans_id)
{
__ASSERT(dev, "dev shouldn't be NULL");
const struct svc_driver_api *api = DEV_API(dev);
__ASSERT(api->sip_svc_plat_async_res_res,
"sip_svc_plat_async_res_res func shouldn't be NULL");
__ASSERT(res, "res shouldn't be NULL");
__ASSERT(buf, "buf shouldn't be NULL");
__ASSERT(size, "size shouldn't be NULL");
__ASSERT(trans_id, "buf shouldn't be NULL");
return api->sip_svc_plat_async_res_res(dev, res, buf, size, trans_id);
}
/**
* @brief Free the command buffer used for ASYNC packet after sending it to lower layers.
*
* @param dev Pointer to the device structure for the driver instance.
* @param request Pointer to sip_svc_request packet.
*/
__syscall void sip_svc_plat_free_async_memory(const struct device *dev,
struct sip_svc_request *request);
static inline void z_impl_sip_svc_plat_free_async_memory(const struct device *dev,
struct sip_svc_request *request)
{
__ASSERT(dev, "dev shouldn't be NULL");
const struct svc_driver_api *api = DEV_API(dev);
__ASSERT(api->sip_svc_plat_free_async_memory,
"sip_svc_plat_free_async_memory func shouldn't be NULL");
__ASSERT(request, "request shouldn't be NULL");
api->sip_svc_plat_free_async_memory(dev, request);
}
#include <zephyr/syscalls/sip_svc_driver.h>
#endif /* ZEPHYR_INCLUDE_SIP_SVC_DRIVER_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/sip_svc/sip_svc_driver.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 3,437 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_SIP_SVC_PROTO_H_
#define ZEPHYR_INCLUDE_SIP_SVC_PROTO_H_
/**
* @file
* @brief Arm SiP services communication protocol
* between service provider and client.
*
* Client to fill in the input data in struct sip_svc_request format
* when requesting SMC/HVC service via 'send' function.
*
* Service to fill in the SMC/HVC return value in struct sip_svc_response
* format and pass to client via Callback.
*/
/**
* @brief Invalid id value
*/
#define SIP_SVC_ID_INVALID 0xFFFFFFFF
/** @brief Header format
*/
#define SIP_SVC_PROTO_VER 0x0
#define SIP_SVC_PROTO_HEADER_CODE_OFFSET 0
#define SIP_SVC_PROTO_HEADER_CODE_MASK 0xFFFF
#define SIP_SVC_PROTO_HEADER_TRANS_ID_OFFSET 16
#define SIP_SVC_PROTO_HEADER_TRANS_ID_MASK 0xFF
#define SIP_SVC_PROTO_HEADER_VER_OFFSET 30
#define SIP_SVC_PROTO_HEADER_VER_MASK 0x3
#define SIP_SVC_PROTO_HEADER(code, trans_id) \
((((code)&SIP_SVC_PROTO_HEADER_CODE_MASK) << SIP_SVC_PROTO_HEADER_CODE_OFFSET) | \
(((trans_id)&SIP_SVC_PROTO_HEADER_TRANS_ID_MASK) \
<< SIP_SVC_PROTO_HEADER_TRANS_ID_OFFSET) | \
((SIP_SVC_PROTO_VER & SIP_SVC_PROTO_HEADER_VER_MASK) << SIP_SVC_PROTO_HEADER_VER_OFFSET))
#define SIP_SVC_PROTO_HEADER_GET_CODE(header) \
(((header) >> SIP_SVC_PROTO_HEADER_CODE_OFFSET) & SIP_SVC_PROTO_HEADER_CODE_MASK)
#define SIP_SVC_PROTO_HEADER_GET_TRANS_ID(header) \
(((header) >> SIP_SVC_PROTO_HEADER_TRANS_ID_OFFSET) & SIP_SVC_PROTO_HEADER_TRANS_ID_MASK)
#define SIP_SVC_PROTO_HEADER_SET_TRANS_ID(header, trans_id) \
(header) &= ~(SIP_SVC_PROTO_HEADER_TRANS_ID_MASK << SIP_SVC_PROTO_HEADER_TRANS_ID_OFFSET); \
(header) |= (((trans_id)&SIP_SVC_PROTO_HEADER_TRANS_ID_MASK) \
<< SIP_SVC_PROTO_HEADER_TRANS_ID_OFFSET);
/** @brief Arm SiP services command code in request header
*
* SIP_SVC_PROTO_CMD_SYNC
* - Typical flow, synchronous request. Service expects EL3/EL2 firmware to
* return the result immediately during SMC/HVC call.
*
* SIP_SVC_PROTO_CMD_ASYNC
* - Asynchronous request. Service is required to poll the response via a
* separate SMC/HVC call. Use this method if the request requires longer
* processing in EL3/EL2.
*/
#define SIP_SVC_PROTO_CMD_SYNC 0x0
#define SIP_SVC_PROTO_CMD_ASYNC 0x1
#define SIP_SVC_PROTO_CMD_MAX SIP_SVC_PROTO_CMD_ASYNC
/** @brief Error code in response header
*
* SIP_SVC_PROTO_STATUS_OK
* - Successfully execute the request.
*
* SIP_SVC_PROTO_STATUS_UNKNOWN
* - Unrecognized SMC/HVC Function ID.
*
* SIP_SVC_PROTO_STATUS_BUSY
* - The request is still in progress. Please try again.
*
* SIP_SVC_PROTO_STATUS_REJECT
* - The request have been rejected due to improper input data.
*
* SIP_SVC_PROTO_STATUS_NO_RESPONSE
* - No response from target hardware yet.
*
* SIP_SVC_PROTO_STATUS_ERROR
* - Error occurred when executing the request.
*
* SIP_SVC_PROTO_STATUS_NOT_SUPPORT
* - Unsupported Arm SiP services command code
*/
#define SIP_SVC_PROTO_STATUS_OK 0x0
#define SIP_SVC_PROTO_STATUS_UNKNOWN 0xFFFF
#define SIP_SVC_PROTO_STATUS_BUSY 0x1
#define SIP_SVC_PROTO_STATUS_REJECT 0x2
#define SIP_SVC_PROTO_STATUS_NO_RESPONSE 0x3
#define SIP_SVC_PROTO_STATUS_ERROR 0x4
/** @brief SiP Service communication protocol
* request format.
*
* request header
* - bits [15: 0] Arm SiP services command code
* - bits [23:16] Transaction ID (Filled in by sip_svc service)
* - bits [29:24] Unused. Reserved.
* - bits [31:30] Arm SiP services communication protocol version
*
* a0 - a7
* - User input data to be filled into a0-a7 registers when trigger
* SMC/HVC
*
* resp_data_addr
* - This parameter only used by asynchronous command.
* - Dynamic memory address for service to put the asynchronous response
* data. The service will free this memory space if the client has
* cancelled the transaction.
*
* resp_data_size
* - This parameter only used by asynchronous command.
* - Maximum memory size in bytes of resp_data_addr
*
* priv_data
* - Memory address to client context. Service will pass this address back
* to client in response format via callback.
*/
struct sip_svc_request {
uint32_t header;
unsigned long a0;
unsigned long a1;
unsigned long a2;
unsigned long a3;
unsigned long a4;
unsigned long a5;
unsigned long a6;
unsigned long a7;
uint64_t resp_data_addr;
uint32_t resp_data_size;
void *priv_data;
};
/** @brief SiP Services service communication protocol
* response format.
*
* response header
* - bits [15: 0] Error code
* - bits [23:16] Transaction ID
* - bits [29:24] Unused. Reserved.
* - bits [31:30] Arm SiP services communication protocol version
*
* a0 - a3
* - SMC/HVC return value
*
* resp_data_addr
* - This parameter only used by asynchronous command.
* - Dynamic memory address that put the asynchronous response data.
* This address is provided by client during request. Client is responsible
* to free the memory space when receive the callback of a asynchronous
* command transaction.The memory needs to be dynamically allocated,
* the framework will free the allocated memory if the channel is in ABORT
* state.
*
* resp_data_size
* - This parameter only used by asynchronous command.
* - Valid data size in bytes of resp_data_addr
*
* priv_data
* - Memory address to client context which given during request.
*/
struct sip_svc_response {
uint32_t header;
unsigned long a0;
unsigned long a1;
unsigned long a2;
unsigned long a3;
uint64_t resp_data_addr;
uint32_t resp_data_size;
void *priv_data;
};
#endif /* ZEPHYR_INCLUDE_SIP_SVC_PROTO_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/sip_svc/sip_svc_proto.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,446 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_ETH_NXP_ENET_H__
#define ZEPHYR_INCLUDE_DRIVERS_ETH_NXP_ENET_H__
/*
* This header is for NXP ENET driver development
* and has definitions for internal implementations
* not to be used by application
*/
#include <zephyr/device.h>
#include <zephyr/kernel.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Reasons for callback to a driver:
*
* Module reset: The ENET module was reset, perhaps because of power management
* actions, and subdriver should reinitialize part of the module.
* Interrupt: An interrupt of a type relevant to the subdriver occurred.
* Interrupt enable: The driver's relevant interrupt was enabled in NVIC
*/
enum nxp_enet_callback_reason {
NXP_ENET_MODULE_RESET,
NXP_ENET_INTERRUPT,
NXP_ENET_INTERRUPT_ENABLED,
};
enum nxp_enet_driver {
NXP_ENET_MAC,
NXP_ENET_MDIO,
NXP_ENET_PTP_CLOCK,
};
extern void nxp_enet_mdio_callback(const struct device *mdio_dev,
enum nxp_enet_callback_reason event,
void *data);
#ifdef CONFIG_PTP_CLOCK_NXP_ENET
extern void nxp_enet_ptp_clock_callback(const struct device *dev,
enum nxp_enet_callback_reason event,
void *data);
#else
#define nxp_enet_ptp_clock_callback(...)
#endif
/*
* Internal implementation, inter-driver communication function
*
* dev: target device to call back
* dev_type: which driver to call back
* event: reason/cause of callback
* data: opaque data, will be interpreted based on reason and target driver
*/
extern void nxp_enet_driver_cb(const struct device *dev,
enum nxp_enet_driver dev_type,
enum nxp_enet_callback_reason event,
void *data);
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_ETH_NXP_ENET_H__ */
``` | /content/code_sandbox/include/zephyr/drivers/ethernet/eth_nxp_enet.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 426 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_SIP_SVC_AGILEX_SMC_H_
#define ZEPHYR_INCLUDE_SIP_SVC_AGILEX_SMC_H_
/**
* @file
* @brief Intel SoC FPGA Agilex customized Arm SiP Services
* SMC protocol.
*/
/* @brief SMC return status
*/
#define SMC_STATUS_INVALID 0xFFFFFFFF
#define SMC_STATUS_OKAY 0
#define SMC_STATUS_BUSY 1
#define SMC_STATUS_REJECT 2
#define SMC_STATUS_NO_RESPONSE 3
#define SMC_STATUS_ERROR 4
/* @brief SMC Intel Header at a1
*
* bit
* 7: 0 Transaction ID
* 59: 8 Reserved
* 63:60 Version
*/
#define SMC_PLAT_PROTO_VER 0x0
#define SMC_PLAT_PROTO_HEADER_TRANS_ID_OFFSET 0
#define SMC_PLAT_PROTO_HEADER_TRANS_ID_MASK 0xFF
#define SMC_PLAT_PROTO_HEADER_VER_OFFSET 60
#define SMC_PLAT_PROTO_HEADER_VER_MASK 0xF
#define SMC_PLAT_PROTO_HEADER \
((SMC_PLAT_PROTO_VER & SMC_PLAT_PROTO_HEADER_VER_MASK) << SMC_PLAT_PROTO_HEADER_VER_OFFSET)
#define SMC_PLAT_PROTO_HEADER_SET_TRANS_ID(header, trans_id) \
(header) &= \
~(SMC_PLAT_PROTO_HEADER_TRANS_ID_MASK << SMC_PLAT_PROTO_HEADER_TRANS_ID_OFFSET); \
(header) |= (((trans_id)&SMC_PLAT_PROTO_HEADER_TRANS_ID_MASK) \
<< SMC_PLAT_PROTO_HEADER_TRANS_ID_OFFSET);
/* @brief SYNC SMC Function IDs
*/
#define SMC_FUNC_ID_GET_SVC_VERSION 0xC2000400
#define SMC_FUNC_ID_REG_READ 0xC2000401
#define SMC_FUNC_ID_REG_WRITE 0xC2000402
#define SMC_FUNC_ID_REG_UPDATE 0xC2000403
#define SMC_FUNC_ID_SET_HPS_BRIDGES 0xC2000404
#define SMC_FUNC_ID_RSU_UPDATE_ADDR 0xC2000405
/* @brief ASYNC SMC Function IDs
*/
#define SMC_FUNC_ID_MAILBOX_SEND_COMMAND 0xC2000420
#define SMC_FUNC_ID_MAILBOX_POLL_RESPONSE 0xC2000421
/* @brief SDM mailbox CANCEL command
*/
#define MAILBOX_CANCEL_COMMAND 0x03
#endif /* ZEPHYR_INCLUDE_SIP_SVC_AGILEX_SMC_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/sip_svc/sip_svc_agilex_smc.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 548 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_ETH_NXP_ENET_QOS_H__
#define ZEPHYR_INCLUDE_DRIVERS_ETH_NXP_ENET_QOS_H__
#include <fsl_device_registers.h>
#include <zephyr/drivers/clock_control.h>
/* Different platforms named the peripheral different in the register definitions */
#ifdef CONFIG_SOC_FAMILY_NXP_MCX
#undef ENET
#define ENET_QOS_NAME ENET
#define ENET_QOS_ALIGNMENT 4
typedef ENET_Type enet_qos_t;
#else
#error "ENET_QOS not enabled on this SOC series"
#endif
#define _PREFIX_UNDERLINE(x) _##x
#define _ENET_QOS_REG_FIELD(reg, field) MACRO_MAP_CAT(_PREFIX_UNDERLINE, reg, field, MASK)
#define _ENET_QOS_REG_MASK(reg, field) CONCAT(ENET_QOS_NAME, _ENET_QOS_REG_FIELD(reg, field))
/* Deciphers value of a field from a read value of an enet qos register
*
* reg: name of the register
* field: name of the bit field within the register
* val: value that had been read from the register
*/
#define ENET_QOS_REG_GET(reg, field, val) FIELD_GET(_ENET_QOS_REG_MASK(reg, field), val)
/* Prepares value of a field for a write to an enet qos register
*
* reg: name of the register
* field: name of the bit field within the register
* val: value to put into the field
*/
#define ENET_QOS_REG_PREP(reg, field, val) FIELD_PREP(_ENET_QOS_REG_MASK(reg, field), val)
#define ENET_QOS_ALIGN_ADDR_SHIFT(x) (x >> (ENET_QOS_ALIGNMENT >> 1))
struct nxp_enet_qos_config {
const struct pinctrl_dev_config *pincfg;
const struct device *clock_dev;
clock_control_subsys_t clock_subsys;
enet_qos_t *base;
};
#define ENET_QOS_MODULE_CFG(module_dev) ((struct nxp_enet_qos_config *) module_dev->config)
#endif /* ZEPHYR_INCLUDE_DRIVERS_ETH_NXP_ENET_H__ */
``` | /content/code_sandbox/include/zephyr/drivers/ethernet/eth_nxp_enet_qos.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 462 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_MIPI_DSI_MCUX_2L_
#define ZEPHYR_INCLUDE_DRIVERS_MIPI_DSI_MCUX_2L_
/*
* HW specific flag- indicates to the MIPI DSI 2L peripheral that the
* data being sent is framebuffer data, which the DSI peripheral may
* byte swap depending on KConfig settings
*/
#define MCUX_DSI_2L_FB_DATA BIT(0x1)
#endif /* ZEPHYR_INCLUDE_DRIVERS_MIPI_DSI_MCUX_2L_ */
``` | /content/code_sandbox/include/zephyr/drivers/mipi_dsi/mipi_dsi_mcux_2l.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 121 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_ETH_ADIN2111_H__
#define ZEPHYR_INCLUDE_DRIVERS_ETH_ADIN2111_H__
#include <stdint.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Locks device access
*
* @param[in] dev ADIN2111 device.
* @param timeout Waiting period to lock the device,
* or one of the special values K_NO_WAIT and
* K_FOREVER.
*
* @retval 0 Device locked.
* @retval -EBUSY Returned without waiting.
* @retval -EAGAIN Waiting period timed out.
*/
int eth_adin2111_lock(const struct device *dev, k_timeout_t timeout);
/**
* @brief Unlocks device access
*
* @param[in] dev ADIN2111 device.
*
* @retval 0 Device unlocked.
* @retval -EPERM The current thread does not own the device lock.
* @retval -EINVAL The device is not locked.
*/
int eth_adin2111_unlock(const struct device *dev);
/**
* @brief Writes host MAC interface register over SPI
*
* @note The caller is responsible for device lock.
* Shall not be called from ISR.
*
* @param[in] dev ADIN2111 device.
* @param reg Register address.
* @param val Value to write.
*
* @retval 0 Successful write.
* @retval <0 Error, a negative errno code.
*/
int eth_adin2111_reg_write(const struct device *dev, const uint16_t reg, uint32_t val);
/**
* @brief Reads host MAC interface register over SPI
*
* @note The caller is responsible for device lock.
* Shall not be called from ISR.
*
* @param[in] dev ADIN2111 device.
* @param reg Register address.
* @param[out] val Read value output.
*
* @retval 0 Successful write.
* @retval <0 Error, a negative errno code.
*/
int eth_adin2111_reg_read(const struct device *dev, const uint16_t reg, uint32_t *val);
/**
* @brief Update host MAC interface register over SPI
*
* @note The caller is responsible for device lock.
* Shall not be called from ISR.
*
* @param[in] dev ADIN2111 device.
* @param reg Register address.
* @param mask Bitmask for bits that may be modified.
* @param data Data to apply in the masked range.
*
* @retval 0 Successful write.
* @retval <0 Error, a negative errno code.
*/
int eth_adin2111_reg_update(const struct device *dev, const uint16_t reg,
uint32_t mask, uint32_t data);
/**
* @brief Reset both the MAC and PHY.
*
* @param[in] dev ADIN2111 device.
* @param delay Delay in milliseconds.
*
* @note The caller is responsible for device lock.
* Shall not be called from ISR.
*
* @retval 0 Successful write.
* @retval <0 Error, a negative errno code.
*/
int eth_adin2111_sw_reset(const struct device *dev, uint16_t delay);
/**
* @brief Reset the MAC device. Note that PHY 1 must be out of software power-down for the MAC
* subsystem reset to take effect.
*
* @note The caller is responsible for device lock.
* Shall not be called from ISR.
*
* @param[in] dev ADIN2111 device.
*
* @retval 0 Successful write.
* @retval <0 Error, a negative errno code.
*/
int eth_adin2111_mac_reset(const struct device *dev);
/**
* @brief Enable/disable the forwarding (to host) of broadcast frames. Frames who's DA
* doesn't match are dropped.
*
* @note The caller is responsible for device lock.
* Shall not be called from ISR.
*
* @param[in] dev ADIN2111 device.
* @param enable Set to 0 to disable and to nonzero to enable.
*
* @retval 0 Successful write.
* @retval <0 Error, a negative errno code.
*/
int eth_adin2111_broadcast_filter(const struct device *dev, bool enable);
/**
* @brief Get the port-related net_if reference.
*
* @param[in] dev ADIN2111 device.
* @param port_idx Port index.
*
* @retval a struct net_if pointer, or NULL on error.
*/
struct net_if *eth_adin2111_get_iface(const struct device *dev, const uint16_t port_idx);
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_ETH_ADIN2111_H__ */
``` | /content/code_sandbox/include/zephyr/drivers/ethernet/eth_adin2111.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,002 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_I3C_ADDRESSES_H_
#define ZEPHYR_INCLUDE_DRIVERS_I3C_ADDRESSES_H_
/**
* @brief I3C Address-related Helper Code
* @defgroup i3c_addresses I3C Address-related Helper Code
* @ingroup i3c_interface
* @{
*/
#include <stdint.h>
#include <zephyr/device.h>
#include <zephyr/sys/util.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Broadcast Address on I3C bus. */
#define I3C_BROADCAST_ADDR 0x7E
/** Maximum value of device addresses. */
#define I3C_MAX_ADDR 0x7F
struct i3c_dev_list;
/**
* Enum to indicate whether an address is reserved, has I2C/I3C device attached,
* or no device attached.
*/
enum i3c_addr_slot_status {
/** Address has not device attached. */
I3C_ADDR_SLOT_STATUS_FREE = 0U,
/** Address is reserved. */
I3C_ADDR_SLOT_STATUS_RSVD,
/** Address is associated with an I3C device. */
I3C_ADDR_SLOT_STATUS_I3C_DEV,
/** Address is associated with an I2C device. */
I3C_ADDR_SLOT_STATUS_I2C_DEV,
/** Bit masks used to filter status bits. */
I3C_ADDR_SLOT_STATUS_MASK = 0x03U,
};
/**
* @brief Structure to keep track of addresses on I3C bus.
*/
struct i3c_addr_slots {
/* 2 bits per slot */
unsigned long slots[((I3C_MAX_ADDR + 1) * 2) / BITS_PER_LONG];
};
/**
* @brief Initialize the I3C address slots struct.
*
* This clears out the assigned address bits, and set the reserved
* address bits according to the I3C specification.
*
* @param dev Pointer to controller device driver instance.
*
* @retval 0 if successful.
* @retval -EINVAL if duplicate addresses.
*/
int i3c_addr_slots_init(const struct device *dev);
/**
* @brief Set the address status of a device.
*
* @param slots Pointer to the address slots structure.
* @param dev_addr Device address.
* @param status New status for the address @p dev_addr.
*/
void i3c_addr_slots_set(struct i3c_addr_slots *slots,
uint8_t dev_addr,
enum i3c_addr_slot_status status);
/**
* @brief Get the address status of a device.
*
* @param slots Pointer to the address slots structure.
* @param dev_addr Device address.
*
* @return Address status for the address @p dev_addr.
*/
enum i3c_addr_slot_status i3c_addr_slots_status(struct i3c_addr_slots *slots,
uint8_t dev_addr);
/**
* @brief Check if the address is free.
*
* @param slots Pointer to the address slots structure.
* @param dev_addr Device address.
*
* @retval true if address is free.
* @retval false if address is not free.
*/
bool i3c_addr_slots_is_free(struct i3c_addr_slots *slots,
uint8_t dev_addr);
/**
* @brief Find the next free address.
*
* This can be used to find the next free address that can be
* assigned to a new device.
*
* @param slots Pointer to the address slots structure.
* @param start_addr Where to start searching
*
* @return The next free address, or 0 if none found.
*/
uint8_t i3c_addr_slots_next_free_find(struct i3c_addr_slots *slots, uint8_t start_addr);
/**
* @brief Mark the address as free (not used) in device list.
*
* @param addr_slots Pointer to the address slots struct.
* @param addr Device address.
*/
static inline void i3c_addr_slots_mark_free(struct i3c_addr_slots *addr_slots,
uint8_t addr)
{
i3c_addr_slots_set(addr_slots, addr,
I3C_ADDR_SLOT_STATUS_FREE);
}
/**
* @brief Mark the address as reserved in device list.
*
* @param addr_slots Pointer to the address slots struct.
* @param addr Device address.
*/
static inline void i3c_addr_slots_mark_rsvd(struct i3c_addr_slots *addr_slots,
uint8_t addr)
{
i3c_addr_slots_set(addr_slots, addr,
I3C_ADDR_SLOT_STATUS_RSVD);
}
/**
* @brief Mark the address as I3C device in device list.
*
* @param addr_slots Pointer to the address slots struct.
* @param addr Device address.
*/
static inline void i3c_addr_slots_mark_i3c(struct i3c_addr_slots *addr_slots,
uint8_t addr)
{
i3c_addr_slots_set(addr_slots, addr,
I3C_ADDR_SLOT_STATUS_I3C_DEV);
}
/**
* @brief Mark the address as I2C device in device list.
*
* @param addr_slots Pointer to the address slots struct.
* @param addr Device address.
*/
static inline void i3c_addr_slots_mark_i2c(struct i3c_addr_slots *addr_slots,
uint8_t addr)
{
i3c_addr_slots_set(addr_slots, addr,
I3C_ADDR_SLOT_STATUS_I2C_DEV);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_I3C_ADDRESSES_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/i3c/addresses.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,155 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_I3C_DEVICETREE_H_
#define ZEPHYR_INCLUDE_DRIVERS_I3C_DEVICETREE_H_
/**
* @brief I3C Devicetree related bits
* @defgroup i3c_devicetree I3C Devicetree related bits
* @ingroup i3c_interface
* @{
*/
#include <stdint.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/sys/util.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Structure initializer for i3c_device_id from devicetree
*
* This helper macro expands to a static initializer for a <tt>struct
* i3c_device_id</tt> by reading the relevant device data from devicetree.
*
* @param node_id Devicetree node identifier for the I3C device whose
* struct i3c_device_id to create an initializer for
*/
#define I3C_DEVICE_ID_DT(node_id) \
{ \
.pid = ((uint64_t)DT_PROP_BY_IDX(node_id, reg, 1) << 32)\
| DT_PROP_BY_IDX(node_id, reg, 2), \
}
/**
* @brief Structure initializer for i3c_device_id from devicetree instance
*
* This is equivalent to
* @code{.c}
* I3C_DEVICE_ID_DT(DT_DRV_INST(inst))
* @endcode
*
* @param inst Devicetree instance number
*/
#define I3C_DEVICE_ID_DT_INST(inst) \
I3C_DEVICE_ID_DT(DT_DRV_INST(inst))
/**
* @brief Structure initializer for i3c_device_desc from devicetree
*
* This helper macro expands to a static initializer for a <tt>struct
* i3c_device_desc</tt> by reading the relevant bus and device data
* from the devicetree.
*
* @param node_id Devicetree node identifier for the I3C device whose
* struct i3c_device_desc to create an initializer for
*/
#define I3C_DEVICE_DESC_DT(node_id) \
{ \
.bus = DEVICE_DT_GET(DT_BUS(node_id)), \
.dev = DEVICE_DT_GET(node_id), \
.static_addr = DT_PROP_BY_IDX(node_id, reg, 0), \
.pid = ((uint64_t)DT_PROP_BY_IDX(node_id, reg, 1) << 32)\
| DT_PROP_BY_IDX(node_id, reg, 2), \
.init_dynamic_addr = \
DT_PROP_OR(node_id, assigned_address, 0), \
},
/**
* @brief Structure initializer for i3c_device_desc from devicetree instance
*
* This is equivalent to
*
* @code{.c}
* I3C_DEVICE_DESC_DT(DT_DRV_INST(inst))
* @endcode
*
* @param inst Devicetree instance number
*/
#define I3C_DEVICE_DESC_DT_INST(inst) \
I3C_DEVICE_DESC_DT(DT_DRV_INST(inst))
/**
* @brief Structure initializer for i3c_device_desc from devicetree
*
* This is mainly used by I3C_DEVICE_ARRAY_DT() to only
* create a struct if and only if it is an I3C device.
*/
#define I3C_DEVICE_DESC_DT_FILTERED(node_id) \
COND_CODE_0(DT_PROP_BY_IDX(node_id, reg, 1), \
(), (I3C_DEVICE_DESC_DT(node_id)))
/**
* @brief Array initializer for a list of i3c_device_desc from devicetree
*
* This is a helper macro to generate an array for a list of i3c_device_desc
* from device tree.
*
* @param node_id Devicetree node identifier of the I3C controller
*/
#define I3C_DEVICE_ARRAY_DT(node_id) \
{ \
DT_FOREACH_CHILD_STATUS_OKAY( \
node_id, \
I3C_DEVICE_DESC_DT_FILTERED) \
}
/**
* @brief Array initializer for a list of i3c_device_desc from devicetree instance
*
* This is equivalent to
* @code{.c}
* I3C_DEVICE_ARRAY_DT(DT_DRV_INST(inst))
* @endcode
*
* @param inst Devicetree instance number of the I3C controller
*/
#define I3C_DEVICE_ARRAY_DT_INST(inst) \
I3C_DEVICE_ARRAY_DT(DT_DRV_INST(inst))
/**
* @brief Like DEVICE_DT_DEFINE() with I3C target device specifics.
*
* Defines a I3C target device which implements the I3C target device API.
*
* @param node_id The devicetree node identifier.
*
* @param init_fn Name of the init function of the driver.
*
* @param pm PM device resources reference (`NULL` if device does not use PM).
*
* @param data Pointer to the device's private data.
*
* @param config The address to the structure containing the
* configuration information for this instance of the driver.
*
* @param level The initialization level. See SYS_INIT() for
* details.
*
* @param prio Priority within the selected initialization level. See
* SYS_INIT() for details.
*
* @param api Provides an initial pointer to the API function struct
* used by the driver. Can be NULL.
*/
#define I3C_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
prio, api, ...) \
DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
prio, api, __VA_ARGS__)
/**
* @brief Like I3C_TARGET_DT_DEFINE() for an instance of a DT_DRV_COMPAT compatible
*
* @param inst instance number. This is replaced by
* `DT_DRV_COMPAT(inst)` in the call to I3C_TARGET_DT_DEFINE().
*
* @param ... other parameters as expected by I3C_TARGET_DT_DEFINE().
*/
#define I3C_DEVICE_DT_INST_DEFINE(inst, ...) \
I3C_DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
/**
* @brief Structure initializer for i3c_i2c_device_desc from devicetree
*
* This helper macro expands to a static initializer for a i3c_i2c_device_desc
* by reading the relevant bus and device data from the devicetree.
*
* @param node_id Devicetree node identifier for the I3C device whose
* struct i3c_i2c_device_desc to create an initializer for
*/
#define I3C_I2C_DEVICE_DESC_DT(node_id) \
{ \
.bus = DEVICE_DT_GET(DT_BUS(node_id)), \
.addr = DT_PROP_BY_IDX(node_id, reg, 0), \
.lvr = DT_PROP_BY_IDX(node_id, reg, 2), \
},
/**
* @brief Structure initializer for i3c_i2c_device_desc from devicetree instance
*
* This is equivalent to
* @code{.c}
* I3C_I2C_DEVICE_DESC_DT(DT_DRV_INST(inst))
* @endcode
*
* @param inst Devicetree instance number
*/
#define I3C_I2C_DEVICE_DESC_DT_INST(inst) \
I3C_I2C_DEVICE_DESC_DT(DT_DRV_INST(inst))
/**
* @brief Structure initializer for i3c_i2c_device_desc from devicetree
*
* This is mainly used by I3C_I2C_DEVICE_ARRAY_DT() to only
* create a struct if and only if it is an I2C device.
*/
#define I3C_I2C_DEVICE_DESC_DT_FILTERED(node_id) \
COND_CODE_0(DT_PROP_BY_IDX(node_id, reg, 1), \
(I3C_I2C_DEVICE_DESC_DT(node_id)), ())
/**
* @brief Array initializer for a list of i3c_i2c_device_desc from devicetree
*
* This is a helper macro to generate an array for a list of
* i3c_i2c_device_desc from device tree.
*
* @param node_id Devicetree node identifier of the I3C controller
*/
#define I3C_I2C_DEVICE_ARRAY_DT(node_id) \
{ \
DT_FOREACH_CHILD_STATUS_OKAY( \
node_id, \
I3C_I2C_DEVICE_DESC_DT_FILTERED) \
}
/**
* @brief Array initializer for a list of i3c_i2c_device_desc from devicetree instance
*
* This is equivalent to
* @code{.c}
* I3C_I2C_DEVICE_ARRAY_DT(DT_DRV_INST(inst))
* @endcode
*
* @param inst Devicetree instance number of the I3C controller
*/
#define I3C_I2C_DEVICE_ARRAY_DT_INST(inst) \
I3C_I2C_DEVICE_ARRAY_DT(DT_DRV_INST(inst))
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_I3C_DEVICETREE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/i3c/devicetree.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,012 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_I3C_IBI_H_
#define ZEPHYR_INCLUDE_DRIVERS_I3C_IBI_H_
/**
* @brief I3C In-Band Interrupts
* @defgroup i3c_ibi I3C In-Band Interrupts
* @ingroup i3c_interface
* @{
*/
#include <stdint.h>
#include <zephyr/device.h>
#include <zephyr/kernel.h>
#include <zephyr/sys/slist.h>
#ifndef CONFIG_I3C_IBI_MAX_PAYLOAD_SIZE
#define CONFIG_I3C_IBI_MAX_PAYLOAD_SIZE 0
#endif
#ifdef __cplusplus
extern "C" {
#endif
struct i3c_device_desc;
/**
* @brief IBI Types.
*/
enum i3c_ibi_type {
/** Target interrupt */
I3C_IBI_TARGET_INTR,
/** Controller Role Request */
I3C_IBI_CONTROLLER_ROLE_REQUEST,
/** Hot Join Request */
I3C_IBI_HOTJOIN,
I3C_IBI_TYPE_MAX = I3C_IBI_HOTJOIN,
/**
* Not an actual IBI type, but simply used by
* the IBI workq for generic callbacks.
*/
I3C_IBI_WORKQUEUE_CB,
};
/**
* @brief Struct for IBI request.
*/
struct i3c_ibi {
/** Type of IBI. */
enum i3c_ibi_type ibi_type;
/** Pointer to payload of IBI. */
uint8_t *payload;
/** Length in bytes of the IBI payload. */
uint8_t payload_len;
};
/**
* @brief Structure of payload buffer for IBI.
*
* This is used for the IBI callback.
*/
struct i3c_ibi_payload {
/**
* Length of available data in the payload buffer.
*/
uint8_t payload_len;
/**
* Pointer to byte array as payload buffer.
*/
uint8_t payload[CONFIG_I3C_IBI_MAX_PAYLOAD_SIZE];
};
/**
* @brief Node about a queued IBI.
*/
struct i3c_ibi_work {
sys_snode_t node;
/**
* k_work struct.
*/
struct k_work work;
/**
* IBI type.
*/
enum i3c_ibi_type type;
union {
/**
* Use for @see I3C_IBI_HOTJOIN.
*/
const struct device *controller;
/**
* Use for @see I3C_IBI_TARGET_INTR,
* and @see I3C_IBI_CONTROLLER_ROLE_REQUEST.
*/
struct i3c_device_desc *target;
};
union {
/**
* IBI payload.
*/
struct i3c_ibi_payload payload;
/**
* Generic workqueue callback when
* type is I3C_IBI_WORKQUEUE_CB.
*/
k_work_handler_t work_cb;
};
};
/**
* @brief Function called when In-Band Interrupt received from target device.
*
* This function is invoked by the controller when the controller
* receives an In-Band Interrupt from the target device.
*
* A success return shall cause the controller to ACK the next byte
* received. An error return shall cause the controller to NACK the
* next byte received.
*
* @param target the device description structure associated with the
* device to which the operation is addressed.
* @param payload Payload associated with the IBI. NULL if there is
* no payload.
*
* @return 0 if the IBI is accepted, or a negative error code.
*/
typedef int (*i3c_target_ibi_cb_t)(struct i3c_device_desc *target,
struct i3c_ibi_payload *payload);
/**
* @brief Queue an IBI work item for future processing.
*
* This queues up an IBI work item in the IBI workqueue
* for future processing.
*
* Note that this will copy the @p ibi_work struct into
* internal structure. If there is not enough space to
* copy the @p ibi_work struct, this returns -ENOMEM.
*
* @param ibi_work Pointer to the IBI work item struct.
*
* @retval 0 If work item is successfully queued.
* @retval -ENOMEM If no more free internal node to
* store IBI work item.
* @retval Others @see k_work_submit_to_queue
*/
int i3c_ibi_work_enqueue(struct i3c_ibi_work *ibi_work);
/**
* @brief Queue a target interrupt IBI for future processing.
*
* This queues up a target interrupt IBI in the IBI workqueue
* for future processing.
*
* @param target Pointer to target device descriptor.
* @param payload Pointer to IBI payload byte array.
* @param payload_len Length of payload byte array.
*
* @retval 0 If work item is successfully queued.
* @retval -ENOMEM If no more free internal node to
* store IBI work item.
* @retval Others @see k_work_submit_to_queue
*/
int i3c_ibi_work_enqueue_target_irq(struct i3c_device_desc *target,
uint8_t *payload, size_t payload_len);
/**
* @brief Queue a hot join IBI for future processing.
*
* This queues up a hot join IBI in the IBI workqueue
* for future processing.
*
* @param dev Pointer to controller device driver instance.
*
* @retval 0 If work item is successfully queued.
* @retval -ENOMEM If no more free internal node to
* store IBI work item.
* @retval Others @see k_work_submit_to_queue
*/
int i3c_ibi_work_enqueue_hotjoin(const struct device *dev);
/**
* @brief Queue a generic callback for future processing.
*
* This queues up a generic callback in the IBI workqueue
* for future processing.
*
* @param dev Pointer to controller device driver instance.
* @param work_cb Callback function.
*
* @retval 0 If work item is successfully queued.
* @retval -ENOMEM If no more free internal node to
* store IBI work item.
* @retval Others @see k_work_submit_to_queue
*/
int i3c_ibi_work_enqueue_cb(const struct device *dev,
k_work_handler_t work_cb);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_I3C_IBI_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/i3c/ibi.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,359 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_I3C_TARGET_DEVICE_H_
#define ZEPHYR_INCLUDE_DRIVERS_I3C_TARGET_DEVICE_H_
/**
* @brief I3C Target Device API
* @defgroup i3c_target_device I3C Target Device API
* @ingroup i3c_interface
* @{
*/
#include <errno.h>
#include <stddef.h>
#include <stdint.h>
#include <zephyr/device.h>
#include <zephyr/sys/slist.h>
#ifdef __cplusplus
extern "C" {
#endif
struct i3c_driver_api;
/**
* @brief Configuration parameters for I3C hardware to act as target device.
*
* This can also be used to configure the controller if it is to act as
* a secondary controller on the bus.
*/
struct i3c_config_target {
/**
* If the hardware is to act as a target device
* on the bus.
*/
bool enable;
/**
* I3C target address.
*
* Used used when operates as secondary controller
* or as a target device.
*/
uint8_t static_addr;
/** Provisioned ID. */
uint64_t pid;
/**
* True if lower 32-bit of Provisioned ID is random.
*
* This sets the bit 32 of Provisioned ID which means
* the lower 32-bit is random value.
*/
bool pid_random;
/** Bus Characteristics Register (BCR). */
uint8_t bcr;
/** Device Characteristics Register (DCR). */
uint8_t dcr;
/** Maximum Read Length (MRL). */
uint16_t max_read_len;
/** Maximum Write Length (MWL). */
uint16_t max_write_len;
/**
* Bit mask of supported HDR modes (0 - 7).
*
* This can be used to enable or disable HDR mode
* supported by the hardware at runtime.
*/
uint8_t supported_hdr;
};
/**
* @brief Structure describing a device that supports the I3C target API.
*
* Instances of this are passed to the i3c_target_register() and
* i3c_target_unregister() functions to indicate addition and removal
* of a target device, respective.
*
* Fields other than @c node must be initialized by the module that
* implements the device behavior prior to passing the object
* reference to i3c_target_register().
*/
struct i3c_target_config {
sys_snode_t node;
/**
* Flags for the target device defined by I3C_TARGET_FLAGS_*
* constants.
*/
uint8_t flags;
/** Address for this target device */
uint8_t address;
/** Callback functions */
const struct i3c_target_callbacks *callbacks;
};
struct i3c_target_callbacks {
/**
* @brief Function called when a write to the device is initiated.
*
* This function is invoked by the controller when the bus completes
* a start condition for a write operation to the address associated
* with a particular device.
*
* A success return shall cause the controller to ACK the next byte
* received. An error return shall cause the controller to NACK the
* next byte received.
*
* @param config Configuration structure associated with the
* device to which the operation is addressed.
*
* @return 0 if the write is accepted, or a negative error code.
*/
int (*write_requested_cb)(struct i3c_target_config *config);
/**
* @brief Function called when a write to the device is continued.
*
* This function is invoked by the controller when it completes
* reception of a byte of data in an ongoing write operation to the
* device.
*
* A success return shall cause the controller to ACK the next byte
* received. An error return shall cause the controller to NACK the
* next byte received.
*
* @param config Configuration structure associated with the
* device to which the operation is addressed.
*
* @param val the byte received by the controller.
*
* @return 0 if more data can be accepted, or a negative error
* code.
*/
int (*write_received_cb)(struct i3c_target_config *config,
uint8_t val);
/**
* @brief Function called when a read from the device is initiated.
*
* This function is invoked by the controller when the bus completes a
* start condition for a read operation from the address associated
* with a particular device.
*
* The value returned in @p val will be transmitted. A success
* return shall cause the controller to react to additional read
* operations. An error return shall cause the controller to ignore
* bus operations until a new start condition is received.
*
* @param config Configuration structure associated with the
* device to which the operation is addressed.
*
* @param val Pointer to storage for the first byte of data to return
* for the read request.
*
* @return 0 if more data can be requested, or a negative error code.
*/
int (*read_requested_cb)(struct i3c_target_config *config,
uint8_t *val);
/**
* @brief Function called when a read from the device is continued.
*
* This function is invoked by the controller when the bus is ready to
* provide additional data for a read operation from the address
* associated with the device device.
*
* The value returned in @p val will be transmitted. A success
* return shall cause the controller to react to additional read
* operations. An error return shall cause the controller to ignore
* bus operations until a new start condition is received.
*
* @param config Configuration structure associated with the
* device to which the operation is addressed.
*
* @param val Pointer to storage for the next byte of data to return
* for the read request.
*
* @return 0 if data has been provided, or a negative error code.
*/
int (*read_processed_cb)(struct i3c_target_config *config,
uint8_t *val);
/**
* @brief Function called when a stop condition is observed after a
* start condition addressed to a particular device.
*
* This function is invoked by the controller when the bus is ready to
* provide additional data for a read operation from the address
* associated with the device device. After the function returns the
* controller shall enter a state where it is ready to react to new
* start conditions.
*
* @param config Configuration structure associated with the
* device to which the operation is addressed.
*
* @return Ignored.
*/
int (*stop_cb)(struct i3c_target_config *config);
};
__subsystem struct i3c_target_driver_api {
int (*driver_register)(const struct device *dev);
int (*driver_unregister)(const struct device *dev);
};
/**
* @brief Writes to the target's TX FIFO
*
* Write to the TX FIFO @p dev I3C bus driver using the provided
* buffer and length. Some I3C targets will NACK read requests until data
* is written to the TX FIFO. This function will write as much as it can
* to the FIFO return the total number of bytes written. It is then up to
* the application to utalize the target callbacks to write the remaining
* data. Negative returns indicate error.
*
* Most of the existing hardware allows simultaneous support for master
* and target mode. This is however not guaranteed.
*
* @param dev Pointer to the device structure for an I3C controller
* driver configured in target mode.
* @param buf Pointer to the buffer
* @param len Length of the buffer
* @param hdr_mode HDR mode see @c I3C_MSG_HDR_MODE*
*
* @retval Total number of bytes written
* @retval -ENOTSUP Not in Target Mode or HDR Mode not supported
* @retval -ENOSPC No space in Tx FIFO
* @retval -ENOSYS If target mode is not implemented
*/
static inline int i3c_target_tx_write(const struct device *dev,
uint8_t *buf, uint16_t len, uint8_t hdr_mode)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)dev->api;
if (api->target_tx_write == NULL) {
return -ENOSYS;
}
return api->target_tx_write(dev, buf, len, hdr_mode);
}
/**
* @brief Registers the provided config as target device of a controller.
*
* Enable I3C target mode for the @p dev I3C bus driver using the provided
* config struct (@p cfg) containing the functions and parameters to send bus
* events. The I3C target will be registered at the address provided as
* @ref i3c_target_config.address struct member. Any I3C bus events related
* to the target mode will be passed onto I3C target device driver via a set of
* callback functions provided in the 'callbacks' struct member.
*
* Most of the existing hardware allows simultaneous support for master
* and target mode. This is however not guaranteed.
*
* @param dev Pointer to the device structure for an I3C controller
* driver configured in target mode.
* @param cfg Config struct with functions and parameters used by
* the I3C target driver to send bus events
*
* @retval 0 Is successful
* @retval -EINVAL If parameters are invalid
* @retval -EIO General input / output error.
* @retval -ENOSYS If target mode is not implemented
*/
static inline int i3c_target_register(const struct device *dev,
struct i3c_target_config *cfg)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)dev->api;
if (api->target_register == NULL) {
return -ENOSYS;
}
return api->target_register(dev, cfg);
}
/**
* @brief Unregisters the provided config as target device
*
* This routine disables I3C target mode for the @p dev I3C bus driver using
* the provided config struct (@p cfg) containing the functions and parameters
* to send bus events.
*
* @param dev Pointer to the device structure for an I3C controller
* driver configured in target mode.
* @param cfg Config struct with functions and parameters used by
* the I3C target driver to send bus events
*
* @retval 0 Is successful
* @retval -EINVAL If parameters are invalid
* @retval -ENOSYS If target mode is not implemented
*/
static inline int i3c_target_unregister(const struct device *dev,
struct i3c_target_config *cfg)
{
const struct i3c_driver_api *api =
(const struct i3c_driver_api *)dev->api;
if (api->target_unregister == NULL) {
return -ENOSYS;
}
return api->target_unregister(dev, cfg);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_I3C_TARGET_DEVICE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/i3c/target_device.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,419 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_I3C_HDR_DDR_H_
#define ZEPHYR_INCLUDE_DRIVERS_I3C_HDR_DDR_H_
/**
* @brief I3C HDR DDR API
* @defgroup i3c_hdr_ddr I3C HDR DDR API
* @ingroup i3c_interface
* @{
*/
#include <errno.h>
#include <stddef.h>
#include <stdint.h>
#include <zephyr/drivers/i3c.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Write a set amount of data to an I3C target device with HDR DDR.
*
* This routine writes a set amount of data synchronously.
*
* @param target I3C target device descriptor.
* @param cmd 7-bit command code
* @param buf Memory pool from which the data is transferred.
* @param num_bytes Number of bytes to write.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_hdr_ddr_write(struct i3c_device_desc *target, uint8_t cmd,
uint8_t *buf, uint32_t num_bytes)
{
struct i3c_msg msg;
msg.buf = buf;
msg.len = num_bytes;
msg.flags = I3C_MSG_WRITE | I3C_MSG_STOP | I3C_MSG_HDR;
msg.hdr_mode = I3C_MSG_HDR_DDR;
msg.hdr_cmd_code = cmd;
return i3c_transfer(target, &msg, 1);
}
/**
* @brief Read a set amount of data from an I3C target device with HDR DDR.
*
* This routine reads a set amount of data synchronously.
*
* @param target I3C target device descriptor.
* @param cmd 7-bit command code
* @param buf Memory pool that stores the retrieved data.
* @param num_bytes Number of bytes to read.
*
* @retval 0 If successful.
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_hdr_ddr_read(struct i3c_device_desc *target, uint8_t cmd,
uint8_t *buf, uint32_t num_bytes)
{
struct i3c_msg msg;
msg.buf = buf;
msg.len = num_bytes;
msg.flags = I3C_MSG_STOP | I3C_MSG_HDR;
msg.hdr_mode = I3C_MSG_HDR_DDR;
msg.hdr_cmd_code = cmd;
return i3c_transfer(target, &msg, 1);
}
/**
* @brief Write then read data from an I3C target device with HDR DDR.
*
* This supports the common operation "this is what I want", "now give
* it to me" transaction pair through a combined write-then-read bus
* transaction.
*
* @param target I3C target device descriptor.
* @param write_buf Pointer to the data to be written
* @param num_write Number of bytes to write
* @param write_cmd 7-bit command code for write
* @param read_buf Pointer to storage for read data
* @param num_read Number of bytes to read
* @param read_cmd 7-bit command code for read
*
* @retval 0 if successful
* @retval -EBUSY Bus is busy.
* @retval -EIO General input / output error.
*/
static inline int i3c_hdr_ddr_write_read(struct i3c_device_desc *target,
const void *write_buf, size_t num_write, uint8_t read_cmd,
void *read_buf, size_t num_read, uint8_t write_cmd)
{
struct i3c_msg msg[2];
msg[0].buf = (uint8_t *)write_buf;
msg[0].len = num_write;
msg[0].flags = I3C_MSG_WRITE | I3C_MSG_HDR;
msg[0].hdr_mode = I3C_MSG_HDR_DDR;
msg[0].hdr_cmd_code = write_cmd;
msg[1].buf = (uint8_t *)read_buf;
msg[1].len = num_read;
msg[1].flags = I3C_MSG_RESTART | I3C_MSG_READ | I3C_MSG_HDR | I3C_MSG_STOP;
msg[1].hdr_mode = I3C_MSG_HDR_DDR;
msg[1].hdr_cmd_code = read_cmd;
return i3c_transfer(target, msg, 2);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_I3C_HDR_DDR_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/i3c/hdr_ddr.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 976 |
```objective-c
/*
*
* Author: Marcin Szkudlinski <marcin.szkudlinski@linux.intel.com>
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_INTEL_ADSP_MTL_TLB
#define ZEPHYR_INCLUDE_DRIVERS_INTEL_ADSP_MTL_TLB
/*
* This function will save contents of the physical memory banks into a provided storage buffer
*
* the system must be almost stopped. Operation is destructive - it will change physical to
* virtual addresses mapping leaving the system not operational
* Power states of memory banks will stay not touched
* assuming
* - the dcache memory had been invalidated before
* - no remapping of addresses below unused_l2_sram_start_marker has been made
* (this is ensured by the driver itself - it rejects such remapping request)
*
* at this point the memory is still up&running so its safe to use libraries like memcpy
* and the procedure can be called in a zephyr driver model way
*/
typedef void (*mm_save_context)(void *storage_buffer);
/*
* This function will return a required size of storage buffer needed to perform context save
*
*/
typedef uint32_t (*mm_get_storage_size)(void);
/*
* This function will restore the contents and power state of the physical memory banks
* and recreate physical to virtual mappings
*
* As the system memory is down at this point, the procedure
* - MUST be located in IMR memory region
* - MUST be called using a simple extern procedure call - API table is not yet loaded
* - MUST NOT use libraries, like memcpy, use instead a special version bmemcpy located in IMR
*
*/
void adsp_mm_restore_context(void *storage_buffer);
struct intel_adsp_tlb_api {
mm_save_context save_context;
mm_get_storage_size get_storage_size;
};
#endif /* ZEPHYR_INCLUDE_DRIVERS_INTEL_ADSP_MTL_TLB */
``` | /content/code_sandbox/include/zephyr/drivers/mm/mm_drv_intel_adsp_mtl_tlb.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 407 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_RAT_H_
#define ZEPHYR_INCLUDE_RAT_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#define ADDR_TRANSLATE_MAX_REGIONS (16u)
#define RAT_CTRL(base_addr, i) (base_addr + 0x20 + 0x10 * (i))
#define RAT_BASE(base_addr, i) (base_addr + 0x24 + 0x10 * (i))
#define RAT_TRANS_L(base_addr, i) (base_addr + 0x28 + 0x10 * (i))
#define RAT_TRANS_H(base_addr, i) (base_addr + 0x2C + 0x10 * (i))
#define RAT_CTRL_W(enable, size) (((enable & 0x1) << 31u) | (size & 0x3F))
/**
* @brief Enum's to represent different possible region size for the address translate module
*/
enum address_trans_region_size {
address_trans_region_size_1 = 0x0,
address_trans_region_size_2,
address_trans_region_size_4,
address_trans_region_size_8,
address_trans_region_size_16,
address_trans_region_size_32,
address_trans_region_size_64,
address_trans_region_size_128,
address_trans_region_size_256,
address_trans_region_size_512,
address_trans_region_size_1K,
address_trans_region_size_2K,
address_trans_region_size_4K,
address_trans_region_size_8K,
address_trans_region_size_16K,
address_trans_region_size_32K,
address_trans_region_size_64K,
address_trans_region_size_128K,
address_trans_region_size_256K,
address_trans_region_size_512K,
address_trans_region_size_1M,
address_trans_region_size_2M,
address_trans_region_size_4M,
address_trans_region_size_8M,
address_trans_region_size_16M,
address_trans_region_size_32M,
address_trans_region_size_64M,
address_trans_region_size_128M,
address_trans_region_size_256M,
address_trans_region_size_512M,
address_trans_region_size_1G,
address_trans_region_size_2G,
address_trans_region_size_4G
};
/**
* @brief Region config structure
*/
struct address_trans_region_config {
uint64_t system_addr;
uint32_t local_addr;
uint32_t size;
};
/**
* @brief Parameters for address_trans_init
*/
struct address_trans_params {
uint32_t num_regions;
uint32_t rat_base_addr;
struct address_trans_region_config *region_config;
};
void sys_mm_drv_ti_rat_init(void *region_config, uint64_t rat_base_addr, uint8_t translate_regions);
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_RAT_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/mm/rat.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 591 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_I3C_CCC_H_
#define ZEPHYR_INCLUDE_DRIVERS_I3C_CCC_H_
/**
* @brief I3C Common Command Codes
* @defgroup i3c_ccc I3C Common Command Codes
* @ingroup i3c_interface
* @{
*/
#include <stdint.h>
#include <zephyr/device.h>
#include <zephyr/toolchain.h>
#include <zephyr/sys/util.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Maximum CCC ID for broadcast */
#define I3C_CCC_BROADCAST_MAX_ID 0x7FU
/**
* Enable Events Command
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_ENEC(broadcast) ((broadcast) ? 0x00U : 0x80U)
/**
* Disable Events Command
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_DISEC(broadcast) ((broadcast) ? 0x01U : 0x81U)
/**
* Enter Activity State
*
* @param as Desired activity state
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_ENTAS(as, broadcast) (((broadcast) ? 0x02U : 0x82U) + (as))
/**
* Enter Activity State 0
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_ENTAS0(broadcast) I3C_CCC_ENTAS(0, broadcast)
/**
* Enter Activity State 1
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_ENTAS1(broadcast) I3C_CCC_ENTAS(1, broadcast)
/**
* Enter Activity State 2
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_ENTAS2(broadcast) I3C_CCC_ENTAS(2, broadcast)
/**
* Enter Activity State 3
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_ENTAS3(broadcast) I3C_CCC_ENTAS(3, broadcast)
/** Reset Dynamic Address Assignment (Broadcast) */
#define I3C_CCC_RSTDAA 0x06U
/** Enter Dynamic Address Assignment (Broadcast) */
#define I3C_CCC_ENTDAA 0x07U
/** Define List of Targets (Broadcast) */
#define I3C_CCC_DEFTGTS 0x08U
/**
* Set Max Write Length (Broadcast or Direct)
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_SETMWL(broadcast) ((broadcast) ? 0x09U : 0x89U)
/**
* Set Max Read Length (Broadcast or Direct)
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_SETMRL(broadcast) ((broadcast) ? 0x0AU : 0x8AU)
/** Enter Test Mode (Broadcast) */
#define I3C_CCC_ENTTM 0x0BU
/** Set Bus Context (Broadcast) */
#define I3C_CCC_SETBUSCON 0x0CU
/**
* Data Transfer Ending Procedure Control
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_ENDXFER(broadcast) ((broadcast) ? 0x12U : 0x92U)
/** Enter HDR Mode (HDR-DDR) (Broadcast) */
#define I3C_CCC_ENTHDR(x) (0x20U + (x))
/** Enter HDR Mode 0 (HDR-DDR) (Broadcast) */
#define I3C_CCC_ENTHDR0 0x20U
/** Enter HDR Mode 1 (HDR-TSP) (Broadcast) */
#define I3C_CCC_ENTHDR1 0x21U
/** Enter HDR Mode 2 (HDR-TSL) (Broadcast) */
#define I3C_CCC_ENTHDR2 0x22U
/** Enter HDR Mode 3 (HDR-BT) (Broadcast) */
#define I3C_CCC_ENTHDR3 0x23U
/** Enter HDR Mode 4 (Broadcast) */
#define I3C_CCC_ENTHDR4 0x24U
/** Enter HDR Mode 5 (Broadcast) */
#define I3C_CCC_ENTHDR5 0x25U
/** Enter HDR Mode 6 (Broadcast) */
#define I3C_CCC_ENTHDR6 0x26U
/** Enter HDR Mode 7 (Broadcast) */
#define I3C_CCC_ENTHDR7 0x27U
/**
* Exchange Timing Information (Broadcast or Direct)
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_SETXTIME(broadcast) ((broadcast) ? 0x28U : 0x98U)
/** Set All Addresses to Static Addresses (Broadcast) */
#define I3C_CCC_SETAASA 0x29U
/**
* Target Reset Action
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_RSTACT(broadcast) ((broadcast) ? 0x2AU : 0x9AU)
/** Define List of Group Address (Broadcast) */
#define I3C_CCC_DEFGRPA 0x2BU
/**
* Reset Group Address
*
* @param broadcast True if broadcast, false if direct.
*/
#define I3C_CCC_RSTGRPA(broadcast) ((broadcast) ? 0x2CU : 0x9CU)
/** Multi-Lane Data Transfer Control (Broadcast) */
#define I3C_CCC_MLANE(broadcast) ((broadcast) ? 0x2DU : 0x9DU)
/**
* Vendor/Standard Extension
*
* @param broadcast True if broadcast, false if direct.
* @param id Extension ID.
*/
#define I3C_CCC_VENDOR(broadcast, id) ((id) + ((broadcast) ? 0x61U : 0xE0U))
/** Set Dynamic Address from Static Address (Direct) */
#define I3C_CCC_SETDASA 0x87U
/** Set New Dynamic Address (Direct) */
#define I3C_CCC_SETNEWDA 0x88U
/** Get Max Write Length (Direct) */
#define I3C_CCC_GETMWL 0x8BU
/** Get Max Read Length (Direct) */
#define I3C_CCC_GETMRL 0x8CU
/** Get Provisioned ID (Direct) */
#define I3C_CCC_GETPID 0x8DU
/** Get Bus Characteristics Register (Direct) */
#define I3C_CCC_GETBCR 0x8EU
/** Get Device Characteristics Register (Direct) */
#define I3C_CCC_GETDCR 0x8FU
/** Get Device Status (Direct) */
#define I3C_CCC_GETSTATUS 0x90U
/** Get Accept Controller Role (Direct) */
#define I3C_CCC_GETACCCR 0x91U
/** Set Bridge Targets (Direct) */
#define I3C_CCC_SETBRGTGT 0x93U
/** Get Max Data Speed (Direct) */
#define I3C_CCC_GETMXDS 0x94U
/** Get Optional Feature Capabilities (Direct) */
#define I3C_CCC_GETCAPS 0x95U
/** Set Route (Direct) */
#define I3C_CCC_SETROUTE 0x96U
/** Device to Device(s) Tunneling Control (Direct) */
#define I3C_CCC_D2DXFER 0x97U
/** Get Exchange Timing Information (Direct) */
#define I3C_CCC_GETXTIME 0x99U
/** Set Group Address (Direct) */
#define I3C_CCC_SETGRPA 0x9BU
struct i3c_device_desc;
/**
* @brief Payload structure for Direct CCC to one target.
*/
struct i3c_ccc_target_payload {
/** Target address */
uint8_t addr;
/** @c 0 for Write, @c 1 for Read */
uint8_t rnw:1;
/**
* - For Write CCC, pointer to the byte array of data
* to be sent, which may contain the Sub-Command Byte
* and additional data.
* - For Read CCC, pointer to the byte buffer for data
* to be read into.
*/
uint8_t *data;
/** Length in bytes for @p data. */
size_t data_len;
/**
* Total number of bytes transferred
*
* A Target can issue an EoD or the Controller can abort a transfer
* before the length of the buffer. It is expected for the driver to
* write to this after the transfer.
*/
size_t num_xfer;
};
/**
* @brief Payload structure for one CCC transaction.
*/
struct i3c_ccc_payload {
struct {
/**
* The CCC ID (@c I3C_CCC_*).
*/
uint8_t id;
/**
* Pointer to byte array of data for this CCC.
*
* This is the bytes following the CCC command in CCC frame.
* Set to @c NULL if no associated data.
*/
uint8_t *data;
/** Length in bytes for optional data array. */
size_t data_len;
/**
* Total number of bytes transferred
*
* A Controller can abort a transfer before the length of the buffer.
* It is expected for the driver to write to this after the transfer.
*/
size_t num_xfer;
} ccc;
struct {
/**
* Array of struct i3c_ccc_target_payload.
*
* Each element describes the target and associated
* payloads for this CCC.
*
* Use with Direct CCC.
*/
struct i3c_ccc_target_payload *payloads;
/** Number of targets */
size_t num_targets;
} targets;
};
/**
* @brief Payload for ENEC/DISEC CCC (Target Events Command).
*/
struct i3c_ccc_events {
/**
* Event byte:
* - Bit[0]: ENINT/DISINT:
* - Target Interrupt Requests
* - Bit[1]: ENCR/DISCR:
* - Controller Role Requests
* - Bit[3]: ENHJ/DISHJ:
* - Hot-Join Event
*/
uint8_t events;
} __packed;
/** Enable Events (ENEC) - Target Interrupt Requests. */
#define I3C_CCC_ENEC_EVT_ENINTR BIT(0)
/** Enable Events (ENEC) - Controller Role Requests. */
#define I3C_CCC_ENEC_EVT_ENCR BIT(1)
/** Enable Events (ENEC) - Hot-Join Event. */
#define I3C_CCC_ENEC_EVT_ENHJ BIT(3)
#define I3C_CCC_ENEC_EVT_ALL \
(I3C_CCC_ENEC_EVT_ENINTR | I3C_CCC_ENEC_EVT_ENCR | I3C_CCC_ENEC_EVT_ENHJ)
/** Disable Events (DISEC) - Target Interrupt Requests. */
#define I3C_CCC_DISEC_EVT_DISINTR BIT(0)
/** Disable Events (DISEC) - Controller Role Requests. */
#define I3C_CCC_DISEC_EVT_DISCR BIT(1)
/** Disable Events (DISEC) - Hot-Join Event. */
#define I3C_CCC_DISEC_EVT_DISHJ BIT(3)
#define I3C_CCC_DISEC_EVT_ALL \
(I3C_CCC_DISEC_EVT_DISINTR | I3C_CCC_DISEC_EVT_DISCR | I3C_CCC_DISEC_EVT_DISHJ)
/*
* Events for both enabling and disabling since
* they have the same bits.
*/
/** Events - Target Interrupt Requests. */
#define I3C_CCC_EVT_INTR BIT(0)
/** Events - Controller Role Requests. */
#define I3C_CCC_EVT_CR BIT(1)
/** Events - Hot-Join Event. */
#define I3C_CCC_EVT_HJ BIT(3)
/** Bitmask for all events. */
#define I3C_CCC_EVT_ALL \
(I3C_CCC_EVT_INTR | I3C_CCC_EVT_CR | I3C_CCC_EVT_HJ)
/**
* @brief Payload for SETMWL/GETMWL CCC (Set/Get Maximum Write Length).
*
* @note For drivers and help functions, the raw data coming
* back from target device is in big endian. This needs to be
* translated back to CPU endianness before passing back to
* function caller.
*/
struct i3c_ccc_mwl {
/** Maximum Write Length */
uint16_t len;
} __packed;
/**
* @brief Payload for SETMRL/GETMRL CCC (Set/Get Maximum Read Length).
*
* @note For drivers and help functions, the raw data coming
* back from target device is in big endian. This needs to be
* translated back to CPU endianness before passing back to
* function caller.
*/
struct i3c_ccc_mrl {
/** Maximum Read Length */
uint16_t len;
/** Optional IBI Payload Size */
uint8_t ibi_len;
} __packed;
/**
* @brief The active controller part of payload for DEFTGTS CCC.
*
* This is used by DEFTGTS (Define List of Targets) CCC to describe
* the active controller on the I3C bus.
*/
struct i3c_ccc_deftgts_active_controller {
/** Dynamic Address of Active Controller */
uint8_t addr;
/** Device Characteristic Register of Active Controller */
uint8_t dcr;
/** Bus Characteristic Register of Active Controller */
uint8_t bcr;
/** Static Address of Active Controller */
uint8_t static_addr;
};
/**
* @brief The target device part of payload for DEFTGTS CCC.
*
* This is used by DEFTGTS (Define List of Targets) CCC to describe
* the existing target devices on the I3C bus.
*/
struct i3c_ccc_deftgts_target {
/** Dynamic Address of a target device, or a group address */
uint8_t addr;
union {
/**
* Device Characteristic Register of a I3C target device
* or a group.
*/
uint8_t dcr;
/** Legacy Virtual Register for legacy I2C device. */
uint8_t lvr;
};
/** Bus Characteristic Register of a target device or a group */
uint8_t bcr;
/** Static Address of a target device or a group */
uint8_t static_addr;
};
/**
* @brief Payload for DEFTGTS CCC (Define List of Targets).
*
* @note @p i3c_ccc_deftgts_target is an array of targets, where
* the number of elements is dependent on the number of I3C targets
* on the bus. Please have enough space for both read and write of
* this CCC.
*/
struct i3c_ccc_deftgts {
/** Data describing the active controller */
struct i3c_ccc_deftgts_active_controller active_controller;
/** Data describing the target(s) on the bus */
struct i3c_ccc_deftgts_target targets[];
} __packed;
/**
* @brief Payload for a single device address.
*
* This is used for:
* - SETDASA (Set Dynamic Address from Static Address)
* - SETNEWDA (Set New Dynamic Address)
* - SETGRPA (Set Group Address)
* - GETACCCR (Get Accept Controller Role)
*
* Note that the target address is encoded within
* struct i3c_ccc_target_payload instead of being encoded in
* this payload.
*/
struct i3c_ccc_address {
/**
* - For SETDASA, Static Address to be assigned as
* Dynamic Address.
* - For SETNEWDA, new Dynamic Address to be assigned.
* - For SETGRPA, new Group Address to be set.
* - For GETACCCR, the correct address of Secondary
* Controller.
*
* @note For SETDATA, SETNEWDA and SETGRAP,
* the address is left-shift by 1, and bit[0] is always 0.
*
* @note Fpr SET GETACCCR, the address is left-shift by 1,
* and bit[0] is the calculated odd parity bit.
*/
uint8_t addr;
} __packed;
/**
* @brief Payload for GETPID CCC (Get Provisioned ID).
*/
struct i3c_ccc_getpid {
/**
* 48-bit Provisioned ID.
*
* @note Data is big-endian where first byte is MSB.
*/
uint8_t pid[6];
} __packed;
/**
* @brief Payload for GETBCR CCC (Get Bus Characteristics Register).
*/
struct i3c_ccc_getbcr {
/** Bus Characteristics Register */
uint8_t bcr;
} __packed;
/**
* @brief Payload for GETDCR CCC (Get Device Characteristics Register).
*/
struct i3c_ccc_getdcr {
/** Device Characteristics Register */
uint8_t dcr;
} __packed;
/**
* @brief Indicate which format of GETSTATUS to use.
*/
enum i3c_ccc_getstatus_fmt {
/** GETSTATUS Format 1 */
GETSTATUS_FORMAT_1,
/** GETSTATUS Format 2 */
GETSTATUS_FORMAT_2,
};
/**
* @brief Defining byte values for GETSTATUS Format 2.
*/
enum i3c_ccc_getstatus_defbyte {
/** Target status. */
GETSTATUS_FORMAT_2_TGTSTAT = 0x00U,
/** PRECR - Alternate status format describing Controller-capable device. */
GETSTATUS_FORMAT_2_PRECR = 0x91U,
/** Invalid defining byte. */
GETSTATUS_FORMAT_2_INVALID = 0x100U
};
/**
* @brief Payload for GETSTATUS CCC (Get Device Status).
*/
union i3c_ccc_getstatus {
struct {
/**
* Device Status
* - Bit[15:8]: Reserved.
* - Bit[7:6]: Activity Mode.
* - Bit[5]: Protocol Error.
* - Bit[4]: Reserved.
* - Bit[3:0]: Number of Pending Interrupts.
*
* @note For drivers and help functions, the raw data coming
* back from target device is in big endian. This needs to be
* translated back to CPU endianness before passing back to
* function caller.
*/
uint16_t status;
} fmt1;
union {
/**
* Defining Byte 0x00: TGTSTAT
*
* @see i3c_ccc_getstatus::fmt1::status
*/
uint16_t tgtstat;
/**
* Defining Byte 0x91: PRECR
* - Bit[15:8]: Vendor Reserved
* - Bit[7:2]: Reserved
* - Bit[1]: Handoff Delay NACK
* - Bit[0]: Deep Sleep Detected
*
* @note For drivers and help functions, the raw data coming
* back from target device is in big endian. This needs to be
* translated back to CPU endianness before passing back to
* function caller.
*/
uint16_t precr;
uint16_t raw_u16;
} fmt2;
} __packed;
/** GETSTATUS Format 1 - Protocol Error bit. */
#define I3C_CCC_GETSTATUS_PROTOCOL_ERR BIT(5)
/** GETSTATUS Format 1 - Activity Mode bitmask. */
#define I3C_CCC_GETSTATUS_ACTIVITY_MODE_MASK GENMASK(7U, 6U)
/**
* @brief GETSTATUS Format 1 - Activity Mode
*
* Obtain Activity Mode from GETSTATUS Format 1 value obtained via
* GETSTATUS.
*
* @param status GETSTATUS Format 1 value
*/
#define I3C_CCC_GETSTATUS_ACTIVITY_MODE(status) \
FIELD_GET(I3C_CCC_GETSTATUS_ACTIVITY_MODE_MASK, (status))
/** GETSTATUS Format 1 - Number of Pending Interrupts bitmask. */
#define I3C_CCC_GETSTATUS_NUM_INT_MASK GENMASK(3U, 0U)
/**
* @brief GETSTATUS Format 1 - Number of Pending Interrupts
*
* Obtain Number of Pending Interrupts from GETSTATUS Format 1 value
* obtained via GETSTATUS.
*
* @param status GETSTATUS Format 1 value
*/
#define I3C_CCC_GETSTATUS_NUM_INT(status) \
FIELD_GET(I3C_CCC_GETSTATUS_NUM_INT_MASK, (status))
/** GETSTATUS Format 2 - PERCR - Deep Sleep Detected bit. */
#define I3C_CCC_GETSTATUS_PRECR_DEEP_SLEEP_DETECTED BIT(0)
/** GETSTATUS Format 2 - PERCR - Handoff Delay NACK. */
#define I3C_CCC_GETSTATUS_PRECR_HANDOFF_DELAY_NACK BIT(1)
/**
* @brief One Bridged Target for SETBRGTGT payload.
*/
struct i3c_ccc_setbrgtgt_tgt {
/**
* Dynamic address of the bridged target.
*
* @note The address is left-shift by 1, and bit[0]
* is always 0.
*/
uint8_t addr;
/**
* 16-bit ID for the bridged target.
*
* @note For drivers and help functions, the raw data coming
* back from target device is in big endian. This needs to be
* translated back to CPU endianness before passing back to
* function caller.
*/
uint16_t id;
} __packed;
/**
* @brief Payload for SETBRGTGT CCC (Set Bridge Targets).
*
* Note that the bridge target address is encoded within
* struct i3c_ccc_target_payload instead of being encoded in
* this payload.
*/
struct i3c_ccc_setbrgtgt {
/** Number of bridged targets */
uint8_t count;
/** Array of bridged targets */
struct i3c_ccc_setbrgtgt_tgt targets[];
} __packed;
/**
* @brief Payload for GETMXDS CCC (Get Max Data Speed).
*
* @note This is only for GETMXDS Format 1 and Format 2.
*/
union i3c_ccc_getmxds {
struct {
/** maxWr */
uint8_t maxwr;
/** maxRd */
uint8_t maxrd;
} fmt1;
struct {
/** maxWr */
uint8_t maxwr;
/** maxRd */
uint8_t maxrd;
/**
* Maximum Read Turnaround Time in microsecond.
*
* This is in little-endian where first byte is LSB.
*/
uint8_t maxrdturn[3];
} fmt2;
struct {
/**
* Defining Byte 0x00: WRRDTURN
*
* @see i3c_ccc_getmxds::fmt2
*/
uint8_t wrrdturn;
/**
* Defining Byte 0x91: CRHDLY
* - Bit[2]: Set Bus Activity State
* - Bit[1:0]: Controller Handoff Activity State
*/
uint8_t crhdly1;
} fmt3;
} __packed;
/** Get Max Data Speed (GETMXDS) - Default Max Sustained Data Rate. */
#define I3C_CCC_GETMXDS_MAX_SDR_FSCL_MAX 0
/** Get Max Data Speed (GETMXDS) - 8MHz Max Sustained Data Rate. */
#define I3C_CCC_GETMXDS_MAX_SDR_FSCL_8MHZ 1
/** Get Max Data Speed (GETMXDS) - 6MHz Max Sustained Data Rate. */
#define I3C_CCC_GETMXDS_MAX_SDR_FSCL_6MHZ 2
/** Get Max Data Speed (GETMXDS) - 4MHz Max Sustained Data Rate. */
#define I3C_CCC_GETMXDS_MAX_SDR_FSCL_4MHZ 3
/** Get Max Data Speed (GETMXDS) - 2MHz Max Sustained Data Rate. */
#define I3C_CCC_GETMXDS_MAX_SDR_FSCL_2MHZ 4
/** Get Max Data Speed (GETMXDS) - Clock to Data Turnaround <= 8ns. */
#define I3C_CCC_GETMXDS_TSCO_8NS 0
/** Get Max Data Speed (GETMXDS) - Clock to Data Turnaround <= 9ns. */
#define I3C_CCC_GETMXDS_TSCO_9NS 1
/** Get Max Data Speed (GETMXDS) - Clock to Data Turnaround <= 10ns. */
#define I3C_CCC_GETMXDS_TSCO_10NS 2
/** Get Max Data Speed (GETMXDS) - Clock to Data Turnaround <= 11ns. */
#define I3C_CCC_GETMXDS_TSCO_11NS 3
/** Get Max Data Speed (GETMXDS) - Clock to Data Turnaround <= 12ns. */
#define I3C_CCC_GETMXDS_TSCO_12NS 4
/** Get Max Data Speed (GETMXDS) - Clock to Data Turnaround > 12ns. */
#define I3C_CCC_GETMXDS_TSCO_GT_12NS 7
/** Get Max Data Speed (GETMXDS) - maxWr - Optional Defining Byte Support. */
#define I3C_CCC_GETMXDS_MAXWR_DEFINING_BYTE_SUPPORT BIT(3)
/** Get Max Data Speed (GETMXDS) - Max Sustained Data Rate bitmask. */
#define I3C_CCC_GETMXDS_MAXWR_MAX_SDR_FSCL_MASK GENMASK(2U, 0U)
/**
* @brief Get Max Data Speed (GETMXDS) - maxWr - Max Sustained Data Rate
*
* Obtain Max Sustained Data Rate value from GETMXDS maxWr value
* obtained via GETMXDS.
*
* @param maxwr GETMXDS maxWr value.
*/
#define I3C_CCC_GETMXDS_MAXWR_MAX_SDR_FSCL(maxwr) \
FIELD_GET(I3C_CCC_GETMXDS_MAXWR_MAX_SDR_FSCL_MASK, (maxwr))
/** Get Max Data Speed (GETMXDS) - maxRd - Write-to-Read Permits Stop Between. */
#define I3C_CCC_GETMXDS_MAXRD_W2R_PERMITS_STOP_BETWEEN BIT(6)
/** Get Max Data Speed (GETMXDS) - maxRd - Clock to Data Turnaround bitmask. */
#define I3C_CCC_GETMXDS_MAXRD_TSCO_MASK GENMASK(5U, 3U)
/**
* @brief Get Max Data Speed (GETMXDS) - maxRd - Clock to Data Turnaround
*
* Obtain Clock to Data Turnaround value from GETMXDS maxRd value
* obtained via GETMXDS.
*
* @param maxrd GETMXDS maxRd value.
*/
#define I3C_CCC_GETMXDS_MAXRD_TSCO(maxrd) \
FIELD_GET(I3C_CCC_GETMXDS_MAXRD_TSCO_MASK, (maxrd))
/** Get Max Data Speed (GETMXDS) - maxRd - Max Sustained Data Rate bitmask. */
#define I3C_CCC_GETMXDS_MAXRD_MAX_SDR_FSCL_MASK GENMASK(2U, 0U)
/**
* @brief Get Max Data Speed (GETMXDS) - maxRd - Max Sustained Data Rate
*
* Obtain Max Sustained Data Rate value from GETMXDS maxRd value
* obtained via GETMXDS.
*
* @param maxrd GETMXDS maxRd value.
*/
#define I3C_CCC_GETMXDS_MAXRD_MAX_SDR_FSCL(maxrd) \
FIELD_GET(I3C_CCC_GETMXDS_MAXRD_MAX_SDR_FSCL_MASK, (maxrd))
/** Get Max Data Speed (GETMXDS) - CRDHLY1 - Set Bus Activity State bit shift value. */
#define I3C_CCC_GETMXDS_CRDHLY1_SET_BUS_ACT_STATE BIT(2)
/** Get Max Data Speed (GETMXDS) - CRDHLY1 - Controller Handoff Activity State bitmask. */
#define I3C_CCC_GETMXDS_CRDHLY1_CTRL_HANDOFF_ACT_STATE_MASK GENMASK(1U, 0U)
/**
* @brief Get Max Data Speed (GETMXDS) - CRDHLY1 - Controller Handoff Activity State
*
* Obtain Controller Handoff Activity State value from GETMXDS value
* obtained via GETMXDS.
*
* @param crhdly1 GETMXDS value.
*/
#define I3C_CCC_GETMXDS_CRDHLY1_CTRL_HANDOFF_ACT_STATE(crhdly1) \
FIELD_GET(I3C_CCC_GETMXDS_CRDHLY1_CTRL_HANDOFF_ACT_STATE_MASK, (chrdly1))
/**
* @brief Indicate which format of GETCAPS to use.
*/
enum i3c_ccc_getcaps_fmt {
/** GETCAPS Format 1 */
GETCAPS_FORMAT_1,
/** GETCAPS Format 2 */
GETCAPS_FORMAT_2,
};
/**
* @brief Enum for I3C Get Capabilities (GETCAPS) Format 2 Defining Byte Values.
*/
enum i3c_ccc_getcaps_defbyte {
/** Standard Target capabilities and features. */
GETCAPS_FORMAT_2_TGTCAPS = 0x00U,
/** Fixed 32b test pattern. */
GETCAPS_FORMAT_2_TESTPAT = 0x5AU,
/** Controller handoff capabilities and features. */
GETCAPS_FORMAT_2_CRCAPS = 0x91U,
/** Virtual Target capabilities and features. */
GETCAPS_FORMAT_2_VTCAPS = 0x93U,
/** Debug-capable Device capabilities and features. */
GETCAPS_FORMAT_2_DBGCAPS = 0xD7U,
/** Invalid defining byte. */
GETCAPS_FORMAT_2_INVALID = 0x100,
};
/**
* @brief Payload for GETCAPS CCC (Get Optional Feature Capabilities).
*
* @note Only supports GETCAPS Format 1 and Format 2. In I3C v1.0 this was
* GETHDRCAP which only returned a single byte which is the same as the
* GETCAPS1 byte.
*/
union i3c_ccc_getcaps {
union {
/**
* I3C v1.0 HDR Capabilities
* - Bit[0]: HDR-DDR
* - Bit[1]: HDR-TSP
* - Bit[2]: HDR-TSL
* - Bit[7:3]: Reserved
*/
uint8_t gethdrcap;
/**
* I3C v1.1+ Device Capabilities
* Byte 1 GETCAPS1
* - Bit[0]: HDR-DDR
* - Bit[1]: HDR-TSP
* - Bit[2]: HDR-TSL
* - Bit[3]: HDR-BT
* - Bit[7:4]: Reserved
* Byte 2 GETCAPS2
* - Bit[3:0]: I3C 1.x Specification Version
* - Bit[5:4]: Group Address Capabilities
* - Bit[6]: HDR-DDR Write Abort
* - Bit[7]: HDR-DDR Abort CRC
* Byte 3 GETCAPS3
* - Bit[0]: Multi-Lane (ML) Data Transfer Support
* - Bit[1]: Device to Device Transfer (D2DXFER) Support
* - Bit[2]: Device to Device Transfer (D2DXFER) IBI Capable
* - Bit[3]: Defining Byte Support in GETCAPS
* - Bit[4]: Defining Byte Support in GETSTATUS
* - Bit[5]: HDR-BT CRC-32 Support
* - Bit[6]: IBI MDB Support for Pending Read Notification
* - Bit[7]: Reserved
* Byte 4 GETCAPS4
* - Bit[7:0]: Reserved
*/
uint8_t getcaps[4];
} fmt1;
union {
/**
* Defining Byte 0x00: TGTCAPS
*
* @see i3c_ccc_getcaps::fmt1::getcaps
*/
uint8_t tgtcaps[4];
/**
* Defining Byte 0x5A: TESTPAT
*
* @note should always be 0xA55AA55A in big endian
*/
uint32_t testpat;
/**
* Defining Byte 0x91: CRCAPS
* Byte 1 CRCAPS1
* - Bit[0]: Hot-Join Support
* - Bit[1]: Group Management Support
* - Bit[2]: Multi-Lane Support
* Byte 2 CRCAPS2
* - Bit[0]: In-Band Interrupt Support
* - Bit[1]: Controller Pass-Back
* - Bit[2]: Deep Sleep Capable
* - Bit[3]: Delayed Controller Handoff
*/
uint8_t crcaps[2];
/**
* Defining Byte 0x93: VTCAPS
* Byte 1 VTCAPS1
* - Bit[2:0]: Virtual Target Type
* - Bit[4]: Side Effects
* - Bit[5]: Shared Peripheral Detect
* Byte 2 VTCAPS2
* - Bit[1:0]: Interrupt Requests
* - Bit[2]: Address Remapping
* - Bit[4:3]: Bus Context and Conditions
*/
uint8_t vtcaps[2];
} fmt2;
} __packed;
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR-DDR mode bit. */
#define I3C_CCC_GETCAPS1_HDR_DDR BIT(0)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR-TSP mode bit. */
#define I3C_CCC_GETCAPS1_HDR_TSP BIT(1)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR-TSL mode bit. */
#define I3C_CCC_GETCAPS1_HDR_TSL BIT(2)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR-BT mode bit. */
#define I3C_CCC_GETCAPS1_HDR_BT BIT(3)
/**
* @brief Get Optional Feature Capabilities Byte 1 (GETCAPS) - HDR Mode
*
* Get the bit corresponding to HDR mode.
*
* @param x HDR mode
*/
#define I3C_CCC_GETCAPS1_HDR_MODE(x) BIT(x)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR Mode 0. */
#define I3C_CCC_GETCAPS1_HDR_MODE0 BIT(0)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR Mode 1. */
#define I3C_CCC_GETCAPS1_HDR_MODE1 BIT(1)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR Mode 2. */
#define I3C_CCC_GETCAPS1_HDR_MODE2 BIT(2)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR Mode 3. */
#define I3C_CCC_GETCAPS1_HDR_MODE3 BIT(3)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR Mode 4. */
#define I3C_CCC_GETCAPS1_HDR_MODE4 BIT(4)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR Mode 5. */
#define I3C_CCC_GETCAPS1_HDR_MODE5 BIT(5)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR Mode 6. */
#define I3C_CCC_GETCAPS1_HDR_MODE6 BIT(6)
/** Get Optional Feature Capabilities Byte 1 (GETCAPS) Format 1 - HDR Mode 7. */
#define I3C_CCC_GETCAPS1_HDR_MODE7 BIT(7)
/** Get Optional Feature Capabilities Byte 2 (GETCAPS) Format 1 - HDR-DDR Write Abort bit. */
#define I3C_CCC_GETCAPS2_HDRDDR_WRITE_ABORT BIT(6)
/** Get Optional Feature Capabilities Byte 2 (GETCAPS) Format 1 - HDR-DDR Abort CRC bit. */
#define I3C_CCC_GETCAPS2_HDRDDR_ABORT_CRC BIT(7)
/**
* @brief Get Optional Feature Capabilities Byte 2 (GETCAPS) Format 1 -
* Group Address Capabilities bitmask.
*/
#define I3C_CCC_GETCAPS2_GRPADDR_CAP_MASK GENMASK(5U, 4U)
/**
* @brief Get Optional Feature Capabilities Byte 2 (GETCAPS) Format 1 - Group Address Capabilities.
*
* Obtain Group Address Capabilities value from GETCAPS Format 1 value
* obtained via GETCAPS.
*
* @param getcaps2 GETCAPS2 value.
*/
#define I3C_CCC_GETCAPS2_GRPADDR_CAP(getcaps2) \
FIELD_GET(I3C_CCC_GETCAPS2_GRPADDR_CAP_MASK, (getcaps2))
/**
* @brief Get Optional Feature Capabilities Byte 2 (GETCAPS) Format 1 -
* I3C 1.x Specification Version bitmask.
*/
#define I3C_CCC_GETCAPS2_SPEC_VER_MASK GENMASK(3U, 0U)
/**
* @brief Get Optional Feature Capabilities Byte 2 (GETCAPS) Format 1 -
* I3C 1.x Specification Version.
*
* Obtain I3C 1.x Specification Version value from GETCAPS Format 1 value
* obtained via GETCAPS.
*
* @param getcaps2 GETCAPS2 value.
*/
#define I3C_CCC_GETCAPS2_SPEC_VER(getcaps2) \
FIELD_GET(I3C_CCC_GETCAPS2_SPEC_VER_MASK, (getcaps2))
/**
* @brief Get Optional Feature Capabilities Byte 3 (GETCAPS) Format 1 -
* Multi-Lane Data Transfer Support bit.
*/
#define I3C_CCC_GETCAPS3_MLANE_SUPPORT BIT(0)
/**
* @brief Get Optional Feature Capabilities Byte 3 (GETCAPS) Format 1 -
* Device to Device Transfer (D2DXFER) Support bit.
*/
#define I3C_CCC_GETCAPS3_D2DXFER_SUPPORT BIT(1)
/**
* @brief Get Optional Feature Capabilities Byte 3 (GETCAPS) Format 1 -
* Device to Device Transfer (D2DXFER) IBI Capable bit.
*/
#define I3C_CCC_GETCAPS3_D2DXFER_IBI_CAPABLE BIT(2)
/**
* @brief Get Optional Feature Capabilities Byte 3 (GETCAPS) Format 1 -
* Defining Byte Support in GETCAPS bit.
*/
#define I3C_CCC_GETCAPS3_GETCAPS_DEFINING_BYTE_SUPPORT BIT(3)
/**
* @brief Get Optional Feature Capabilities Byte 3 (GETCAPS) Format 1 -
* Defining Byte Support in GETSTATUS bit.
*/
#define I3C_CCC_GETCAPS3_GETSTATUS_DEFINING_BYTE_SUPPORT BIT(4)
/**
* @brief Get Optional Feature Capabilities Byte 3 (GETCAPS) Format 1 -
* HDR-BT CRC-32 Support bit.
*/
#define I3C_CCC_GETCAPS3_HDRBT_CRC32_SUPPORT BIT(5)
/**
* @brief Get Optional Feature Capabilities Byte 3 (GETCAPS) Format 1 -
* IBI MDB Support for Pending Read Notification bit.
*/
#define I3C_CCC_GETCAPS3_IBI_MDR_PENDING_READ_NOTIFICATION BIT(6)
/**
* @brief Get Fixed Test Pattern (GETCAPS) Format 2 -
* Fixed Test Pattern Byte 1.
*/
#define I3C_CCC_GETCAPS_TESTPAT1 0xA5
/**
* @brief Get Fixed Test Pattern (GETCAPS) Format 2 -
* Fixed Test Pattern Byte 2.
*/
#define I3C_CCC_GETCAPS_TESTPAT2 0x5A
/**
* @brief Get Fixed Test Pattern (GETCAPS) Format 2 -
* Fixed Test Pattern Byte 3.
*/
#define I3C_CCC_GETCAPS_TESTPAT3 0xA5
/**
* @brief Get Fixed Test Pattern (GETCAPS) Format 2 -
* Fixed Test Pattern Byte 4.
*/
#define I3C_CCC_GETCAPS_TESTPAT4 0x5A
/**
* @brief Get Fixed Test Pattern (GETCAPS) Format 2 -
* Fixed Test Pattern Word in Big Endian.
*/
#define I3C_CCC_GETCAPS_TESTPAT 0xA55AA55A
/**
* @brief Get Controller Handoff Capabilities Byte 1 (GETCAPS) Format 2 -
* Hot-Join Support.
*/
#define I3C_CCC_GETCAPS_CRCAPS1_HJ_SUPPORT BIT(0)
/**
* @brief Get Controller Handoff Capabilities Byte 1 (GETCAPS) Format 2 -
* Group Management Support.
*/
#define I3C_CCC_GETCAPS_CRCAPS1_GRP_MANAGEMENT_SUPPORT BIT(1)
/**
* @brief Get Controller Handoff Capabilities Byte 1 (GETCAPS) Format 2 -
* Multi-Lane Support.
*/
#define I3C_CCC_GETCAPS_CRCAPS1_ML_SUPPORT BIT(2)
/**
* @brief Get Controller Handoff Capabilities Byte 2 (GETCAPS) Format 2 -
* In-Band Interrupt Support.
*/
#define I3C_CCC_GETCAPS_CRCAPS2_IBI_TIR_SUPPORT BIT(0)
/**
* @brief Get Controller Handoff Capabilities Byte 2 (GETCAPS) Format 2 -
* Controller Pass-Back.
*/
#define I3C_CCC_GETCAPS_CRCAPS2_CONTROLLER_PASSBACK BIT(1)
/**
* @brief Get Controller Handoff Capabilities Byte 2 (GETCAPS) Format 2 -
* Deep Sleep Capable.
*/
#define I3C_CCC_GETCAPS_CRCAPS2_DEEP_SLEEP_CAPABLE BIT(2)
/**
* @brief Get Controller Handoff Capabilities Byte 2 (GETCAPS) Format 2 -
* Deep Sleep Capable.
*/
#define I3C_CCC_GETCAPS_CRCAPS2_DELAYED_CONTROLLER_HANDOFF BIT(3)
/** Get Capabilities (GETCAPS) - VTCAP1 - Virtual Target Type bitmask. */
#define I3C_CCC_GETCAPS_VTCAP1_VITRUAL_TARGET_TYPE_MASK GENMASK(2U, 0U)
/**
* @brief Get Capabilities (GETCAPS) - VTCAP1 - Virtual Target Type
*
* Obtain Virtual Target Type value from VTCAP1 value
* obtained via GETCAPS format 2 VTCAP def byte.
*
* @param vtcap1 VTCAP1 value.
*/
#define I3C_CCC_GETCAPS_VTCAP1_VITRUAL_TARGET_TYPE(vtcap1) \
FIELD_GET(I3C_CCC_GETCAPS_VTCAP1_VITRUAL_TARGET_TYPE_MASK, (vtcap1))
/**
* @brief Get Virtual Target Capabilities Byte 1 (GETCAPS) Format 2 -
* Side Effects.
*/
#define I3C_CCC_GETCAPS_VTCAP1_SIDE_EFFECTS BIT(4)
/**
* @brief Get Virtual Target Capabilities Byte 1 (GETCAPS) Format 2 -
* Shared Peripheral Detect.
*/
#define I3C_CCC_GETCAPS_VTCAP1_SHARED_PERIPH_DETECT BIT(5)
/** Get Capabilities (GETCAPS) - VTCAP2 - Interrupt Requests bitmask. */
#define I3C_CCC_GETCAPS_VTCAP2_INTERRUPT_REQUESTS_MASK GENMASK(1U, 0U)
/**
* @brief Get Capabilities (GETCAPS) - VTCAP2 - Interrupt Requests
*
* Obtain Interrupt Requests value from VTCAP2 value
* obtained via GETCAPS format 2 VTCAP def byte.
*
* @param vtcap2 VTCAP2 value.
*/
#define I3C_CCC_GETCAPS_VTCAP2_INTERRUPT_REQUESTS(vtcap2) \
FIELD_GET(I3C_CCC_GETCAPS_VTCAP2_INTERRUPT_REQUESTS_MASK, (vtcap2))
/**
* @brief Get Virtual Target Capabilities Byte 2 (GETCAPS) Format 2 -
* Address Remapping.
*/
#define I3C_CCC_GETCAPS_VTCAP2_ADDRESS_REMAPPING BIT(2)
/** Get Capabilities (GETCAPS) - VTCAP2 - Bus Context and Condition bitmask. */
#define I3C_CCC_GETCAPS_VTCAP2_BUS_CONTEXT_AND_COND_MASK GENMASK(4U, 3U)
/**
* @brief Get Capabilities (GETCAPS) - VTCAP2 - Bus Context and Condition
*
* Obtain Bus Context and Condition value from VTCAP2 value
* obtained via GETCAPS format 2 VTCAP def byte.
*
* @param vtcap2 VTCAP2 value.
*/
#define I3C_CCC_GETCAPS_VTCAP2_BUS_CONTEXT_AND_COND(vtcap2) \
FIELD_GET(I3C_CCC_GETCAPS_VTCAP2_BUS_CONTEXT_AND_COND_MASK, (vtcap2))
/**
* @brief Enum for I3C Reset Action (RSTACT) Defining Byte Values.
*/
enum i3c_ccc_rstact_defining_byte {
/** No Reset on Target Reset Pattern. */
I3C_CCC_RSTACT_NO_RESET = 0x00U,
/** Reset the I3C Peripheral Only. */
I3C_CCC_RSTACT_PERIPHERAL_ONLY = 0x01U,
/** Reset the Whole Target. */
I3C_CCC_RSTACT_RESET_WHOLE_TARGET = 0x02U,
/** Debug Network Adapter Reset. */
I3C_CCC_RSTACT_DEBUG_NETWORK_ADAPTER = 0x03U,
/** Virtual Target Detect. */
I3C_CCC_RSTACT_VIRTUAL_TARGET_DETECT = 0x04U,
};
/**
* @brief Test if I3C CCC payload is for broadcast.
*
* This tests if the CCC payload is for broadcast.
*
* @param[in] payload Pointer to the CCC payload.
*
* @retval true if payload target is broadcast
* @retval false if payload target is direct
*/
static inline bool i3c_ccc_is_payload_broadcast(const struct i3c_ccc_payload *payload)
{
return (payload->ccc.id <= I3C_CCC_BROADCAST_MAX_ID);
}
/**
* @brief Get BCR from a target
*
* Helper function to get BCR (Bus Characteristic Register) from
* target device.
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] bcr Pointer to the BCR payload structure.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_getbcr(struct i3c_device_desc *target,
struct i3c_ccc_getbcr *bcr);
/**
* @brief Get DCR from a target
*
* Helper function to get DCR (Device Characteristic Register) from
* target device.
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] dcr Pointer to the DCR payload structure.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_getdcr(struct i3c_device_desc *target,
struct i3c_ccc_getdcr *dcr);
/**
* @brief Get PID from a target
*
* Helper function to get PID (Provisioned ID) from
* target device.
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] pid Pointer to the PID payload structure.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_getpid(struct i3c_device_desc *target,
struct i3c_ccc_getpid *pid);
/**
* @brief Broadcast RSTACT to reset I3C Peripheral.
*
* Helper function to broadcast Target Reset Action (RSTACT) to
* all connected targets to Reset the I3C Peripheral Only (0x01).
*
* @param[in] controller Pointer to the controller device driver instance.
* @param[in] action What reset action to perform.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_rstact_all(const struct device *controller,
enum i3c_ccc_rstact_defining_byte action);
/**
* @brief Broadcast RSTDAA to reset dynamic addresses for all targets.
*
* Helper function to reset dynamic addresses of all connected targets.
*
* @param[in] controller Pointer to the controller device driver instance.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_rstdaa_all(const struct device *controller);
/**
* @brief Set Dynamic Address from Static Address for a target
*
* Helper function to do SETDASA (Set Dynamic Address from Static Address)
* for a particular target.
*
* Note this does not update @p target with the new dynamic address.
*
* @param[in] target Pointer to the target device descriptor where
* the device is configured with a static address.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_setdasa(const struct i3c_device_desc *target);
/**
* @brief Set New Dynamic Address for a target
*
* Helper function to do SETNEWDA(Set New Dynamic Address) for a particular target.
*
* Note this does not update @p target with the new dynamic address.
*
* @param[in] target Pointer to the target device descriptor where
* the device is configured with a static address.
* @param[in] new_da Pointer to the new_da struct.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_setnewda(const struct i3c_device_desc *target,
struct i3c_ccc_address new_da);
/**
* @brief Broadcast ENEC/DISEC to enable/disable target events.
*
* Helper function to broadcast Target Events Command to enable or
* disable target events (ENEC/DISEC).
*
* @param[in] controller Pointer to the controller device driver instance.
* @param[in] enable ENEC if true, DISEC if false.
* @param[in] events Pointer to the event struct.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_events_all_set(const struct device *controller,
bool enable, struct i3c_ccc_events *events);
/**
* @brief Direct CCC ENEC/DISEC to enable/disable target events.
*
* Helper function to send Target Events Command to enable or
* disable target events (ENEC/DISEC) on a single target.
*
* @param[in] target Pointer to the target device descriptor.
* @param[in] enable ENEC if true, DISEC if false.
* @param[in] events Pointer to the event struct.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_events_set(struct i3c_device_desc *target,
bool enable, struct i3c_ccc_events *events);
/**
* @brief Broadcast SETMWL to Set Maximum Write Length.
*
* Helper function to do SETMWL (Set Maximum Write Length) to
* all connected targets.
*
* @param[in] controller Pointer to the controller device driver instance.
* @param[in] mwl Pointer to SETMWL payload.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_setmwl_all(const struct device *controller,
const struct i3c_ccc_mwl *mwl);
/**
* @brief Single target SETMWL to Set Maximum Write Length.
*
* Helper function to do SETMWL (Set Maximum Write Length) to
* one target.
*
* @param[in] target Pointer to the target device descriptor.
* @param[in] mwl Pointer to SETMWL payload.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_setmwl(const struct i3c_device_desc *target,
const struct i3c_ccc_mwl *mwl);
/**
* @brief Single target GETMWL to Get Maximum Write Length.
*
* Helper function to do GETMWL (Get Maximum Write Length) of
* one target.
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] mwl Pointer to GETMWL payload.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_getmwl(const struct i3c_device_desc *target,
struct i3c_ccc_mwl *mwl);
/**
* @brief Broadcast SETMRL to Set Maximum Read Length.
*
* Helper function to do SETMRL (Set Maximum Read Length) to
* all connected targets.
*
* @param[in] controller Pointer to the controller device driver instance.
* @param[in] mrl Pointer to SETMRL payload.
* @param[in] has_ibi_size True if also sending the optional IBI payload
* size. False if not sending.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_setmrl_all(const struct device *controller,
const struct i3c_ccc_mrl *mrl,
bool has_ibi_size);
/**
* @brief Single target SETMRL to Set Maximum Read Length.
*
* Helper function to do SETMRL (Set Maximum Read Length) to
* one target.
*
* Note this uses the BCR of the target to determine whether
* to send the optional IBI payload size.
*
* @param[in] target Pointer to the target device descriptor.
* @param[in] mrl Pointer to SETMRL payload.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_setmrl(const struct i3c_device_desc *target,
const struct i3c_ccc_mrl *mrl);
/**
* @brief Single target GETMRL to Get Maximum Read Length.
*
* Helper function to do GETMRL (Get Maximum Read Length) of
* one target.
*
* Note this uses the BCR of the target to determine whether
* to send the optional IBI payload size.
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] mrl Pointer to GETMRL payload.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_getmrl(const struct i3c_device_desc *target,
struct i3c_ccc_mrl *mrl);
/**
* @brief Single target GETSTATUS to Get Target Status.
*
* Helper function to do GETSTATUS (Get Target Status) of
* one target.
*
* Note this uses the BCR of the target to determine whether
* to send the optional IBI payload size.
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] status Pointer to GETSTATUS payload.
* @param[in] fmt Which GETSTATUS to use.
* @param[in] defbyte Defining Byte if using format 2.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_getstatus(const struct i3c_device_desc *target,
union i3c_ccc_getstatus *status,
enum i3c_ccc_getstatus_fmt fmt,
enum i3c_ccc_getstatus_defbyte defbyte);
/**
* @brief Single target GETSTATUS to Get Target Status (Format 1).
*
* Helper function to do GETSTATUS (Get Target Status, format 1) of
* one target.
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] status Pointer to GETSTATUS payload.
*
* @return @see i3c_do_ccc
*/
static inline int i3c_ccc_do_getstatus_fmt1(const struct i3c_device_desc *target,
union i3c_ccc_getstatus *status)
{
return i3c_ccc_do_getstatus(target, status,
GETSTATUS_FORMAT_1,
GETSTATUS_FORMAT_2_INVALID);
}
/**
* @brief Single target GETSTATUS to Get Target Status (Format 2).
*
* Helper function to do GETSTATUS (Get Target Status, format 2) of
* one target.
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] status Pointer to GETSTATUS payload.
* @param[in] defbyte Defining Byte for GETSTATUS format 2.
*
* @return @see i3c_do_ccc
*/
static inline int i3c_ccc_do_getstatus_fmt2(const struct i3c_device_desc *target,
union i3c_ccc_getstatus *status,
enum i3c_ccc_getstatus_defbyte defbyte)
{
return i3c_ccc_do_getstatus(target, status,
GETSTATUS_FORMAT_2, defbyte);
}
/**
* @brief Single target GETCAPS to Get Target Status.
*
* Helper function to do GETCAPS (Get Capabilities) of
* one target.
*
* This should only be supported if Advanced Capabilities Bit of
* the BCR is set
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] caps Pointer to GETCAPS payload.
* @param[in] fmt Which GETCAPS to use.
* @param[in] defbyte Defining Byte if using format 2.
*
* @return @see i3c_do_ccc
*/
int i3c_ccc_do_getcaps(const struct i3c_device_desc *target,
union i3c_ccc_getcaps *caps,
enum i3c_ccc_getcaps_fmt fmt,
enum i3c_ccc_getcaps_defbyte defbyte);
/**
* @brief Single target GETCAPS to Get Capabilities (Format 1).
*
* Helper function to do GETCAPS (Get Capabilities, format 1) of
* one target.
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] caps Pointer to GETCAPS payload.
*
* @return @see i3c_do_ccc
*/
static inline int i3c_ccc_do_getcaps_fmt1(const struct i3c_device_desc *target,
union i3c_ccc_getcaps *caps)
{
return i3c_ccc_do_getcaps(target, caps,
GETCAPS_FORMAT_1,
GETCAPS_FORMAT_2_INVALID);
}
/**
* @brief Single target GETCAPS to Get Capabilities (Format 2).
*
* Helper function to do GETCAPS (Get Capabilities, format 2) of
* one target.
*
* @param[in] target Pointer to the target device descriptor.
* @param[out] caps Pointer to GETCAPS payload.
* @param[in] defbyte Defining Byte for GETCAPS format 2.
*
* @return @see i3c_do_ccc
*/
static inline int i3c_ccc_do_getcaps_fmt2(const struct i3c_device_desc *target,
union i3c_ccc_getcaps *caps,
enum i3c_ccc_getcaps_defbyte defbyte)
{
return i3c_ccc_do_getcaps(target, caps,
GETCAPS_FORMAT_2, defbyte);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_I3C_CCC_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/i3c/ccc.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 13,160 |
```objective-c
/*
*
*/
/**
* @file
* @brief Memory Management Driver APIs
*
* This contains APIs for a system-wide memory management
* driver. Only one instance is permitted on the system.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_SYSTEM_MM_H_
#define ZEPHYR_INCLUDE_DRIVERS_SYSTEM_MM_H_
#include <zephyr/types.h>
#ifndef _ASMLANGUAGE
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Memory Management Driver APIs
* @defgroup mm_drv_apis Memory Management Driver APIs
*
* This contains APIs for a system-wide memory management
* driver. Only one instance is permitted on the system.
*
* @ingroup memory_management
* @{
*/
/**
* @name Caching mode definitions.
*
* These are mutually exclusive.
*
* @{
*/
/** No caching */
#define SYS_MM_MEM_CACHE_NONE 2
/** Write-through caching */
#define SYS_MM_MEM_CACHE_WT 1
/** Full write-back caching */
#define SYS_MM_MEM_CACHE_WB 0
/** Reserved bits for cache modes */
#define SYS_MM_MEM_CACHE_MASK (BIT(3) - 1)
/**
* @}
*/
/**
* @name Region permission attributes.
*
* Default should be read-only, no user, no exec.
*
* @{
*/
/** Region will have read/write access (and not read-only) */
#define SYS_MM_MEM_PERM_RW BIT(3)
/** Region will be executable (normally forbidden) */
#define SYS_MM_MEM_PERM_EXEC BIT(4)
/** Region will be accessible to user mode (normally supervisor-only) */
#define SYS_MM_MEM_PERM_USER BIT(5)
/**
* @}
*/
/**
* @name Memory Mapping and Unmapping
*
* On mapping and unmapping of memory.
*
* @{
*/
/**
* @brief Map one physical page into the virtual address space
*
* This maps one physical page into the virtual address space.
* Behavior when providing unaligned address is undefined, this
* is assumed to be page aligned.
*
* The memory range itself is never accessed by this operation.
*
* This API must be safe to call in ISRs or exception handlers. Calls
* to this API are assumed to be serialized.
*
* @param virt Page-aligned destination virtual address to map
* @param phys Page-aligned source physical address to map
* @param flags Caching, access and control flags, see SYS_MM_MEM_* macros
*
* @retval 0 if successful
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if virtual address has already been mapped
*/
int sys_mm_drv_map_page(void *virt, uintptr_t phys, uint32_t flags);
/**
* @brief Map a region of physical memory into the virtual address space
*
* This maps a region of physical memory into the virtual address space.
* Behavior when providing unaligned addresses/sizes is undefined, these
* are assumed to be page aligned.
*
* The memory range itself is never accessed by this operation.
*
* This API must be safe to call in ISRs or exception handlers. Calls
* to this API are assumed to be serialized.
*
* @param virt Page-aligned destination virtual address to map
* @param phys Page-aligned source physical address to map
* @param size Page-aligned size of the mapped memory region in bytes
* @param flags Caching, access and control flags, see SYS_MM_MEM_* macros
*
* @retval 0 if successful
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if any virtual addresses have already been mapped
*/
int sys_mm_drv_map_region(void *virt, uintptr_t phys,
size_t size, uint32_t flags);
/**
* @brief Map an array of physical memory into the virtual address space
*
* This maps an array of physical pages into a continuous virtual address
* space. Behavior when providing unaligned addresses is undefined, these
* are assumed to be page aligned.
*
* The physical memory pages are never accessed by this operation.
*
* This API must be safe to call in ISRs or exception handlers. Calls
* to this API are assumed to be serialized.
*
* @param virt Page-aligned destination virtual address to map
* @param phys Array of pge-aligned source physical address to map
* @param cnt Number of elements in the physical page array
* @param flags Caching, access and control flags, see SYS_MM_MEM_* macros
*
* @retval 0 if successful
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if any virtual addresses have already been mapped
*/
int sys_mm_drv_map_array(void *virt, uintptr_t *phys,
size_t cnt, uint32_t flags);
/**
* @brief Remove mapping for one page of the provided virtual address
*
* This unmaps one page from the virtual address space.
*
* When this completes, the relevant translation table entries will be
* updated as if no mapping was ever made for that memory page. No previous
* context needs to be preserved. This function must update mapping in
* all active translation tables.
*
* Behavior when providing unaligned address is undefined, this
* is assumed to be page aligned.
*
* Implementations must invalidate translation caching as necessary.
*
* @param virt Page-aligned virtual address to un-map
*
* @retval 0 if successful
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if virtual address is not mapped
*/
int sys_mm_drv_unmap_page(void *virt);
/**
* @brief Remove mappings for a provided virtual address range
*
* This unmaps pages in the provided virtual address range.
*
* When this completes, the relevant translation table entries will be
* updated as if no mapping was ever made for that memory range. No previous
* context needs to be preserved. This function must update mappings in
* all active translation tables.
*
* Behavior when providing unaligned address is undefined, this
* is assumed to be page aligned.
*
* Implementations must invalidate translation caching as necessary.
*
* @param virt Page-aligned base virtual address to un-map
* @param size Page-aligned region size
*
* @retval 0 if successful
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if virtual address is not mapped
*/
int sys_mm_drv_unmap_region(void *virt, size_t size);
/**
* @brief Remap virtual pages into new address
*
* This remaps a virtual memory region starting at @p virt_old
* of size @p size into a new virtual memory region starting at
* @p virt_new. In other words, physical memory at @p virt_old is
* remapped to appear at @p virt_new. Both addresses must be page
* aligned and valid.
*
* Note that the virtual memory at both the old and new addresses
* must be unmapped in the memory domains of any runnable Zephyr
* thread as this does not deal with memory domains.
*
* Note that overlapping of old and new virtual memory regions
* is usually not supported for simpler implementation. Refer to
* the actual driver to make sure if overlapping is allowed.
*
* @param virt_old Page-aligned base virtual address of existing memory
* @param size Page-aligned size of the mapped memory region in bytes
* @param virt_new Page-aligned base virtual address to which to remap
* the memory
*
* @retval 0 if successful
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if old virtual addresses are not all mapped or
* new virtual addresses are not all unmapped
*/
int sys_mm_drv_remap_region(void *virt_old, size_t size, void *virt_new);
/**
* @}
*/
/**
* @name Memory Moving
*
* On moving already mapped memory.
*
* @{
*/
/**
* @brief Physically move memory, with copy
*
* This maps a region of physical memory into the new virtual address space
* (@p virt_new), and copy region of size @p size from the old virtual
* address space (@p virt_old). The new virtual memory region is mapped
* from physical memory starting at @p phys_new of size @p size.
*
* Behavior when providing unaligned addresses/sizes is undefined, these
* are assumed to be page aligned.
*
* Note that the virtual memory at both the old and new addresses
* must be unmapped in the memory domains of any runnable Zephyr
* thread as this does not deal with memory domains.
*
* Note that overlapping of old and new virtual memory regions
* is usually not supported for simpler implementation. Refer to
* the actual driver to make sure if overlapping is allowed.
*
* @param virt_old Page-aligned base virtual address of existing memory
* @param size Page-aligned size of the mapped memory region in bytes
* @param virt_new Page-aligned base virtual address to which to map
* new physical pages
* @param phys_new Page-aligned base physical address to contain
* the moved memory
*
* @retval 0 if successful
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if old virtual addresses are not all mapped or
* new virtual addresses are not all unmapped
*/
int sys_mm_drv_move_region(void *virt_old, size_t size, void *virt_new,
uintptr_t phys_new);
/**
* @brief Physically move memory, with copy
*
* This maps a region of physical memory into the new virtual address space
* (@p virt_new), and copy region of size @p size from the old virtual
* address space (@p virt_old). The new virtual memory region is mapped
* from an array of physical pages.
*
* Behavior when providing unaligned addresses/sizes is undefined, these
* are assumed to be page aligned.
*
* Note that the virtual memory at both the old and new addresses
* must be unmapped in the memory domains of any runnable Zephyr
* thread as this does not deal with memory domains.
*
* Note that overlapping of old and new virtual memory regions
* is usually not supported for simpler implementation. Refer to
* the actual driver to make sure if overlapping is allowed.
*
* @param virt_old Page-aligned base virtual address of existing memory
* @param size Page-aligned size of the mapped memory region in bytes
* @param virt_new Page-aligned base virtual address to which to map
* new physical pages
* @param phys_new Array of page-aligned physical address to contain
* the moved memory
* @param phys_cnt Number of elements in the physical page array
*
* @retval 0 if successful
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if old virtual addresses are not all mapped or
* new virtual addresses are not all unmapped
*/
int sys_mm_drv_move_array(void *virt_old, size_t size, void *virt_new,
uintptr_t *phys_new, size_t phys_cnt);
/**
* @}
*/
/**
* @name Memory Mapping Attributes
*
* On manipulating attributes of already mapped memory.
*
* @{
*/
/**
* @brief Update memory page flags
*
* This changes the attributes of physical memory page which is already
* mapped to a virtual address. This is useful when use case of
* specific memory region changes.
* E.g. when the library/module code is copied to the memory then
* it needs to be read-write and after it has already
* been copied and library/module code is ready to be executed then
* attributes need to be changed to read-only/executable.
* Calling this API must not cause losing memory contents.
*
* @param virt Page-aligned virtual address to be updated
* @param flags Caching, access and control flags, see SYS_MM_MEM_* macros
*
* @retval 0 if successful
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if virtual addresses is not mapped
*/
int sys_mm_drv_update_page_flags(void *virt, uint32_t flags);
/**
* @brief Update memory region flags
*
* This changes the attributes of physical memory which is already
* mapped to a virtual address. This is useful when use case of
* specific memory region changes.
* E.g. when the library/module code is copied to the memory then
* it needs to be read-write and after it has already
* been copied and library/module code is ready to be executed then
* attributes need to be changed to read-only/executable.
* Calling this API must not cause losing memory contents.
*
* @param virt Page-aligned virtual address to be updated
* @param size Page-aligned size of the mapped memory region in bytes
* @param flags Caching, access and control flags, see SYS_MM_MEM_* macros
*
* @retval 0 if successful
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if virtual addresses is not mapped
*/
int sys_mm_drv_update_region_flags(void *virt, size_t size, uint32_t flags);
/**
* @}
*/
/**
* @name Memory Mappings Query
*
* On querying information on memory mappings.
*
* @{
*/
/**
* @brief Get the mapped physical memory address from virtual address.
*
* The function queries the translation tables to find the physical
* memory address of a mapped virtual address.
*
* Behavior when providing unaligned address is undefined, this
* is assumed to be page aligned.
*
* @param virt Page-aligned virtual address
* @param[out] phys Mapped physical address (can be NULL if only checking
* if virtual address is mapped)
*
* @retval 0 if mapping is found and valid
* @retval -EINVAL if invalid arguments are provided
* @retval -EFAULT if virtual address is not mapped
*/
int sys_mm_drv_page_phys_get(void *virt, uintptr_t *phys);
/**
* @brief Represents an available memory region.
*
* A memory region that can be used by allocators. Driver defined
* attributes can be used to guide the proper usage of each region.
*/
struct sys_mm_drv_region {
void *addr; /**< @brief Address of the memory region */
size_t size; /**< @brief Size of the memory region */
uint32_t attr; /**< @brief Driver defined attributes of the memory region */
};
/* TODO is it safe to assume no valid region has size == 0? */
/**
* @brief Iterates over an array of regions returned by #sys_mm_drv_query_memory_regions
*
* Note that a sentinel item marking the end of the array is expected for
* this macro to work.
*/
#define SYS_MM_DRV_MEMORY_REGION_FOREACH(regions, iter) \
for (iter = regions; iter->size; iter++)
/**
* @brief Query available memory regions
*
* Returns an array of available memory regions. One can iterate over
* the array using #SYS_MM_DRV_MEMORY_REGION_FOREACH. Note that the last
* item of the array is a sentinel marking the end, and it's identified
* by it's size attribute, which is zero.
*
* @retval regions A possibly empty array - i.e. containing only the sentinel
* marking at the end - of memory regions.
*/
const struct sys_mm_drv_region *sys_mm_drv_query_memory_regions(void);
/**
* @brief Free the memory array returned by #sys_mm_drv_query_memory_regions
*
* The driver may have dynamically allocated the memory for the array of
* regions returned by #sys_mm_drv_query_memory_regions. This method provides
* it the opportunity to free any related resources.
*
* @param regions Array of regions previously returned by
* #sys_mm_drv_query_memory_regions
*/
void sys_mm_drv_query_memory_regions_free(const struct sys_mm_drv_region *regions);
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* _ASMLANGUAGE */
#endif /* ZEPHYR_INCLUDE_DRIVERS_SYSTEM_MM_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/mm/system_mm.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 3,329 |
```objective-c
/*
*
*/
/**
* @file
* @brief Memory Banks Driver APIs
*
* This contains generic APIs to be used by a system-wide memory management
* driver to track page usage within memory banks.
*
* @note The caller of these functions needs to ensure proper locking
* to protect the data when using these APIs.
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_MM_DRV_BANK_H
#define ZEPHYR_INCLUDE_DRIVERS_MM_DRV_BANK_H
#include <zephyr/kernel.h>
#include <zephyr/sys/mem_stats.h>
#include <stdint.h>
/**
* @brief Memory Banks Driver APIs
* @defgroup mm_drv_bank_apis Memory Banks Driver APIs
*
* This contains APIs for a system-wide memory management driver to
* track page usage within memory banks.
*
* @note The caller of these functions needs to ensure proper locking
* to protect the data when using these APIs.
*
* @ingroup memory_management
* @{
*/
/**
* @brief Information about memory banks.
*/
struct sys_mm_drv_bank {
/** Number of unmapped pages. */
uint32_t unmapped_pages;
/** Number of mapped pages. */
uint32_t mapped_pages;
/** Maximum number of mapped pages since last counter reset. */
uint32_t max_mapped_pages;
};
/**
* @brief Initialize a memory bank's data structure
*
* The driver may wish to track various information about the memory banks
* that it uses. This routine will initialize a generic structure containing
* that information. Since at the power on all memory banks are switched on
* it will start with all pages mapped. In next phase of driver initialization
* unused pages will be unmapped.
*
* @param[in,out] bank Pointer to the memory bank structure used for tracking
* @param[in] bank_pages Number of pages in the memory bank
*/
void sys_mm_drv_bank_init(struct sys_mm_drv_bank *bank, uint32_t bank_pages);
/**
* @brief Track the mapping of a page in the specified memory bank
*
* This function is used to update the number of mapped pages within the
* specified memory bank.
*
* @param[in,out] bank Pointer to the memory bank's data structure
*
* @return The number of pages mapped within the memory bank
*/
uint32_t sys_mm_drv_bank_page_mapped(struct sys_mm_drv_bank *bank);
/**
* @brief Track the unmapping of a page in the specified memory bank
*
* This function is used to update the number of unmapped pages within the
* specified memory bank.
*
* @param[in,out] bank Pointer to the memory bank's data structure
*
* @return The number of unmapped pages within the memory bank
*/
uint32_t sys_mm_drv_bank_page_unmapped(struct sys_mm_drv_bank *bank);
/**
* @brief Reset the max number of pages mapped in the bank
*
* This routine is used to reset the maximum number of pages mapped in
* the specified memory bank to the current number of pages mapped in
* that memory bank.
*
* @param[in,out] bank Pointer to the memory bank's data structure
*/
void sys_mm_drv_bank_stats_reset_max(struct sys_mm_drv_bank *bank);
/**
* @brief Retrieve the memory usage stats for the specified memory bank
*
* This routine extracts the system memory stats from the memory bank.
*
* @param[in] bank Pointer to the memory bank's data structure
* @param[in,out] stats Pointer to memory into which to copy the system memory stats
*/
void sys_mm_drv_bank_stats_get(struct sys_mm_drv_bank *bank,
struct sys_memory_stats *stats);
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_DRIVERS_MM_DRV_BANK_H */
``` | /content/code_sandbox/include/zephyr/drivers/mm/mm_drv_bank.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 772 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_VIRTUALIZATION_IVSHMEM_H_
#define ZEPHYR_INCLUDE_DRIVERS_VIRTUALIZATION_IVSHMEM_H_
/**
* @brief Inter-VM Shared Memory (ivshmem) reference API
* @defgroup ivshmem Inter-VM Shared Memory (ivshmem) reference API
* @ingroup io_interfaces
* @{
*/
#include <zephyr/types.h>
#include <stddef.h>
#include <zephyr/device.h>
#include <zephyr/kernel.h>
#ifdef __cplusplus
extern "C" {
#endif
#define IVSHMEM_V2_PROTO_UNDEFINED 0x0000
#define IVSHMEM_V2_PROTO_NET 0x0001
typedef size_t (*ivshmem_get_mem_f)(const struct device *dev,
uintptr_t *memmap);
typedef uint32_t (*ivshmem_get_id_f)(const struct device *dev);
typedef uint16_t (*ivshmem_get_vectors_f)(const struct device *dev);
typedef int (*ivshmem_int_peer_f)(const struct device *dev,
uint32_t peer_id, uint16_t vector);
typedef int (*ivshmem_register_handler_f)(const struct device *dev,
struct k_poll_signal *signal,
uint16_t vector);
#ifdef CONFIG_IVSHMEM_V2
typedef size_t (*ivshmem_get_rw_mem_section_f)(const struct device *dev,
uintptr_t *memmap);
typedef size_t (*ivshmem_get_output_mem_section_f)(const struct device *dev,
uint32_t peer_id,
uintptr_t *memmap);
typedef uint32_t (*ivshmem_get_state_f)(const struct device *dev,
uint32_t peer_id);
typedef int (*ivshmem_set_state_f)(const struct device *dev,
uint32_t state);
typedef uint32_t (*ivshmem_get_max_peers_f)(const struct device *dev);
typedef uint16_t (*ivshmem_get_protocol_f)(const struct device *dev);
typedef int (*ivshmem_enable_interrupts_f)(const struct device *dev,
bool enable);
#endif /* CONFIG_IVSHMEM_V2 */
__subsystem struct ivshmem_driver_api {
ivshmem_get_mem_f get_mem;
ivshmem_get_id_f get_id;
ivshmem_get_vectors_f get_vectors;
ivshmem_int_peer_f int_peer;
ivshmem_register_handler_f register_handler;
#ifdef CONFIG_IVSHMEM_V2
ivshmem_get_rw_mem_section_f get_rw_mem_section;
ivshmem_get_output_mem_section_f get_output_mem_section;
ivshmem_get_state_f get_state;
ivshmem_set_state_f set_state;
ivshmem_get_max_peers_f get_max_peers;
ivshmem_get_protocol_f get_protocol;
ivshmem_enable_interrupts_f enable_interrupts;
#endif
};
/**
* @brief Get the inter-VM shared memory
*
* Note: This API is not supported for ivshmem-v2, as
* the R/W and R/O areas may not be mapped contiguously.
* For ivshmem-v2, use the ivshmem_get_rw_mem_section,
* ivshmem_get_output_mem_section and ivshmem_get_state
* APIs to access the shared memory.
*
* @param dev Pointer to the device structure for the driver instance
* @param memmap A pointer to fill in with the memory address
*
* @return the size of the memory mapped, or 0
*/
__syscall size_t ivshmem_get_mem(const struct device *dev,
uintptr_t *memmap);
static inline size_t z_impl_ivshmem_get_mem(const struct device *dev,
uintptr_t *memmap)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->get_mem(dev, memmap);
}
/**
* @brief Get our VM ID
*
* @param dev Pointer to the device structure for the driver instance
*
* @return our VM ID or 0 if we are not running on doorbell version
*/
__syscall uint32_t ivshmem_get_id(const struct device *dev);
static inline uint32_t z_impl_ivshmem_get_id(const struct device *dev)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->get_id(dev);
}
/**
* @brief Get the number of interrupt vectors we can use
*
* @param dev Pointer to the device structure for the driver instance
*
* @return the number of available interrupt vectors
*/
__syscall uint16_t ivshmem_get_vectors(const struct device *dev);
static inline uint16_t z_impl_ivshmem_get_vectors(const struct device *dev)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->get_vectors(dev);
}
/**
* @brief Interrupt another VM
*
* @param dev Pointer to the device structure for the driver instance
* @param peer_id The VM ID to interrupt
* @param vector The interrupt vector to use
*
* @return 0 on success, a negative errno otherwise
*/
__syscall int ivshmem_int_peer(const struct device *dev,
uint32_t peer_id, uint16_t vector);
static inline int z_impl_ivshmem_int_peer(const struct device *dev,
uint32_t peer_id, uint16_t vector)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->int_peer(dev, peer_id, vector);
}
/**
* @brief Register a vector notification (interrupt) handler
*
* @param dev Pointer to the device structure for the driver instance
* @param signal A pointer to a valid and ready to be signaled
* struct k_poll_signal. Or NULL to unregister any handler
* registered for the given vector.
* @param vector The interrupt vector to get notification from
*
* Note: The returned status, if positive, to a raised signal is the vector
* that generated the signal. This lets the possibility to the user
* to have one signal for all vectors, or one per-vector.
*
* @return 0 on success, a negative errno otherwise
*/
__syscall int ivshmem_register_handler(const struct device *dev,
struct k_poll_signal *signal,
uint16_t vector);
static inline int z_impl_ivshmem_register_handler(const struct device *dev,
struct k_poll_signal *signal,
uint16_t vector)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->register_handler(dev, signal, vector);
}
#ifdef CONFIG_IVSHMEM_V2
/**
* @brief Get the ivshmem read/write section (ivshmem-v2 only)
*
* @param dev Pointer to the device structure for the driver instance
* @param memmap A pointer to fill in with the memory address
*
* @return the size of the memory mapped, or 0
*/
__syscall size_t ivshmem_get_rw_mem_section(const struct device *dev,
uintptr_t *memmap);
static inline size_t z_impl_ivshmem_get_rw_mem_section(const struct device *dev,
uintptr_t *memmap)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->get_rw_mem_section(dev, memmap);
}
/**
* @brief Get the ivshmem output section for a peer (ivshmem-v2 only)
*
* @param dev Pointer to the device structure for the driver instance
* @param peer_id The VM ID whose output memory section to get
* @param memmap A pointer to fill in with the memory address
*
* @return the size of the memory mapped, or 0
*/
__syscall size_t ivshmem_get_output_mem_section(const struct device *dev,
uint32_t peer_id,
uintptr_t *memmap);
static inline size_t z_impl_ivshmem_get_output_mem_section(const struct device *dev,
uint32_t peer_id,
uintptr_t *memmap)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->get_output_mem_section(dev, peer_id, memmap);
}
/**
* @brief Get the state value of a peer (ivshmem-v2 only)
*
* @param dev Pointer to the device structure for the driver instance
* @param peer_id The VM ID whose state to get
*
* @return the state value of the peer
*/
__syscall uint32_t ivshmem_get_state(const struct device *dev,
uint32_t peer_id);
static inline uint32_t z_impl_ivshmem_get_state(const struct device *dev,
uint32_t peer_id)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->get_state(dev, peer_id);
}
/**
* @brief Set our state (ivshmem-v2 only)
*
* @param dev Pointer to the device structure for the driver instance
* @param state The state value to set
*
* @return 0 on success, a negative errno otherwise
*/
__syscall int ivshmem_set_state(const struct device *dev,
uint32_t state);
static inline int z_impl_ivshmem_set_state(const struct device *dev,
uint32_t state)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->set_state(dev, state);
}
/**
* @brief Get the maximum number of peers supported (ivshmem-v2 only)
*
* @param dev Pointer to the device structure for the driver instance
*
* @return the maximum number of peers supported, or 0
*/
__syscall uint32_t ivshmem_get_max_peers(const struct device *dev);
static inline uint32_t z_impl_ivshmem_get_max_peers(const struct device *dev)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->get_max_peers(dev);
}
/**
* @brief Get the protocol used by this ivshmem instance (ivshmem-v2 only)
*
* @param dev Pointer to the device structure for the driver instance
*
* @return the protocol
*/
__syscall uint16_t ivshmem_get_protocol(const struct device *dev);
static inline uint16_t z_impl_ivshmem_get_protocol(const struct device *dev)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->get_protocol(dev);
}
/**
* @brief Set the interrupt enablement for our VM (ivshmem-v2 only)
*
* @param dev Pointer to the device structure for the driver instance
* @param enable True to enable interrupts, false to disable
*
* @return 0 on success, a negative errno otherwise
*/
__syscall int ivshmem_enable_interrupts(const struct device *dev,
bool enable);
static inline int z_impl_ivshmem_enable_interrupts(const struct device *dev,
bool enable)
{
const struct ivshmem_driver_api *api =
(const struct ivshmem_driver_api *)dev->api;
return api->enable_interrupts(dev, enable);
}
#endif /* CONFIG_IVSHMEM_V2 */
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <zephyr/syscalls/ivshmem.h>
#endif /* ZEPHYR_INCLUDE_DRIVERS_VIRTUALIZATION_IVSHMEM_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/virtualization/ivshmem.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,477 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CAN_TRANSCEIVER_H_
#define ZEPHYR_INCLUDE_DRIVERS_CAN_TRANSCEIVER_H_
#include <zephyr/drivers/can.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief CAN Transceiver Driver APIs
* @defgroup can_transceiver CAN Transceiver
* @since 3.1
* @version 0.1.0
* @ingroup io_interfaces
* @{
*/
/**
* @cond INTERNAL_HIDDEN
*
* For internal driver use only, skip these in public documentation.
*/
/**
* @brief Callback API upon enabling CAN transceiver
* See @a can_transceiver_enable() for argument description
*/
typedef int (*can_transceiver_enable_t)(const struct device *dev, can_mode_t mode);
/**
* @brief Callback API upon disabling CAN transceiver
* See @a can_transceiver_disable() for argument description
*/
typedef int (*can_transceiver_disable_t)(const struct device *dev);
__subsystem struct can_transceiver_driver_api {
can_transceiver_enable_t enable;
can_transceiver_disable_t disable;
};
/** @endcond */
/**
* @brief Enable CAN transceiver
*
* Enable the CAN transceiver.
*
* @note The CAN transceiver is controlled by the CAN controller driver and
* should not normally be controlled by the application.
*
* @see can_start()
*
* @param dev Pointer to the device structure for the driver instance.
* @param mode Operation mode.
* @retval 0 If successful.
* @retval -EIO General input/output error, failed to enable device.
*/
static inline int can_transceiver_enable(const struct device *dev, can_mode_t mode)
{
const struct can_transceiver_driver_api *api =
(const struct can_transceiver_driver_api *)dev->api;
return api->enable(dev, mode);
}
/**
* @brief Disable CAN transceiver
*
* Disable the CAN transceiver.
* @note The CAN transceiver is controlled by the CAN controller driver and
* should not normally be controlled by the application.
*
* @see can_stop()
*
* @param dev Pointer to the device structure for the driver instance.
* @retval 0 If successful.
* @retval -EIO General input/output error, failed to disable device.
*/
static inline int can_transceiver_disable(const struct device *dev)
{
const struct can_transceiver_driver_api *api =
(const struct can_transceiver_driver_api *)dev->api;
return api->disable(dev);
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_CAN_TRANSCEIVER_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/can/transceiver.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 562 |
```objective-c
/*
*
*/
#ifndef ZEPHYR_INCLUDE_DRIVERS_CAN_CAN_FAKE_H_
#define ZEPHYR_INCLUDE_DRIVERS_CAN_CAN_FAKE_H_
#include <zephyr/drivers/can.h>
#include <zephyr/fff.h>
#ifdef __cplusplus
extern "C" {
#endif
DECLARE_FAKE_VALUE_FUNC(int, fake_can_start, const struct device *);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_stop, const struct device *);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_set_timing, const struct device *, const struct can_timing *);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_set_timing_data, const struct device *,
const struct can_timing *);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_get_capabilities, const struct device *, can_mode_t *);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_set_mode, const struct device *, can_mode_t);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_send, const struct device *, const struct can_frame *,
k_timeout_t, can_tx_callback_t, void *);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_add_rx_filter, const struct device *, can_rx_callback_t,
void *, const struct can_filter *);
DECLARE_FAKE_VOID_FUNC(fake_can_remove_rx_filter, const struct device *, int);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_recover, const struct device *, k_timeout_t);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_get_state, const struct device *, enum can_state *,
struct can_bus_err_cnt *);
DECLARE_FAKE_VOID_FUNC(fake_can_set_state_change_callback, const struct device *,
can_state_change_callback_t, void *);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_get_max_filters, const struct device *, bool);
DECLARE_FAKE_VALUE_FUNC(int, fake_can_get_core_clock, const struct device *, uint32_t *);
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_CAN_CAN_FAKE_H_ */
``` | /content/code_sandbox/include/zephyr/drivers/can/can_fake.h | objective-c | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 390 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.